qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
143,745
|
<p>One thing that's really been making life difficult in getting up to speed on the codebase on an ASP classic project is that the include file situation is kind of a mess. I sometimes find the function I was looking for being included in an include file that is totally unrelated. Does anyone have any advice on how to refactor this such that one can more easily tell where a function is if they need to find it?</p>
<p><strong>EDIT:</strong> One thing I forgot to ask: does vbscript have any kind of mechanism for preventing a file from being included twice? Sorta like #ifndef's from C?</p>
|
[
{
"answer_id": 148124,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 2,
"selected": false,
"text": "initialise.asp lib_http.asp lib_mssql.asp '..\\'"
},
{
"answer_id": 148366,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 2,
"selected": false,
"text": "<%@ Language=VBScript %>\n<% Option Explicit %>\n<% Response.Buffer = true%>\n<html>\n<head>\n<!--#include file=\"../general/t-head.asp\"-->\n<!--#include file=\"../bus/product.asp\"-->\n<title>Products page</title>\n</head>\n<body>\n<!--#include file=\"../general/t-begin.asp\"-->\n\n <% 'all your code %>\n\n<!--#include file=\"../general/t-end.asp\"--> \n</body>\n</html>\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
143,746
|
<p>I know most people think that as a <em>bad practice</em> but when you are trying to make your class public interface only work with references, keeping pointers inside and only when necessary, I think there is no way to return something telling that the value you are looking doesn't exist in the container.</p>
<pre>
class list {
public:
value &get(type key);
};
</pre>
<p>Let's think that you don't want to have dangerous pointers being saw in the public interface of the class, how do you return a not found in this case, throwing an exception?</p>
<p>What is your approach to that? Do you return an empty <em>value</em> and check for the empty state of it? I actually use the throw approach but I introduce a checking method:</p>
<pre>
class list {
public:
bool exists(type key);
value &get(type key);
};
</pre>
<p>So when I forget to check that the value exists first I get an exception, that is really an <em>exception</em>.</p>
<p>How would you do it?</p>
|
[
{
"answer_id": 143758,
"author": "MidnightGun",
"author_id": 13220,
"author_profile": "https://Stackoverflow.com/users/13220",
"pm_score": -1,
"selected": false,
"text": "MyType *pObj = nullptr;\nreturn *pObj\n"
},
{
"answer_id": 143782,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 4,
"selected": false,
"text": "iterator find( const key_type& key );\n"
},
{
"answer_id": 143799,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "typedef std::pair<bool, yourvalue> pair"
},
{
"answer_id": 144239,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "T & std::vector::operator[]( /* index */ )\n T & std::vector::at( /* index */ )\n [] at [] at // If you want your user to have this kind of code, then choose either\n// pointer or smart pointer solution\nvoid doSomething(MyClass & p_oMyClass)\n{\n MyValue * pValue = p_oMyClass.getValue() ;\n \n if(pValue != NULL)\n {\n // Etc.\n }\n}\n\nMyValue * doSomethingElseAndReturnValue(MyClass & p_oMyClass)\n{\n MyValue * pValue = p_oMyClass.getValue() ;\n \n if(pValue != NULL)\n {\n // Etc.\n }\n\n return pValue ;\n}\n\n// ==========================================================\n\n// If you want your user to have this kind of code, then choose the\n// throwing reference solution\nvoid doSomething(MyClass & p_oMyClass)\n{\n if(p_oMyClass.hasValue())\n {\n MyValue & oValue = p_oMyClass.getValue() ;\n }\n}\n"
},
{
"answer_id": 144501,
"author": "Roman Odaisky",
"author_id": 21055,
"author_profile": "https://Stackoverflow.com/users/21055",
"pm_score": 3,
"selected": false,
"text": "Optional boost::optional<X> get_X_if_possible();\n enforce template <class T, class E>\nT& enforce(boost::optional<T>& opt, E e = std::runtime_error(\"enforce failed\"))\n{\n if(!opt)\n {\n throw e;\n }\n\n return *opt;\n}\n\n// and an overload for T const &\n if(boost::optional<X> maybe_x = get_X_if_possible())\n{\n X& x = *maybe_x;\n\n // use x\n}\nelse\n{\n oops(\"Hey, we got no x again!\");\n}\n X& x = enforce(get_X_if_possible());\n\n// use x\n"
},
{
"answer_id": 144524,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 0,
"selected": false,
"text": "// 'reference' style, check before use\nif (Accessor<type> value = list.get(key)) {\n type &v = value;\n v.doSomething();\n}\n// or\nif (Accessor<type> value = list.get(key)) {\n static_cast<type&>(value).doSomething();\n}\n // 'reference' style, skip check \ntype &v = list.get(key);\nv.doSomething();\n// or\nstatic_cast<type&>(list.get(key)).doSomething();\n // 'pointer' style, check before use\nif (Accessor<type> value = list.get(key)) {\n value->doSomething();\n}\n\n// 'pointer' style, skip check \nlist.get(key)->doSomething();\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623/"
] |
143,747
|
<p>I'm writing some JavaScript code that needs to fire the <code>click</code> event for a link. In Internet Explorer I can do this </p>
<pre><code>var button = document.getElementById('myButton');
button.click();
</code></pre>
<p>But this doesn't work in Firefox, and I assume any other browser. In Firefox, I've done this </p>
<pre><code>var button = document.getElementById('myButton');
window.location = button.href;
</code></pre>
<p>I feel like this is not the best way to do this. Is there a better way to trigger a <code>click</code> event? Preferably something that works regardless of the type of element or the browser.</p>
|
[
{
"answer_id": 143771,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 6,
"selected": false,
"text": "function fireEvent(element,event) {\n if (document.createEvent) {\n // dispatch for firefox + others\n var evt = document.createEvent(\"HTMLEvents\");\n evt.initEvent(event, true, true ); // event type,bubbling,cancelable\n return !element.dispatchEvent(evt);\n } else {\n // dispatch for IE\n var evt = document.createEventObject();\n return element.fireEvent('on'+event,evt)\n }\n}\n"
},
{
"answer_id": 145370,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 2,
"selected": false,
"text": "<a id=\"my-link\" href=\"#\" onclick=\"alert('Hello world');\">My link</a>\n\ndocument.getElementById('my-link').onclick();\n"
},
{
"answer_id": 1435344,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<a class=\"navlink\" href=\"mypage.html\">Online Estimate</a>\n $(\".pagelink\").click(function(){\n $(\".navlink[href=\"+$(this).attr(\"href\")+\"]\").trigger('click');\n return false;\n});\n <a class=\"pagelink\" href=\"mypage.html\">Online Estimate</a>\n"
},
{
"answer_id": 3593165,
"author": "Achshar",
"author_id": 433905,
"author_profile": "https://Stackoverflow.com/users/433905",
"pm_score": -1,
"selected": false,
"text": "document.getElementById('foo').onclick();\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
143,756
|
<p>I need to rename the database but when I do in
<code>PGAdmin : ALTER DATABASE "databaseName" RENAME TO "databaseNameOld"</code> it told me that it cannot.</p>
<p>How can I do it?</p>
<p>(<strong>Version 8.3 on WindowsXP</strong>)</p>
<p><strong>Update</strong></p>
<ul>
<li><p>The first error message : Cannot because I was connect to it. So I selected an other database and did the queries.</p></li>
<li><p>I get a second error message telling me that it has come user connect. I see in the <code>PGAdmin</code> screen that it has many <code>PID</code> but they are inactive... I do not see how to kill them.</p></li>
</ul>
|
[
{
"answer_id": 143764,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 8,
"selected": false,
"text": "ALTER DATABASE people RENAME TO customers;\n"
},
{
"answer_id": 143852,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": 2,
"selected": false,
"text": "pg_cancel_backend()"
},
{
"answer_id": 7678959,
"author": "gsiems",
"author_id": 642201,
"author_profile": "https://Stackoverflow.com/users/642201",
"pm_score": 7,
"selected": false,
"text": "-- disconnect from the database to be renamed\n\\c postgres\n\n-- force disconnect all other clients from the database to be renamed\nSELECT pg_terminate_backend( pid )\nFROM pg_stat_activity\nWHERE pid <> pg_backend_pid( )\n AND datname = 'name of database';\n\n-- rename the database (it should now have zero clients)\nALTER DATABASE \"name of database\" RENAME TO \"new name of database\";\n pg_stat_activity pid procpid procpid pid"
},
{
"answer_id": 18430601,
"author": "smoore4",
"author_id": 1143681,
"author_profile": "https://Stackoverflow.com/users/1143681",
"pm_score": 3,
"selected": false,
"text": "pgAdmin psql pgBouncer"
},
{
"answer_id": 60557872,
"author": "rovyko",
"author_id": 3769464,
"author_profile": "https://Stackoverflow.com/users/3769464",
"pm_score": 0,
"selected": false,
"text": "ERROR: database \"my_stubborn_db\" is being accessed by other users\n Detail: There is 1 other session using the database.\n"
},
{
"answer_id": 66951818,
"author": "Valsaraj Viswanathan",
"author_id": 2581174,
"author_profile": "https://Stackoverflow.com/users/2581174",
"pm_score": 1,
"selected": false,
"text": "ALTER DATABASE postgres RENAME TO pgnew;\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
143,791
|
<p>I have a system (Ubuntu) with many processes and one (or more) have a memory leak. Is there a good way to find the process that has the leak? Some of the process are JVMs, some are not. Some are home grown some are open source.</p>
|
[
{
"answer_id": 143809,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": false,
"text": "top top -b -n 1"
},
{
"answer_id": 147322,
"author": "Dprado",
"author_id": 21943,
"author_profile": "https://Stackoverflow.com/users/21943",
"pm_score": 3,
"selected": false,
"text": "while true\ndo\necho \"---------------------------------\" >> /tmp/mem_usage\ndate >> /tmp/mem_usage\nps aux >> /tmp/mem_usage\nsleep 60\ndone\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
143,793
|
<p>According to this article <a href="http://msdn.microsoft.com/en-us/library/cc197951(VS.95).aspx" rel="nofollow noreferrer">Silverlight 2 Beta 2</a> supports the <code>DataContractJsonSerializer</code> object. But, when I try to use it VS says </p>
<blockquote>
<p>"Type 'DataContractJsonSerializer' is not defined".</p>
</blockquote>
<p>I have a method marked as ScriptableMember that gets called from JavaScript and is passed an Object. Inside this method I need to serialize the object to a string (preferably JSON) and then save it in isolated storage.</p>
<p>Does Silverlight 2 Beta 2 really support DataContractJsonSerializer? Or would anyone recommend a different method of saving the JavaScript created ScriptObject in the Isolated Storage?</p>
|
[
{
"answer_id": 143824,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 1,
"selected": false,
"text": "Sys.Serialization.JavaScriptSerializer.serialize(obj);\nSys.Serialization.JavaScriptSerializer.deserialize(json);\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
] |
143,808
|
<p>We have fairly large C++ application which is composed of about 60 projects in Visual Studio 2005. It currently takes 7 minutes to link in Release mode and I would like to try to reduce the time. Are there any tips for improving the link time?</p>
<p>Most of the projects compile to static libraries, this makes testing easier since each one also has a set of associated unit tests. It seems the use of static libraries prevents VS2005 from using incremental linking, so even with incremental linking turned on it does a full link every time.</p>
<p>Would using DLLs for the sub projects make any difference? I don't really want to go through all the headers and add macros to export the symbols (even using a script) but if it would do something to reduce the 7 minute link time I will certainly consider it.</p>
<p>For some reason using nmake from the command line is slightly faster and linking the same application on Linux (with GCC) is much faster.</p>
<ul>
<li>Visual Studio IDE 7 minutes</li>
<li>Visual C++ using nmake from the command line - 5 minutes</li>
<li>GCC on Linux 34 seconds</li>
</ul>
|
[
{
"answer_id": 145386,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 5,
"selected": true,
"text": "/GL /LTCG /Z7 .obj /Zi .pdb"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5022/"
] |
143,814
|
<p>In an ideal world, our development processes would be perfect, resulting in regular releases that were so thoroughly tested that it would never be necessary to "hotfix" a running application.</p>
<p>But, unfortunately, we live in the real world, and sometimes bugs slip past us and don't rear their ugly heads until we're already busy coding away at the next release. And the bug needs to be fixed <strong><em>Now</em></strong>. Not as a part of the next scheduled release. Not tonight when the traffic dies down. <strong><em>Now</em></strong>.</p>
<p>How do you deal with this need? It really can run counter to good design practices, like refactoring your code into nice, discrete class libraries.</p>
<p>Hand-editing markup and stored procedures on a production server can be a recipe for disaster, but it can also avert disaster.</p>
<p>What are some good strategies for application design and deployment techniques to find a balance between maintenance needs and good coding practices?</p>
|
[
{
"answer_id": 143851,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "/repo/trunk/\n/repo/tags/1.1\n/repo/tags/1.2\n/repo/tags/1.3\n tags/x svn update tags/x trunk"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] |
143,815
|
<p>Can I use JavaScript to check (irrespective of scrollbars) if an HTML element has overflowed its content? For example, a long div with small, fixed size, the overflow property set to visible, and no scrollbars on the element.</p>
|
[
{
"answer_id": 143833,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 4,
"selected": false,
"text": "element.scrollHeight element.scrollWidth element.offsetHeight element.offsetWidth"
},
{
"answer_id": 143889,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 9,
"selected": true,
"text": "client[Height|Width] scroll[Height|Width] // Determines if the passed element is overflowing its bounds,\n// either vertically or horizontally.\n// Will temporarily modify the \"overflow\" style to detect this\n// if necessary.\nfunction checkOverflow(el)\n{\n var curOverflow = el.style.overflow;\n\n if ( !curOverflow || curOverflow === \"visible\" )\n el.style.overflow = \"hidden\";\n\n var isOverflowing = el.clientWidth < el.scrollWidth \n || el.clientHeight < el.scrollHeight;\n\n el.style.overflow = curOverflow;\n\n return isOverflowing;\n}\n"
},
{
"answer_id": 37425662,
"author": "Paul V",
"author_id": 945389,
"author_profile": "https://Stackoverflow.com/users/945389",
"pm_score": -1,
"selected": false,
"text": "while (elHeader.clientWidth < elHeader.scrollWidth || elHeader.clientHeight < elHeader.scrollHeight) {\n var f = parseInt(elHeader.getStyle('font-size'), 10);\n f--;\n elHeader.setStyle('font-size', f + 'px');\n}\n width:100%;\n font-size:40px;\n line-height:36px;\n font-family:Arial;\n text-align:center;\n max-height:36px;\n overflow:hidden;\n"
},
{
"answer_id": 56464302,
"author": "Agu Dondo",
"author_id": 936703,
"author_profile": "https://Stackoverflow.com/users/936703",
"pm_score": 1,
"selected": false,
"text": "if ( $(\".inner-element\").prop('scrollHeight') > $(\".inner-element\").height() ) {\n\n console.log(\"element is overflowing\");\n\n} else {\n\n console.log(\"element is not overflowing\");\n\n}\n .prop('scrollWidth') .width()"
},
{
"answer_id": 62272697,
"author": "Alisson Nunes",
"author_id": 4718937,
"author_profile": "https://Stackoverflow.com/users/4718937",
"pm_score": 3,
"selected": false,
"text": "function checkOverflow(elem) {\n const elemWidth = elem.getBoundingClientRect().width\n const parentWidth = elem.parentElement.getBoundingClientRect().width\n\n return elemWidth > parentWidth\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
143,822
|
<p>this wiki page gave a general idea of how to convert a single char to ascii <a href="http://en.wikibooks.org/wiki/Ruby_Programming/ASCII" rel="noreferrer">http://en.wikibooks.org/wiki/Ruby_Programming/ASCII</a></p>
<p>But say if I have a string and I wanted to get each character's ascii from it, what do i need to do?</p>
<pre><code>"string".each_byte do |c|
$char = c.chr
$ascii = ?char
puts $ascii
end
</code></pre>
<p>It doesn't work because it's not happy with the line $ascii = ?char</p>
<pre><code>syntax error, unexpected '?'
$ascii = ?char
^
</code></pre>
|
[
{
"answer_id": 143834,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": true,
"text": "c \"string\".each_byte do |c|\n puts c\nend\n 115\n116\n114\n105\n110\n103\n"
},
{
"answer_id": 1557734,
"author": "Mark",
"author_id": 137100,
"author_profile": "https://Stackoverflow.com/users/137100",
"pm_score": 2,
"selected": false,
"text": "\"a\"[0]\n ?a\n"
},
{
"answer_id": 9774098,
"author": "alexsuslin",
"author_id": 1167345,
"author_profile": "https://Stackoverflow.com/users/1167345",
"pm_score": 5,
"selected": false,
"text": "puts \"string\".split('').map(&:ord).to_s\n"
},
{
"answer_id": 31591016,
"author": "LastZactionHero",
"author_id": 1895150,
"author_profile": "https://Stackoverflow.com/users/1895150",
"pm_score": 4,
"selected": false,
"text": "codepoints str = 'hello world'\nstr.codepoints\n=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] \n\nstr = \"你好世界\"\nstr.codepoints\n=> [20320, 22909, 19990, 30028]\n"
},
{
"answer_id": 33700454,
"author": "nikkypx",
"author_id": 1395009,
"author_profile": "https://Stackoverflow.com/users/1395009",
"pm_score": 3,
"selected": false,
"text": "=> 'hello world'.each_byte.to_a\n=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n\n=> 'hello world'.bytes\n=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2668/"
] |
143,847
|
<p>What is the best way to find if an object is in an array?</p>
<p>This is the best way I know:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}
console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 143863,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 11,
"selected": true,
"text": "includes() arr.includes(obj);\n function include(arr,obj) {\n return (arr.indexOf(obj) != -1);\n}\n if (!Array.prototype.indexOf)\n {\n\n Array.prototype.indexOf = function(searchElement /*, fromIndex */)\n\n {\n\n\n \"use strict\";\n\n if (this === void 0 || this === null)\n throw new TypeError();\n\n var t = Object(this);\n var len = t.length >>> 0;\n if (len === 0)\n return -1;\n\n var n = 0;\n if (arguments.length > 0)\n {\n n = Number(arguments[1]);\n if (n !== n)\n n = 0;\n else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))\n n = (n > 0 || -1) * Math.floor(Math.abs(n));\n }\n\n if (n >= len)\n return -1;\n\n var k = n >= 0\n ? n\n : Math.max(len - Math.abs(n), 0);\n\n for (; k < len; k++)\n {\n if (k in t && t[k] === searchElement)\n return k;\n }\n return -1;\n };\n\n }\n if (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function (obj, fromIndex) {\n if (fromIndex == null) {\n fromIndex = 0;\n } else if (fromIndex < 0) {\n fromIndex = Math.max(0, this.length + fromIndex);\n }\n for (var i = fromIndex, j = this.length; i < j; i++) {\n if (this[i] === obj)\n return i;\n }\n return -1;\n };\n }\n Array.prototype.hasObject = (\n !Array.indexOf ? function (o)\n {\n var l = this.length + 1;\n while (l -= 1)\n {\n if (this[l - 1] === o)\n {\n return true;\n }\n }\n return false;\n } : function (o)\n {\n return (this.indexOf(o) !== -1);\n }\n );\n"
},
{
"answer_id": 143945,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "indexOf if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);\nelse result = customSlowerSearch(yourArray, target);\n indexOf return false;"
},
{
"answer_id": 144172,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 5,
"selected": false,
"text": "indexOf indexOf indexOf if (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function (obj, fromIndex) {\n if (fromIndex == null) {\n fromIndex = 0;\n } else if (fromIndex < 0) {\n fromIndex = Math.max(0, this.length + fromIndex);\n }\n for (var i = fromIndex, j = this.length; i < j; i++) {\n if (this[i] === obj)\n return i;\n }\n return -1;\n };\n}\n var include = Array.prototype.indexOf ?\n function(arr, obj) { return arr.indexOf(obj) !== -1; } :\n function(arr, obj) {\n for(var i = -1, j = arr.length; ++i < j;)\n if(arr[i] === obj) return true;\n return false;\n };\n"
},
{
"answer_id": 2527680,
"author": "Germán Rodríguez",
"author_id": 56748,
"author_profile": "https://Stackoverflow.com/users/56748",
"pm_score": 8,
"selected": false,
"text": "$.inArray(5 + 5, [ \"8\", \"9\", \"10\", 10 + \"\" ]);\n"
},
{
"answer_id": 7093224,
"author": "Aaria Carter-Weir",
"author_id": 647351,
"author_profile": "https://Stackoverflow.com/users/647351",
"pm_score": 3,
"selected": false,
"text": "utils = {} var utils = {};\n\n/**\n * utils.isArray\n *\n * Best guess if object is an array.\n */\nutils.isArray = function(obj) {\n // do an instanceof check first\n if (obj instanceof Array) {\n return true;\n }\n // then check for obvious falses\n if (typeof obj !== 'object') {\n return false;\n }\n if (utils.type(obj) === 'array') {\n return true;\n }\n return false;\n };\n\n/**\n * utils.type\n *\n * Attempt to ascertain actual object type.\n */\nutils.type = function(obj) {\n if (obj === null || typeof obj === 'undefined') {\n return String (obj);\n }\n return Object.prototype.toString.call(obj)\n .replace(/\\[object ([a-zA-Z]+)\\]/, '$1').toLowerCase();\n};\n /**\n * Adding hasOwnProperty method if needed.\n */\nif (typeof Object.prototype.hasOwnProperty !== 'function') {\n Object.prototype.hasOwnProperty = function (prop) {\n var type = utils.type(this);\n type = type.charAt(0).toUpperCase() + type.substr(1);\n return this[prop] !== undefined\n && this[prop] !== window[type].prototype[prop];\n };\n}\n function in_array (needle, haystack, strict) {\n var key;\n\n if (strict) {\n for (key in haystack) {\n if (!haystack.hasOwnProperty[key]) continue;\n\n if (haystack[key] === needle) {\n return true;\n }\n }\n } else {\n for (key in haystack) {\n if (!haystack.hasOwnProperty[key]) continue;\n\n if (haystack[key] == needle) {\n return true;\n }\n }\n }\n\n return false;\n}\n"
},
{
"answer_id": 9435838,
"author": "bortunac",
"author_id": 544803,
"author_profile": "https://Stackoverflow.com/users/544803",
"pm_score": 3,
"selected": false,
"text": ".indexOf() Object.defineProperty( Array.prototype,'has',\n{\n value:function(o, flag){\n if (flag === undefined) {\n return this.indexOf(o) !== -1;\n } else { // only for raw js object\n for(var v in this) {\n if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;\n }\n return false; \n },\n // writable:false,\n // enumerable:false\n})\n Array.prototype.has=function(){... //use like \n[22 ,'a', {prop:'x'}].has(12) // false\n[\"a\",\"b\"].has(\"a\") // true\n\n[1,{a:1}].has({a:1},1) // true\n[1,{a:1}].has({a:1}) // false\n [o1].has(o2,true) // true if every level value is same\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17533/"
] |
143,850
|
<p>let's say we have a c++ class like:</p>
<pre><code>class MyClass
{
void processArray( <an array of 255 integers> )
{
int i ;
for (i=0;i<255;i++)
{
// do something with values in the array
}
}
}
</code></pre>
<p>and one instance of the class like: </p>
<pre><code>MyClass myInstance ;
</code></pre>
<p>and 2 threads which call the processArray method of that instance (depending on how system executes threads, probably in a completely irregular order). There is no mutex lock used in that scope so both threads can enter.</p>
<p><strong>My question is what happens to the i ? Does each thread scope has it's own "i" or would each entering thread modify i in the for loop, causing i to be changing weirdly all the time.</strong> </p>
|
[
{
"answer_id": 143853,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": true,
"text": "i i"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23000/"
] |
143,855
|
<p>Do you use code-generation tools (aside from those used to generate proxies and from designers built-in to visual studio)? </p>
<p>What part(s) of your application do you generate? </p>
<p>Do you typically roll your own generator? If so, what type of generator do you write (asp templates, coddom etc.). If not, what 3rd party tools do you use?</p>
<p>I am currently working on a few different projects wich all use a custom code-generator that handles everything from generating the database structure, business entities, DAL, and BLL. I am curious about other peoples experiences are with these kinds of tools.</p>
|
[
{
"answer_id": 144177,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 3,
"selected": false,
"text": "<ActiveRecord(\"Kiwi\")> _\nClass CKiwi\nEnd Class\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17744/"
] |
143,872
|
<p>I am writing a data conversion in PL/SQL that processes data and loads it into a table. According to the PL/SQL Profiler, one of the slowest parts of the conversion is the actual insert into the target table. The table has a single index.</p>
<p>To prepare the data for load, I populate a variable using the rowtype of the table, then insert it into the table like this:</p>
<blockquote>
<p><code>insert into mytable values r_myRow;</code></p>
</blockquote>
<p>It seems that I could gain performance by doing the following:</p>
<ul>
<li>Turn logging off during the insert</li>
<li>Insert multiple records at once</li>
</ul>
<p>Are these methods advisable? If so, what is the syntax?</p>
|
[
{
"answer_id": 143946,
"author": "CaptainPicard",
"author_id": 15203,
"author_profile": "https://Stackoverflow.com/users/15203",
"pm_score": 5,
"selected": true,
"text": "INSERT /*+APPEND*/"
},
{
"answer_id": 13887303,
"author": "skk",
"author_id": 1905348,
"author_profile": "https://Stackoverflow.com/users/1905348",
"pm_score": 1,
"selected": false,
"text": "SQL>create table tablename(eid number, ename varchar2(20),sal number,job char(10));\n SQL>insert into tablename values(&eid,'&ename',&sal,'&job');\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625/"
] |
143,925
|
<p>I want to be able to run a single spec file's tests — for the one file I'm editing, for example. <code>rake spec</code> executes all the specs. My project is not a Rails project, so <code>rake spec:doc</code> doesn't work.</p>
<p>Don't know if this matters, but here is my directory structure.</p>
<pre>
./Rakefile
./lib
./lib/cushion.rb
./lib/cushion
./lib/cushion/doc.rb
./lib/cushion/db.rb
./spec
./spec/spec.opts
./spec/spec_helper.rb
./spec/db_spec.rb
</pre>
|
[
{
"answer_id": 144063,
"author": "Cameron Booth",
"author_id": 14873,
"author_profile": "https://Stackoverflow.com/users/14873",
"pm_score": 10,
"selected": true,
"text": "bundle exec rspec path/to/spec/file.rb\n bundle exec spec path/to/spec/file.rb\n"
},
{
"answer_id": 146612,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": false,
"text": "spec ruby myclass_spec.rb\n"
},
{
"answer_id": 1909419,
"author": "Zeke",
"author_id": 95670,
"author_profile": "https://Stackoverflow.com/users/95670",
"pm_score": 4,
"selected": false,
"text": "rake spec:user #run spec/model/user_spec.rb (searches for user*_spec.rb)\nrake test:users_c #run test/functional/users_controller_test.rb\nrake spec:user:token #run the first spec in user_spec.rb that matches /token/\nrake test:user:token #run all tests in user_test.rb that match /token/\nrake test:last\nrake spec:last\n"
},
{
"answer_id": 3501347,
"author": "boblin",
"author_id": 2190153,
"author_profile": "https://Stackoverflow.com/users/2190153",
"pm_score": 4,
"selected": false,
"text": "-l, --line LINE_NUMBER Execute example group or example at given line.\n (does not work for dynamically generated examples)\n"
},
{
"answer_id": 5658081,
"author": "joelparkerhenderson",
"author_id": 528726,
"author_profile": "https://Stackoverflow.com/users/528726",
"pm_score": 3,
"selected": false,
"text": "ruby rake -I spec spec/models/user_spec.rb"
},
{
"answer_id": 5679783,
"author": "tcurdt",
"author_id": 33165,
"author_profile": "https://Stackoverflow.com/users/33165",
"pm_score": 6,
"selected": false,
"text": "-e it \"shows the plane arrival time\"\n rspec path/to/spec/file.rb -e 'shows the plane arrival time'\n./scripts/spec path/to/spec/file.rb -e 'shows the plane arrival time'\n"
},
{
"answer_id": 11639611,
"author": "juanpaco",
"author_id": 322418,
"author_profile": "https://Stackoverflow.com/users/322418",
"pm_score": 7,
"selected": false,
"text": "rspec path/to/spec:<line number>\n 1: \n2: it \"should be awesome\" do\n3: foo = 3\n4: foo.should eq(3)\n5: end\n6:\n rspec spec/models/foo_spec.rb:2\n"
},
{
"answer_id": 27356175,
"author": "Prabhakar Undurthi",
"author_id": 2200417,
"author_profile": "https://Stackoverflow.com/users/2200417",
"pm_score": 2,
"selected": false,
"text": " rspec/spec/features/controller/spec_file_name.rb\n\n Example:\n\n Creating rspec spec/features/todos/create_spec.rb\n Editing rspec spec/features/todos/edit_spec.rb\n Deleting rspec spec/features/todos/destroy_spec.rb\n rspec \n rspec/spec/feaures/controller_name\n\n Example: rspec/spec/features/todos\n"
},
{
"answer_id": 43983110,
"author": "Victor BV",
"author_id": 2930272,
"author_profile": "https://Stackoverflow.com/users/2930272",
"pm_score": 3,
"selected": false,
"text": "tags it \"creates an user\", dev: :current do\n user = create(:user)\n expect(user.persisted?).to be_truthy\nend\n bundle exec rspec . --tag dev:current\n"
},
{
"answer_id": 47064184,
"author": "nflauria",
"author_id": 5656846,
"author_profile": "https://Stackoverflow.com/users/5656846",
"pm_score": 4,
"selected": false,
"text": "rspec rspec 'path_to/spec.rb' rspec 'path_to/spec.rb:7'"
},
{
"answer_id": 70170831,
"author": "Khaireddine Hamdi",
"author_id": 6430324,
"author_profile": "https://Stackoverflow.com/users/6430324",
"pm_score": -1,
"selected": false,
"text": "rspec spec/models/model_spec.rb:47\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12887/"
] |
143,933
|
<p>My side question is there really any difference between tinyblob & tinytext? </p>
<p>Buy my real question is what reason, if any, would I choose varchar(255) over tinyblob or tinytext? </p>
|
[
{
"answer_id": 143943,
"author": "sethbc",
"author_id": 21722,
"author_profile": "https://Stackoverflow.com/users/21722",
"pm_score": 4,
"selected": false,
"text": "M L M M L L L L"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444/"
] |
143,947
|
<p>More than about LINQ to [insert your favorite provider here], this question is about searching or filtering in-memory collections. </p>
<p>I know LINQ (or searching/filtering extension methods) works in objects implementing <code>IEnumerable</code> or <code>IEnumerable<T></code>. The question is: <em>because of the nature of enumeration, is every query complexity at least <strong>O(n)</strong>?</em></p>
<p>For example:</p>
<pre><code>var result = list.FirstOrDefault(o => o.something > n);
</code></pre>
<p>In this case, every algorithm will take at least <strong>O(n)</strong> unless <code>list</code> is ordered with respect to <code>'something'</code>, in which case the search should take <strong>O(log(n))</strong>: it should be a binary search. However, If I understand correctly, this query will be resolved through enumeration, so it should take <strong>O(n)</strong>, even in <code>list</code> was previously ordered.</p>
<ul>
<li>Is there something I can do to solve a query in <strong>O(log(n))</strong>?</li>
<li>If I want performance, should I use Array.Sort and Array.BinarySearch?</li>
</ul>
|
[
{
"answer_id": 144002,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "IEnumerable"
},
{
"answer_id": 144089,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 2,
"selected": false,
"text": "IEnumerable<int> mySet = new HashSet<int>();\n\n// calls the fast HashSet.Contains because HashSet implements ICollection.\nif (mySet.Contains(10)) { /* code */ }\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18552/"
] |
143,971
|
<p>I think title should be good enough.</p>
|
[
{
"answer_id": 188077,
"author": "ColinYounger",
"author_id": 1223,
"author_profile": "https://Stackoverflow.com/users/1223",
"pm_score": 0,
"selected": false,
"text": "v1.0 <-- Branch \n v1.0.1 <-- Tag \n v1.0.2 <-- Tag \nv1.1 <-- Branch \n v1.1.1 <-- Tag \n v1.1.2 <-- Tag \nv1.2 <-- Branch \n v1.2.1 <-- Tag \n v1.2.2 <-- Tag \nv1.3 <-- Branch \n v1.3.1 <-- Tag \n v1.3.2 <-- Tag \nv1.4 <-- Branch \n v1.4.1 <-- Tag \n v1.4.2 <-- Tag \nv1.5 <-- Branch \n v1.5.1 <-- Tag \n v1.5.2 <-- Tag \n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] |
143,973
|
<p>I happened upon a brief discussion recently on another site about C# runtime compilation recently while searching for something else and thought the idea was interesting. Have you ever used this? I'm trying to determine how/when one might use this and what problem it solves. I'd be very interested in hearing how you've used it or in what context it makes sense.</p>
<p>Thanks much.</p>
|
[
{
"answer_id": 143988,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 2,
"selected": false,
"text": "IMyProxy : IXmlRpcProxy\n{\n [XmlRpcMethod]\n int Add(int a, int b);\n}\n IMyProxy proxy = (IMyProxy)XmlRcpFactory.Create(typeof(IMyProxy));\n int result = proxy.Add(1, 2);\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7862/"
] |
143,997
|
<p>In Jesse Liberty's Learning C# book, he says "Objects of one type can be converted into objects of another type. This is called casting."</p>
<p>If you investigate the IL generated from the code below, you can clearly see that the casted assignment isn't doing the same thing as the converted assignment. In the former, you can see the boxing/unboxing occurring; in the latter you can see a call to a convert method. </p>
<p>I know in the end it may be just a silly semantic difference--but is casting just another word for converting. I don't mean to be snarky, but I'm not interested in anyone's gut feeling on this--opinions don't count here! Can anyone point to a definitive reference that confirms or denies if casting and converting are the same thing?</p>
<pre><code> object x;
int y;
x = 4;
y = ( int )x;
y = Convert.ToInt32( x );
</code></pre>
<p>Thank you</p>
<p>rp</p>
<p>Note added after Matt's comment about explicit/implicit:</p>
<p>I don't think implicit/explicit is the difference. In the code I posted, the change is explicit in both cases. An implicit conversion is what occurs when you assign a short to an int.</p>
<p>Note to Sklivvz:</p>
<p>I wanted confirmation that my suspicion of the looseness of Jesse Liberty's (otherwise usually lucid and clear) language was correct. I thought that Jesse Liberty was being a little loose with his language. I understand that casting is routed in object hierarchy--i.e., you can't cast from an integer to a string but you could cast from custom exception derived from System.Exception to a System.Exception. </p>
<p>It's interesting, though, that when you do try to cast from an int to a string the compiler tells you that it couldn't "convert" the value. Maybe Jesse is more correct than I thought! </p>
|
[
{
"answer_id": 144006,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 5,
"selected": false,
"text": "static void Main(string[] args)\n{\n long l = long.MaxValue;\n\n Console.WriteLine(l);\n\n byte b = (byte) l;\n\n Console.WriteLine(b);\n\n b = Convert.ToByte(l);\n\n Console.WriteLine(b);\n\n}\n"
},
{
"answer_id": 144020,
"author": "Wayne Bloss",
"author_id": 16387,
"author_profile": "https://Stackoverflow.com/users/16387",
"pm_score": 3,
"selected": false,
"text": "int i = 5;\ndouble d = i;\n double d = 1.5;\nint i = (int)d;\n string s = \"15\";\nint i = Convert.ToInt32(s);\n string s = \"The quick brown fox\";\nint i = Convert.ToInt32(s);\n"
},
{
"answer_id": 144021,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "object x;\nint y;\n\nx = 4;\n\ny = ( int )x;\n (newtype)somevar y = CInt(x)\n y = CType(x, newtype)\n Convert() Convert() Convert() y x x y Convert()"
},
{
"answer_id": 144040,
"author": "CodeRedick",
"author_id": 17145,
"author_profile": "https://Stackoverflow.com/users/17145",
"pm_score": -1,
"selected": false,
"text": "char caster = '5';\nConsole.WriteLine((int)caster);\n"
},
{
"answer_id": 144069,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "float f = 1.5f;\nint i = (int) f; // Conversion\n object o = \"hello\";\nstring x = (string) o; // No data is \"converted\"; x and o refer to the same object\n"
},
{
"answer_id": 144116,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "List<int> myList = new List<int>();\n//up-cast\nIEnumerable<int> myEnumerable = (IEnumerable<int>) myList;\n//down-cast\nList<int> myOtherList = (List<int>) myEnumerable;\n List<int> myList = new List<int>();\nint[] myArray = myList.ToArray();\n decimal w = 1.1m;\nint x = (int)w;\n"
},
{
"answer_id": 246850,
"author": "Mark T",
"author_id": 10722,
"author_profile": "https://Stackoverflow.com/users/10722",
"pm_score": 1,
"selected": false,
"text": "x=-2.5 (int)x=-2 Convert.ToInt32(x)=-2\nx=-1.5 (int)x=-1 Convert.ToInt32(x)=-2\nx=-0.5 (int)x= 0 Convert.ToInt32(x)= 0\nx= 0.5 (int)x= 0 Convert.ToInt32(x)= 0\nx= 1.5 (int)x= 1 Convert.ToInt32(x)= 2\nx= 2.5 (int)x= 2 Convert.ToInt32(x)= 2\n x=-1.5 x=1.5"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/143997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
] |
144,058
|
<p>I just installed Ganymede and am exploring an old project in it. All of my JSPs are giving me weird validation errors. I'm seeing stuff like - </p>
<pre><code>Syntax error on token "}", delete this token
Syntax error on token "catch", Identifier expected
Syntax error, insert "Finally" to complete TryStatement
</code></pre>
<p>I'm doing best practice stuff here, no scriplets or anything, so I think that Eclipse is incorrectly applying a Java class validator to my JSPs. Any idea on how to stop that from happening?</p>
<p>Under Options/Editors/File Associations I have the following for JSPs:</p>
<pre><code>JSP Editor (default)
Web Page Editor
Text Editor
CSS JSP Editor
</code></pre>
<p>Am I missing something?</p>
<p>Also I think this is correct, but just in case it's not, here is my page directive - </p>
<pre><code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
</code></pre>
|
[
{
"answer_id": 281282,
"author": "Greg",
"author_id": 28002,
"author_profile": "https://Stackoverflow.com/users/28002",
"pm_score": 1,
"selected": false,
"text": "<% if(message != null) { %>\n <p id=\"message\"><%=message %></p>\n<% } else { %>\n <p>Please login to view your account information.</p>\n<% } %>\n Syntax error on token \"}\", delete this token\nSyntax error on token \"catch\", Identifier expected\nSyntax error, insert \"Finally\" to complete TryStatement\n"
},
{
"answer_id": 290722,
"author": "Greg",
"author_id": 28002,
"author_profile": "https://Stackoverflow.com/users/28002",
"pm_score": 3,
"selected": false,
"text": "<form:errors path=\"*\" />\n <form:errors path=\"*\"></form:errors>\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543/"
] |
144,088
|
<p>I'm playing with ASP.NET MVC for the last few days and was able to build a small site. Everything works great. </p>
<p>Now, I need to pass the page's META tags (title, description, keywords, etc.) via the ViewData. (i'm using a master page).</p>
<p>How you're dealing with this? Thank you in advance.</p>
|
[
{
"answer_id": 144127,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 5,
"selected": true,
"text": "<head>\n<asp:ContentPlaceHolder ID=\"cphHead\" runat=\"server\">\n <title>Default Title</title>\n <meta name=\"description\" content=\"Default Description\" />\n <meta name=\"keywords\" content=\"Default Keywords\" />\n</asp:ContentPlaceHolder>\n</head>\n <asp:Content ID=\"headContent\" ContentPlaceHolderID=\"cphHead\" runat=\"server\">\n <title>Page Specific Title</title>\n <meta name=\"description\" content=\"Page Specific Description\" />\n <meta name=\"keywords\" content=\"Page Specific Keywords\" />\n</asp:Content>\n"
},
{
"answer_id": 147494,
"author": "Charlino",
"author_id": 10202,
"author_profile": "https://Stackoverflow.com/users/10202",
"pm_score": 4,
"selected": false,
"text": "public class BaseViewData\n{\n public string Title { get; set; }\n public string MetaKeywords { get; set; }\n public string MetaDescription { get; set; }\n}\n public partial class Site : System.Web.Mvc.ViewMasterPage<BaseViewData>\n{\n}\n <title><%=ViewData.Model.Title %></title>\n<meta name=\"keywords\" content=\"<%=ViewData.Model.MetaKeywords %>\" />\n<meta name=\"description\" content=\"<%=ViewData.Model.MetaDescription %>\" />\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19610/"
] |
144,118
|
<p>While trying to generate classes from a xsd, i got this error:</p>
<pre><code>java.lang.IllegalArgumentException: Illegal class inheritance loop. Outer class OrderPropertyList may not subclass from inner class: OrderPropertyList
</code></pre>
<p>My xsd define a element to group a unbounded element like this:</p>
<pre><code> <element minOccurs="0" name="orderPropertyList">
<complexType>
<sequence>
<element maxOccurs="unbounded" name="orderProperty" type="tns:orderProperty" />
</sequence>
</complexType>
</element>
</code></pre>
<p>And my customization binding follows as specified on <a href="http://java.sun.com/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html" rel="nofollow noreferrer">this page</a>, but it doesn´t work.
Here my binding:</p>
<pre><code><jaxb:bindings schemaLocation="../xsd/Schema.xsd" node="/xs:schema">
<jaxb:bindings node="//xs:element[@name='orderPropertyList']">
<jaxb:class name="OrderPropertyList"/>
</jaxb:bindings>
</jaxb:bindings>
</code></pre>
<p>My intention is to generate a individual class for orderPropertyList, not the default behave that is generating a inner class inside the root element of the xsd.</p>
<p>I´ve watched someone with the same intention <a href="http://forums.java.net/jive/thread.jspa?threadID=15633" rel="nofollow noreferrer">here</a> and <a href="http://forums.java.net/jive/message.jspa?messageID=228180" rel="nofollow noreferrer">here</a>, but it doesn´t work properly for me. :(</p>
<p>JAXB version: </p>
<pre><code>Specification-Version: 2.1
Implementation-Version: 2.1.8
</code></pre>
<p>Any help?</p>
|
[
{
"answer_id": 179916,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<jaxb:globalBindings localScoping=\"toplevel\"/>\n <jaxb:bindings schemaLocation=\"../xsd/Schema.xsd\" node=\"/xs:schema\">\n <jaxb:bindings node=\"//xs:element[@name='orderPropertyList']\">\n <jaxb:class name=\"OrderPropertyList\"/>\n </jaxb:bindings>\n</jaxb:bindings>\n <jaxb:bindings node=\"//xs:element[@name='orderPropertyList']/xs:complexType\">\n"
},
{
"answer_id": 7775099,
"author": "Jeff Evans",
"author_id": 375670,
"author_profile": "https://Stackoverflow.com/users/375670",
"pm_score": 2,
"selected": false,
"text": "<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\" version=\"1.0\">\n <xsd:element name=\"TopLevelElement\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name=\"Something\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name=\"Something\" maxOccurs=\"unbounded\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name=\"somethingFieldA\" type=\"xsd:string\"/>\n <xsd:element name=\"somethingFieldB\" type=\"xsd:string\"/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:element>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:element>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:element>\n</xsd:schema>\n Something Something complexType Something"
},
{
"answer_id": 33867623,
"author": "amit dahiya",
"author_id": 5594528,
"author_profile": "https://Stackoverflow.com/users/5594528",
"pm_score": 0,
"selected": false,
"text": "/xs:complexType"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21370/"
] |
144,134
|
<p>How does C handle converting between integers and characters? Say you've declared an integer variable and ask the user for a number but they input a string instead. What would happen?</p>
|
[
{
"answer_id": 144199,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 2,
"selected": false,
"text": "char foo = 'a'; // The ascii value representation for lower-case 'a' is 97\nint bar = foo; // bar now contains the value 97 \nbar = 255; // 255 is 0x000000ff in hexadecimal\nfoo = bar; // foo now contains -1 (0xff) \nunsigned char foo2 = foo; // foo now contains 255 (0xff)\n"
},
{
"answer_id": 144332,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "fgets() atoi() strtol() strtoul() strtoll() strtoull() strtod()"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1972/"
] |
144,147
|
<p>I have a sparse array in Jscript, with non-null elements occuring at both negative and positive indices. When I try to use a for in loop, it doesn't traverse the array from the lowest (negative) index to the highest positive index. Instead it returns the array in the order that I added the elements. Enumeration doesn't work either. Is there any method that will allow me to do that?</p>
<p><strong>Example</strong></p>
<pre><code>arrName = new Array();
arrName[-10] = "A";
arrName[20] = "B";
arrName[10] = "C";
</code></pre>
<p>When looping through, it should give me A then C the B.</p>
|
[
{
"answer_id": 144182,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 4,
"selected": true,
"text": "<script type=\"text/javascript\">\n//define and initialize your object/hastable\nvar obj = {};\nobj[20] = 'C';\nobj[10] = 'B';\nobj[-10] = 'A';\n\n// get the indexes and sort them\nvar indexes = [];\nfor(var i in obj){\n indexes.push(i);\n}\nindexes.sort(function(a,b){\n return a-b;\n});\n\n// write the values to the page in index order (increasing)\nfor(var i=0,l=indexes.length; i<l; i++){\n document.write(obj[indexes[i]] + ' ');\n}\n// Should print out as \"A B C\" to the page\n</script>\n"
},
{
"answer_id": 144188,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "Array Object var arr = new Array();\narr[0] = 'A';\narr[1] = 'B';\narr[-1] = 'C';\narr.length\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
144,151
|
<p>My macro updates a large spreadsheet with numbers, but it runs very slowly as excel is rendering the result as it computes it. How do I stop excel from rendering the output until the macro is complete?</p>
|
[
{
"answer_id": 144160,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 2,
"selected": false,
"text": "Public Sub MyMacro\n On Error GoTo ErrHandler\n Application.ScreenUpdating = False\n ... do my stuff that might raise an error\n Application.ScreenUpdating = True\n Exit Sub\nErrHandler:\n Application.ScreenUpdating = True\n ... Do something with the error, e.g. MsgBox \nEnd Sub\n"
},
{
"answer_id": 144173,
"author": "SeeR",
"author_id": 22569,
"author_profile": "https://Stackoverflow.com/users/22569",
"pm_score": 5,
"selected": true,
"text": "Application.ScreenUpdating = False\nApplication.Calculation = xlCalculationManual\n...\n...\n...\nApplication.Calculation = xlCalculationAutomatic\nApplication.ScreenUpdating = True\n"
},
{
"answer_id": 144221,
"author": "wilth",
"author_id": 5218,
"author_profile": "https://Stackoverflow.com/users/5218",
"pm_score": 1,
"selected": false,
"text": "On Error Goto AfterCalculation\nApplication.ScreenUpdating = False\nApplication.Calculation = xlCalculationManual\n...\n\nAfterCalculation:\nApplication.Calculation = xlCalculationAutomatic\nApplication.ScreenUpdating = True\n"
},
{
"answer_id": 452544,
"author": "user37130",
"author_id": 37130,
"author_profile": "https://Stackoverflow.com/users/37130",
"pm_score": 2,
"selected": false,
"text": "Application.ScreenUpdating = False\nPreviousCalcMode = Application.Calculation\nApplication.Calculation = xlCalculationManual\n ... \n ...\n ...\nApplication.Calculation = PreviousCalcMode\nApplication.ScreenUpdating = True\n Sub DoSomeThing\n\n\nOn Error Goto DisplayError\n\nApplication.ScreenUpdating = False\nPreviousCalcMode = Application.Calculation\nApplication.Calculation = xlCalculationManual\n ... \n ...\n ...\nApplication.Calculation = PreviousCalcMode\nApplication.ScreenUpdating = True\n\nExit Sub\n\nDisplayError:\nApplication.Calculation = PreviousCalcMode\nApplication.ScreenUpdating = True\n\nMsgBox Err.Description\nEnd 'This stops execution of macro, in some macros this might not be what you want'\n '(i.e you might want to close files etc)'\nEnd Sub\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5472/"
] |
144,167
|
<p>I am using Oracle SQL (in SQLDeveloper, so I don't have access to SQLPLUS commands such as COLUMN) to execute a query that looks something like this:</p>
<pre><code>select assigner_staff_id as staff_id, active_flag, assign_date,
complete_date, mod_date
from work where assigner_staff_id = '2096';
</code></pre>
<p>The results it give me look something like this:</p>
<pre>
STAFF_ID ACTIVE_FLAG ASSIGN_DATE COMPLETE_DATE MOD_DATE
---------------------- ----------- ------------------------- ------------------------- -------------------------
2096 F 25-SEP-08 27-SEP-08 27-SEP-08 02.27.30.642959000 PM
2096 F 25-SEP-08 25-SEP-08 25-SEP-08 01.41.02.517321000 AM
2 rows selected
</pre>
<p>This can very easily produce a very wide and unwieldy textual report when I'm trying to paste the results as a nicely formatted quick-n-dirty text block into an e-mail or problem report, etc. What's the best way to get rid of all tha extra white space in the output columns when I'm using just plain-vanilla Oracle SQL? So far all my web searches haven't turned up much, as all the web search results are showing me how to do it using formatting commands like COLUMN in SQLPLUS (which I don't have).</p>
|
[
{
"answer_id": 144187,
"author": "Thomas Jones-Low",
"author_id": 23030,
"author_profile": "https://Stackoverflow.com/users/23030",
"pm_score": 3,
"selected": true,
"text": "select substr(assigner_staff_id, 8) as staff_id, \n active_flag as Flag, \n to_char(assign_date, 'DD/MM/YY'),\n to_char(complete_date, 'DD/MM/YY'), \n mod_date\nfrom work where assigner_staff_id = '2096';\n"
},
{
"answer_id": 144197,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 0,
"selected": false,
"text": "select substring( convert(varchar(4), assigner_staff_id), 1, 4 ) as id, \n active_flag as act, -- use shorter column name\n\n -- etc. \n\nfrom work where assigner_staff_id = '2096';\n"
},
{
"answer_id": 145055,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 0,
"selected": false,
"text": "SQL> set serveroutput on \nSQL> execute print_table('select * from all_objects where rownum < 3');\nOWNER : SYS\nOBJECT_NAME : /1005bd30_LnkdConstant\nSUBOBJECT_NAME :\nOBJECT_ID : 27574\nDATA_OBJECT_ID :\nOBJECT_TYPE : JAVA CLASS\nCREATED : 22-may-2008 11:41:13\nLAST_DDL_TIME : 22-may-2008 11:41:13\nTIMESTAMP : 2008-05-22:11:41:13\nSTATUS : VALID\nTEMPORARY : N\nGENERATED : N\nSECONDARY : N\n-----------------\nOWNER : SYS\nOBJECT_NAME : /10076b23_OraCustomDatumClosur\nSUBOBJECT_NAME :\nOBJECT_ID : 22390\nDATA_OBJECT_ID :\nOBJECT_TYPE : JAVA CLASS\nCREATED : 22-may-2008 11:38:34\nLAST_DDL_TIME : 22-may-2008 11:38:34\nTIMESTAMP : 2008-05-22:11:38:34\nSTATUS : VALID\nTEMPORARY : N\nGENERATED : N\nSECONDARY : N\n-----------------\n\nPL/SQL procedure successfully completed.\n\nSQL> \n"
},
{
"answer_id": 13185162,
"author": "Jim Clouse",
"author_id": 868541,
"author_profile": "https://Stackoverflow.com/users/868541",
"pm_score": 2,
"selected": false,
"text": "select /*csv*/ col1, col2 from table;\nselect /*Delimited*/ col1, col2 from table;\n"
},
{
"answer_id": 20098946,
"author": "Bubba",
"author_id": 3013559,
"author_profile": "https://Stackoverflow.com/users/3013559",
"pm_score": 0,
"selected": false,
"text": "select \n(cast(assigner_staff_id as VARCHAR2(4)) AS STAFF_ID,\n(cast(active_flag as VARCHAR2(1))) AS A,\n(cast(assign_date as VARCHAR2(10))) AS ASSIGN_DATE,\n(cast(COMPLETE_date as VARCHAR2(10))) AS COMPLETE_DATE,\n(cast(mod_date as VARCHAR2(10))) AS MOD_DATE\nfrom work where assigner_staff_id = '2096';\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13140/"
] |
144,176
|
<p>I need to convert a (possibly) null terminated array of ascii bytes to a string in C# and the fastest way I've found to do it is by using my UnsafeAsciiBytesToString method shown below. This method uses the String.String(sbyte*) constructor which contains a warning in it's remarks:</p>
<p>"The value parameter is assumed to point to an array representing a string encoded using the default ANSI code page (that is, the encoding method specified by Encoding.Default).</p>
<p>Note: <strong>* Because the default ANSI code page is system-dependent, the string created by this constructor from identical signed byte arrays may differ on different systems. *</strong> ...</p>
<p><strong>* If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. *</strong>
"</p>
<p>Now, I'm positive that the way the string is encoded will never change... but the default codepage on the system that my app is running on might change. So, is there any reason that I shouldn't run screaming from using String.String(sbyte*) for this purpose?</p>
<pre><code>using System;
using System.Text;
namespace FastAsciiBytesToString
{
static class StringEx
{
public static string AsciiBytesToString(this byte[] buffer, int offset, int maxLength)
{
int maxIndex = offset + maxLength;
for( int i = offset; i < maxIndex; i++ )
{
/// Skip non-nulls.
if( buffer[i] != 0 ) continue;
/// First null we find, return the string.
return Encoding.ASCII.GetString(buffer, offset, i - offset);
}
/// Terminating null not found. Convert the entire section from offset to maxLength.
return Encoding.ASCII.GetString(buffer, offset, maxLength);
}
public static string UnsafeAsciiBytesToString(this byte[] buffer, int offset)
{
string result = null;
unsafe
{
fixed( byte* pAscii = &buffer[offset] )
{
result = new String((sbyte*)pAscii);
}
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
byte[] asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c', 0, 0, 0 };
string result = asciiBytes.AsciiBytesToString(3, 6);
Console.WriteLine("AsciiBytesToString Result: \"{0}\"", result);
result = asciiBytes.UnsafeAsciiBytesToString(3);
Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result);
/// Non-null terminated test.
asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c' };
result = asciiBytes.UnsafeAsciiBytesToString(3);
Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result);
Console.ReadLine();
}
}
}
</code></pre>
|
[
{
"answer_id": 144189,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "String(sbyte*, int, int) public static string UnsafeAsciiBytesToString(byte[] buffer, int offset, int length)\n{\n unsafe\n {\n fixed (byte* pAscii = buffer)\n { \n return new String((sbyte*)pAscii, offset, length);\n }\n }\n}\n public static string UnsafeAsciiBytesToString(byte[] buffer, int offset)\n{\n int end = offset;\n while (end < buffer.Length && buffer[end] != 0)\n {\n end++;\n }\n unsafe\n {\n fixed (byte* pAscii = buffer)\n { \n return new String((sbyte*)pAscii, offset, end - offset);\n }\n }\n}\n"
},
{
"answer_id": 1835186,
"author": "Pat",
"author_id": 116891,
"author_profile": "https://Stackoverflow.com/users/116891",
"pm_score": 3,
"selected": false,
"text": "string s = myEncoding.GetString(bytes.TakeWhile(b => !b.Equals(0)).ToArray());\n"
},
{
"answer_id": 2466242,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": -1,
"selected": false,
"text": "string result = \"\";\nfor (int i = 0; i < data.Length && data[i] != 0; i++)\n result += (char)data[i];\n"
},
{
"answer_id": 8248997,
"author": "Vladimir Poslavskiy",
"author_id": 1062758,
"author_profile": "https://Stackoverflow.com/users/1062758",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace TestProject1\n{\n class Class1\n {\n static public string cstr_to_string( byte[] data, int code_page)\n {\n Encoding Enc = Encoding.GetEncoding(code_page); \n int inx = Array.FindIndex(data, 0, (x) => x == 0);//search for 0\n if (inx >= 0)\n return (Enc.GetString(data, 0, inx));\n else \n return (Enc.GetString(data)); \n }\n\n }\n}\n"
},
{
"answer_id": 12584758,
"author": "euwe",
"author_id": 1512586,
"author_profile": "https://Stackoverflow.com/users/1512586",
"pm_score": 2,
"selected": false,
"text": "s = s.Substring(0, s.IndexOf((char) 0));\n"
},
{
"answer_id": 17588566,
"author": "Harald Coppoolse",
"author_id": 2281790,
"author_profile": "https://Stackoverflow.com/users/2281790",
"pm_score": 0,
"selected": false,
"text": "string s = \"Hello World!\"\nbyte[] b = System.Text.Encoding.ASCII.GetBytes(s);\n byte[] byteArray = new byte[] {0x41, 0x42, 0x09, 0x00, 0x255};\nstring s = System.Text.Encoding.ASCII.GetString(byteArray);\n"
},
{
"answer_id": 20247598,
"author": "user3042599",
"author_id": 3042599,
"author_profile": "https://Stackoverflow.com/users/3042599",
"pm_score": 4,
"selected": false,
"text": "String MyString = Encoding.ASCII.GetString(MyByteBuffer).TrimEnd((Char)0);\n"
},
{
"answer_id": 57975836,
"author": "Heinzi",
"author_id": 87698,
"author_profile": "https://Stackoverflow.com/users/87698",
"pm_score": 2,
"selected": false,
"text": "var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);\ntry\n{\n return Marshal.PtrToStringAnsi(handle.AddrOfPinnedObject());\n}\nfinally\n{\n handle.Free();\n}\n Marshal.PtrToStringUni"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16387/"
] |
144,218
|
<p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
|
[
{
"answer_id": 144231,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "decimal.getcontext().prec=2\n"
},
{
"answer_id": 144263,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": ">>> \"%8.2e\"% ( 1.0/3.0 )\n'3.33e-01'\n"
},
{
"answer_id": 719519,
"author": "user86317",
"author_id": 86317,
"author_profile": "https://Stackoverflow.com/users/86317",
"pm_score": 1,
"selected": false,
"text": "def lround(x,leadingDigits=0): \n \"\"\"Return x either as 'print' would show it (the default) \n or rounded to the specified digit as counted from the leftmost \n non-zero digit of the number, e.g. lround(0.00326,2) --> 0.0033\n \"\"\" \n assert leadingDigits>=0 \n if leadingDigits==0: \n return float(str(x)) #just give it back like 'print' would give it\n return float('%.*e' % (int(leadingDigits),x)) #give it back as rounded by the %e format \n >>> lround(1./3.,2),str(lround(1./3.,2)),str(lround(1./3.,4))\n(0.33000000000000002, '0.33', '0.3333')\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
144,226
|
<p>From what I know, the em keyword in CSS means the current size of a font.</p>
<p>So if you put 1.2 em, it means 120% of the font height.</p>
<p>It doesn't seem right though that em is used for setting the width of divs etc like YUI grids does:</p>
<pre><code>margin-right:24.0769em;*margin-right:23.62em;
</code></pre>
<p>Everytime I read about em, I forget what it really represents.</p>
<p>I'm hoping someone can explain it to me so it sticks in my head heeh.</p>
|
[
{
"answer_id": 144238,
"author": "Fczbkk",
"author_id": 22920,
"author_profile": "https://Stackoverflow.com/users/22920",
"pm_score": 0,
"selected": false,
"text": "em"
},
{
"answer_id": 144271,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 1,
"selected": false,
"text": "<!-- Browser default size (usually 16px) -->\n<div style=\"font-size: 1.00em;\">\n <!-- 150 % of the container's size: 16 + (16/2) = 24 -->\n <div style=\"font-size: 1.50em;\">\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] |
144,246
|
<p>I have an application that is causing a lot of headaches. It's a .NET app connecting to SQL Server 2005 via a web service. The program has grid that is filled by a long running stored procedure that is prone to timing out. In the case when it does time out and a SqlException is thrown, there is no execption handling to close the connection.</p>
<p>What are the actual consequences of this condition? I think that the framework or SQL Server probably takes care of it one way or another but am not sure. </p>
<p><strong>Addition</strong>
The program always works well in the morning, but after an hour or so of use it basically stops working. The issue isn't that I don't know how to code the connection properly. I need to know if these symptoms could be casued by the unclosed connections. It is kind of a big deal to change the production code and I would like to know that it is at least possible for this to be the issue.</p>
<p><strong>Conclusion</strong>
I engineered this failure to occur on hundreds of simultaneous connections. Never was I able reproduce the failure condition in the application environment. Marked best practices answer as correct. Thanks everyone.</p>
|
[
{
"answer_id": 144251,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 0,
"selected": false,
"text": "finally\n{\n if (cn != null)\n {\n cn.Dispose();\n cn = null;\n }\n}\n"
},
{
"answer_id": 144252,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 0,
"selected": false,
"text": "try\n{\n sqlCommandObject.Execute(); // this line will throw a timeout exception\n}\nfinally\n{\n sqlConnectionObject.Close(); // this will execute no matter what happens\n}\n"
},
{
"answer_id": 144299,
"author": "ullmark",
"author_id": 23044,
"author_profile": "https://Stackoverflow.com/users/23044",
"pm_score": 4,
"selected": true,
"text": "using (SqlConnection conn = new SqlConnection())\n{\n // SqlCode here \n}\n"
},
{
"answer_id": 144304,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 1,
"selected": false,
"text": " using ( SqlConnection conn = new SqlConnection() )\n {\n ...\n }\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22273/"
] |
144,250
|
<p>I am writing an iPhone application and need to essentially implement something equivalent to the 'eyedropper' tool in photoshop, where you can touch a point on the image and capture the RGB values for the pixel in question to determine and match its color. Getting the UIImage is the easy part, but is there a way to convert the UIImage data into a bitmap representation in which I could extract this information for a given pixel? A working code sample would be most appreciated, and note that I am not concerned with the alpha value.</p>
|
[
{
"answer_id": 144928,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 4,
"selected": false,
"text": "CGImageRef cgImage = [image CGImage];\nCGDataProviderRef provider = CGImageGetDataProvider(cgImage);\nCFDataRef bitmapData = CGDataProviderCopyData(provider);\n"
},
{
"answer_id": 396931,
"author": "iggames",
"author_id": 49622,
"author_profile": "https://Stackoverflow.com/users/49622",
"pm_score": 3,
"selected": false,
"text": "UInt8* data = CFDataGetBytePtr(bitmapData); CoreGraphics.framework"
},
{
"answer_id": 694139,
"author": "Asher",
"author_id": 84181,
"author_profile": "https://Stackoverflow.com/users/84181",
"pm_score": 6,
"selected": true,
"text": "#define RGBA 4\n#define RGBA_8_BIT 8\n size_t bytesPerRow;\nsize_t byteCount;\nsize_t pixelCount;\n\nCGContextRef context;\nCGColorSpaceRef colorSpace;\n\nUInt8 *pixelByteData;\n// A pointer to an array of RGBA bytes in memory\nRPVW_RGBAPixel *pixelData;\n typedef struct RGBAPixel {\n byte red;\n byte green;\n byte blue;\n byte alpha;\n} RGBAPixel;\n -(RGBAPixel*) bitmap {\n NSLog( @\"Returning bitmap representation of UIImage.\" );\n // 8 bits each of red, green, blue, and alpha.\n [self setBytesPerRow:self.size.width * RGBA];\n [self setByteCount:bytesPerRow * self.size.height];\n [self setPixelCount:self.size.width * self.size.height];\n\n // Create RGB color space\n [self setColorSpace:CGColorSpaceCreateDeviceRGB()];\n\n if (!colorSpace)\n {\n NSLog(@\"Error allocating color space.\");\n return nil;\n }\n\n [self setPixelData:malloc(byteCount)];\n\n if (!pixelData)\n {\n NSLog(@\"Error allocating bitmap memory. Releasing color space.\");\n CGColorSpaceRelease(colorSpace);\n\n return nil;\n }\n\n // Create the bitmap context. \n // Pre-multiplied RGBA, 8-bits per component. \n // The source image format will be converted to the format specified here by CGBitmapContextCreate.\n [self setContext:CGBitmapContextCreate(\n (void*)pixelData,\n self.size.width,\n self.size.height,\n RGBA_8_BIT,\n bytesPerRow,\n colorSpace,\n kCGImageAlphaPremultipliedLast\n )];\n\n // Make sure we have our context\n if (!context) {\n free(pixelData);\n NSLog(@\"Context not created!\");\n }\n\n // Draw the image to the bitmap context. \n // The memory allocated for the context for rendering will then contain the raw image pixelData in the specified color space.\n CGRect rect = { { 0 , 0 }, { self.size.width, self.size.height } };\n\n CGContextDrawImage( context, rect, self.CGImage );\n\n // Now we can get a pointer to the image pixelData associated with the bitmap context.\n pixelData = (RGBAPixel*) CGBitmapContextGetData(context);\n\n return pixelData;\n}\n typedef unsigned char byte;\n typedef struct RGBPixel{\n byte red;\n byte green;\n byte blue; \n } \nRGBPixel;\n // Reference to Quartz CGImage for receiver (self) \nCFDataRef bitmapData; \n\n// Buffer holding raw pixel data copied from Quartz CGImage held in receiver (self) \nUInt8* pixelByteData;\n\n// A pointer to the first pixel element in an array \nRGBPixel* pixelData;\n //Get the bitmap data from the receiver's CGImage (see UIImage docs) \n[self setBitmapData: CGDataProviderCopyData(CGImageGetDataProvider([self CGImage]))];\n\n//Create a buffer to store bitmap data (unitialized memory as long as the data) \n[self setPixelBitData:malloc(CFDataGetLength(bitmapData))];\n\n//Copy image data into allocated buffer \nCFDataGetBytes(bitmapData,CFRangeMake(0,CFDataGetLength(bitmapData)),pixelByteData);\n\n//Cast a pointer to the first element of pixelByteData \n//Essentially what we're doing is making a second pointer that divides the byteData's units differently - instead of dividing each unit as 1 byte we will divide each unit as 3 bytes (1 pixel). \npixelData = (RGBPixel*) pixelByteData;\n\n//Now you can access pixels by index: pixelData[ index ] \nNSLog(@\"Pixel data one red (%i), green (%i), blue (%i).\", pixelData[0].red, pixelData[0].green, pixelData[0].blue);\n\n//You can determine the desired index by multiplying row * column. \nreturn pixelData;\n -(RGBPixel*)pixelDataForRow:(int)row column:(int)column{\n //Return a pointer to the pixel data\n return &pixelData[row * column]; \n}\n"
},
{
"answer_id": 12032147,
"author": "garafajon",
"author_id": 698967,
"author_profile": "https://Stackoverflow.com/users/698967",
"pm_score": 2,
"selected": false,
"text": "- (UIColor*)colorFromImage:(UIImage*)image sampledAtPoint:(CGPoint)p {\n CGImageRef cgImage = [image CGImage];\n CGDataProviderRef provider = CGImageGetDataProvider(cgImage);\n CFDataRef bitmapData = CGDataProviderCopyData(provider);\n const UInt8* data = CFDataGetBytePtr(bitmapData);\n size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);\n size_t width = CGImageGetWidth(cgImage);\n size_t height = CGImageGetHeight(cgImage);\n int col = p.x*(width-1);\n int row = p.y*(height-1);\n const UInt8* pixel = data + row*bytesPerRow+col*4;\n UIColor* returnColor = [UIColor colorWithRed:pixel[0]/255. green:pixel[1]/255. blue:pixel[2]/255. alpha:1.0];\n CFRelease(bitmapData);\n return returnColor;\n}\n UIColor* sampledColor = [self colorFromImage:image\n sampledAtPoint:CGPointMake(p.x/imageView.frame.size.width,\n p.y/imageView.frame.size.height)];\n"
},
{
"answer_id": 12059435,
"author": "Matej Bukovinski",
"author_id": 88854,
"author_profile": "https://Stackoverflow.com/users/88854",
"pm_score": 5,
"selected": false,
"text": "#import <UIKit/UIKit.h>\n\n\n@interface UIImage (Picker)\n\n- (UIColor *)colorAtPosition:(CGPoint)position;\n\n@end\n #import \"UIImage+Picker.h\"\n\n\n@implementation UIImage (Picker)\n\n- (UIColor *)colorAtPosition:(CGPoint)position {\n\n CGRect sourceRect = CGRectMake(position.x, position.y, 1.f, 1.f);\n CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, sourceRect);\n\n CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();\n unsigned char *buffer = malloc(4);\n CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;\n CGContextRef context = CGBitmapContextCreate(buffer, 1, 1, 8, 4, colorSpace, bitmapInfo);\n CGColorSpaceRelease(colorSpace);\n CGContextDrawImage(context, CGRectMake(0.f, 0.f, 1.f, 1.f), imageRef);\n CGImageRelease(imageRef);\n CGContextRelease(context);\n\n CGFloat r = buffer[0] / 255.f;\n CGFloat g = buffer[1] / 255.f;\n CGFloat b = buffer[2] / 255.f;\n CGFloat a = buffer[3] / 255.f;\n\n free(buffer);\n\n return [UIColor colorWithRed:r green:g blue:b alpha:a];\n}\n\n@end \n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17123/"
] |
144,261
|
<p>Does Apple's Xcode development environment provide any tools for memory leak detection?</p>
<p>I am especially interested in tools that apply to the iPhone SDK. Currently my favourite platform for hobby programming projects</p>
<p>Documentations/tutorials for said tools would be very helpful.</p>
|
[
{
"answer_id": 144491,
"author": "KevDog",
"author_id": 13139,
"author_profile": "https://Stackoverflow.com/users/13139",
"pm_score": 2,
"selected": false,
"text": "Instruments User Guide"
},
{
"answer_id": 144494,
"author": "titaniumdecoy",
"author_id": 18091,
"author_profile": "https://Stackoverflow.com/users/18091",
"pm_score": 5,
"selected": false,
"text": "Profile Product /Applications/Xcode.app/Contents/Applications/"
},
{
"answer_id": 144509,
"author": "catlan",
"author_id": 23028,
"author_profile": "https://Stackoverflow.com/users/23028",
"pm_score": 3,
"selected": false,
"text": "menu -> run -> start with performance tool -> ..."
},
{
"answer_id": 144866,
"author": "rustyshelf",
"author_id": 6044,
"author_profile": "https://Stackoverflow.com/users/6044",
"pm_score": 7,
"selected": true,
"text": "Leaks"
},
{
"answer_id": 144919,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 4,
"selected": false,
"text": "Clang Static Analyser"
},
{
"answer_id": 145007,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 2,
"selected": false,
"text": "rustyshelf's solution"
},
{
"answer_id": 3726830,
"author": "Benoit Caccinolo",
"author_id": 438783,
"author_profile": "https://Stackoverflow.com/users/438783",
"pm_score": 2,
"selected": false,
"text": "iphone-essential-performance-tools-list"
},
{
"answer_id": 5467228,
"author": "jww",
"author_id": 608639,
"author_profile": "https://Stackoverflow.com/users/608639",
"pm_score": 3,
"selected": false,
"text": "Introduction to Instruments User Guide Locating Memory Issues in Your App"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22502/"
] |
144,283
|
<p>Is it just that <code>nvarchar</code> supports multibyte characters? If that is the case, is there really any point, other than storage concerns, to using <code>varchars</code>?</p>
|
[
{
"answer_id": 144311,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 4,
"selected": false,
"text": "nvarchar varchar nvarchar varchar nvarchar varchar"
},
{
"answer_id": 147302,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 12,
"selected": true,
"text": "nvarchar varchar varchar nvarchar varchar"
},
{
"answer_id": 3884532,
"author": "Jeremy Frank",
"author_id": 73846,
"author_profile": "https://Stackoverflow.com/users/73846",
"pm_score": 5,
"selected": false,
"text": "SELECT value$ FROM sys.props$ WHERE name = 'NLS_CHARACTERSET'"
},
{
"answer_id": 20094228,
"author": "Paul",
"author_id": 1945782,
"author_profile": "https://Stackoverflow.com/users/1945782",
"pm_score": 3,
"selected": false,
"text": "NVARCHAR VARCHAR VARCHAR NVARCHAR TEXT NTEXT VARCHAR NVARCHAR"
},
{
"answer_id": 35418951,
"author": "Ali Elmi",
"author_id": 1804116,
"author_profile": "https://Stackoverflow.com/users/1804116",
"pm_score": 3,
"selected": false,
"text": "NVARCHAR VARCHAR VARCHAR(10)"
},
{
"answer_id": 41484348,
"author": "Rafid",
"author_id": 196697,
"author_profile": "https://Stackoverflow.com/users/196697",
"pm_score": 3,
"selected": false,
"text": "nvarchar varchar varchar(900) varchar(901) nvarchar nvarchar(450) nvarchar nvarchar(max) varchar(5)"
},
{
"answer_id": 43960886,
"author": "Debendra Dash",
"author_id": 5418530,
"author_profile": "https://Stackoverflow.com/users/5418530",
"pm_score": 5,
"selected": false,
"text": "Varchar(n) nvarchar(n) Varchar Nvarchar"
},
{
"answer_id": 45607118,
"author": "Rinoy Ashokan",
"author_id": 7772699,
"author_profile": "https://Stackoverflow.com/users/7772699",
"pm_score": 2,
"selected": false,
"text": "nvarchar varchar nvarchar where = varchar nvarchar varchar LIKE ="
},
{
"answer_id": 66423745,
"author": "Amar Anondo",
"author_id": 13921383,
"author_profile": "https://Stackoverflow.com/users/13921383",
"pm_score": 4,
"selected": false,
"text": "varchar non-Unicode characters nvarchar unicode non-unicode 8,000 characters 4,000 characters 1 byte 2 bytes"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] |
144,321
|
<p>I'm processing a huge file with (GNU) <code>awk</code>, (other available tools are: Linux shell tools, some old (>5.0) version of Perl, but can't install modules).</p>
<p>My problem: if some field1, field2, field3 contain X, Y, Z I must search for a file in another directory which contains field4, and field5 on one line, and insert some data from the found file to the current output.</p>
<p>E.g.:</p>
<p>Actual file line:</p>
<pre><code>f1 f2 f3 f4 f5
X Y Z A B
</code></pre>
<p>Now I need to search for another file (in another directory), which contains e.g.</p>
<pre><code>f1 f2 f3 f4
A U B W
</code></pre>
<p>And write to STDOUT <code>$0</code> from the original file, and <code>f2</code> and <code>f3</code> from the found file, then process the next line of the original file.</p>
<p>Is it possible to do it with <code>awk</code>?</p>
|
[
{
"answer_id": 144406,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "## perl code to do some dirty work\n\nfor my $line (`grep 'X Y Z' myhugefile`) {\n chomp $line;\n my ($a, $b, $c, $d, $e) = split(/ /,$line);\n my $cmd = 'grep -P \"' . $d . ' .+? ' . $e .'\" otherfile';\n for my $from_otherfile (`$cmd`) {\n chomp $from_otherfile;\n my ($oa, $ob, $oc, $od) = split(/ /,$from_otherfile);\n print \"$a $ob $oc\\n\";\n }\n}\n"
},
{
"answer_id": 147796,
"author": "tsee",
"author_id": 13164,
"author_profile": "https://Stackoverflow.com/users/13164",
"pm_score": 3,
"selected": true,
"text": "#!/usr/bin/env perl -nwa\nuse strict;\nuse File::Find 'find';\nmy @search = qw(X Y Z);\n\n# if you know in advance that the otherfile isn't\n# huge, you can cache it in memory as an optimization.\n\n# with any more columns, you want a loop here:\nif ($F[0] eq $search[0]\n and $F[1] eq $search[1]\n and $F[2] eq $search[2])\n{\n my @files;\n find(sub {\n return if not -f $_;\n # verbatim search for the columns in the file name.\n # I'm still not sure what your file-search criteria are, though.\n push @files, $File::Find::name if /\\Q$F[3]\\E/ and /\\Q$F[4]\\E/;\n # alternatively search for the combination:\n #push @files, $File::Find::name if /\\Q$F[3]\\E.*\\Q$F[4]\\E/;\n # or search *all* files in the search path?\n #push @files, $File::Find::name;\n }, '/search/path'\n )\n foreach my $file (@files) {\n open my $fh, '<', $file or die \"Can't open file '$file': $!\";\n while (defined($_ = <$fh>)) {\n chomp;\n # order of fields doesn't matter per your requirement.\n my @cols = split ' ', $_;\n my %seen = map {($_=>1)} @cols;\n if ($seen{$F[3]} and $seen{$F[4]}) {\n print join(' ', $F[0], @cols[1,2]), \"\\n\";\n }\n }\n close $fh;\n }\n} # end if matching line\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11621/"
] |
144,375
|
<p>I want a nice 2 column layout using CSS float's.</p>
<p>Column#1 160 px
Column#2 100% (i.e. the rest of the space).</p>
<p>I want to place the Col#2's div first, so my layout looks like:</p>
<pre><code><div id="header"></div>
<div id="content">
<div id="col2"></div>
<div id="col1"></div>
</div>
<div id="footer"></div>
</code></pre>
<p>What has to be get this effect?</p>
|
[
{
"answer_id": 144384,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "div#col2 {\n padding-left: 160px;\n width: 100%;\n}\n\ndiv#col1 {\n float: left;\n width: 160px;\n}\n #col1 #col2 #col1 #content {\n position: relative; \n}\ndiv#col2 {\n width: 160px;\n position: absolute;\n}\n\ndiv#col1 {\n width: 100%;\n margin-left: 160px;\n}\n div#footer {\n clear: both;\n}\n"
},
{
"answer_id": 144391,
"author": "MattBelanger",
"author_id": 655,
"author_profile": "https://Stackoverflow.com/users/655",
"pm_score": 1,
"selected": false,
"text": "div#col2 {\n width: 160px;\n float: left;\n position: relative;\n}\n\ndiv#col1 {\n width:100%;\n margin-left: 160px;\n}\n"
},
{
"answer_id": 34469081,
"author": "Peyman Mohamadpour",
"author_id": 5104596,
"author_profile": "https://Stackoverflow.com/users/5104596",
"pm_score": 0,
"selected": false,
"text": "#col1 #col2 overflow: hidden #content overflow: hidden #content{\n overflow: hidden;\n padding: 20px 0;\n height: 100px;\n background-color: #cdeecd;\n}\n\n#content #col1{\n float: right;\n width: 160px;\n height: 100px;\n background-color: #eecdcd;\n}\n\n#content #col2{\n height: 100px;\n overflow: hidden;\n background-color: #cdcdee;\n} <div id=\"content\">\n <div id=\"col1\"></div>\n <div id=\"col2\"></div>\n</div>"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] |
144,380
|
<p>I'm writing a game which is taking user input and rendering it on-screen. The engine I'm using for this is entirely unicode-friendly, so I'd like to keep that if at all possible. The problem is that the rendering loop looks like this:</p>
<pre><code>"string".each_byte do |c|
render_this_letter(c)
end
</code></pre>
<p>I don't know a whole lot about i18n, but I know enough to know the above code is only ever going to work for me and people who speak my language. I'd prefer something like:</p>
<pre><code>"unicode string".each_unicode_letter do |u|
render_unicode_letter(u)
end
</code></pre>
<p>Does this exist in the core distribution? I'm somewhat averse to adding additional requirements to the install, but if it's the only way to do it, I'll live.</p>
<p>For extra fun, I have no way of knowing if the string is, in fact, a unicode string.</p>
<p>EDIT: The library I'm using can indeed render entire strings, however I'm letting the user edit what comes up on the fly - if they hit 'backspace', essentially, I need to know how many bytes to chop off the end.</p>
|
[
{
"answer_id": 144384,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "div#col2 {\n padding-left: 160px;\n width: 100%;\n}\n\ndiv#col1 {\n float: left;\n width: 160px;\n}\n #col1 #col2 #col1 #content {\n position: relative; \n}\ndiv#col2 {\n width: 160px;\n position: absolute;\n}\n\ndiv#col1 {\n width: 100%;\n margin-left: 160px;\n}\n div#footer {\n clear: both;\n}\n"
},
{
"answer_id": 144391,
"author": "MattBelanger",
"author_id": 655,
"author_profile": "https://Stackoverflow.com/users/655",
"pm_score": 1,
"selected": false,
"text": "div#col2 {\n width: 160px;\n float: left;\n position: relative;\n}\n\ndiv#col1 {\n width:100%;\n margin-left: 160px;\n}\n"
},
{
"answer_id": 34469081,
"author": "Peyman Mohamadpour",
"author_id": 5104596,
"author_profile": "https://Stackoverflow.com/users/5104596",
"pm_score": 0,
"selected": false,
"text": "#col1 #col2 overflow: hidden #content overflow: hidden #content{\n overflow: hidden;\n padding: 20px 0;\n height: 100px;\n background-color: #cdeecd;\n}\n\n#content #col1{\n float: right;\n width: 160px;\n height: 100px;\n background-color: #eecdcd;\n}\n\n#content #col2{\n height: 100px;\n overflow: hidden;\n background-color: #cdcdee;\n} <div id=\"content\">\n <div id=\"col1\"></div>\n <div id=\"col2\"></div>\n</div>"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2555346/"
] |
144,435
|
<p>I'm looking into a mechanism for serialize data to be passed over a socket or shared-memory in a language-independent mechanism. I'm reluctant to use XML since this data is going to be very structured, and encoding/decoding speed is vital. Having a good C API that's liberally licensed is important, but ideally there should be support for a ton of other languages. I've looked at <a href="http://code.google.com/apis/protocolbuffers/" rel="noreferrer">google's protocol buffers</a> and <a href="http://en.wikipedia.org/wiki/ASN.1" rel="noreferrer">ASN.1</a>. Am I on the right track? Is there something better? Should I just implement my own packed structure and not look for some standard?</p>
|
[
{
"answer_id": 18711717,
"author": "anish",
"author_id": 911576,
"author_profile": "https://Stackoverflow.com/users/911576",
"pm_score": 0,
"selected": false,
"text": "1. Storage\n2. Encoding Style (1 byte 2 byte)\n3. TLV standards\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14032/"
] |
144,439
|
<p>If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path?</p>
<p>I know of <pre>Path.Combine</pre> but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.</p>
<p>e.g:</p>
<pre>
string folder1 = "foo";
string folder2 = "bar";
CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")
</pre>
<p>Any ideas?
Does C# support unlimited args in methods?</p>
|
[
{
"answer_id": 144441,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 5,
"selected": true,
"text": "string CombinePaths(params string[] parts) {\n string result = String.Empty;\n foreach (string s in parts) {\n result = Path.Combine(result, s);\n }\n return result;\n}\n"
},
{
"answer_id": 144449,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 0,
"selected": false,
"text": "public static string CreateDirectoryName(string fileName, params string[] folders)\n{\n if(folders == null || folders.Length <= 0)\n {\n return fileName;\n }\n\n string directory = string.Empty;\n foreach(string folder in folders)\n {\n directory = System.IO.Path.Combine(directory, folder);\n }\n directory = System.IO.Path.Combine(directory, fileName);\n\n return directory;\n}\n"
},
{
"answer_id": 144577,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 3,
"selected": false,
"text": "string[] ary = new string[] { \"c:\\\\\", \"Windows\", \"System\" };\nstring path = ary.Aggregate((aggregation, val) => Path.Combine(aggregation, val));\nConsole.WriteLine(path); //outputs c:\\Windows\\System\n"
},
{
"answer_id": 144587,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": " public static DirectoryInfo Subdirectory(this DirectoryInfo self, params string[] subdirectoryName)\n {\n Array.ForEach(\n subdirectoryName, \n sn => self = new DirectoryInfo(Path.Combine(self.FullName, sn))\n );\n return self;\n }\n self DirectoryInfo di = new DirectoryInfo(\"C:\\\\\")\n .Subdirectory(\"Windows\")\n .Subdirectory(\"System32\");\n\n DirectoryInfo di2 = new DirectoryInfo(\"C:\\\\\")\n .Subdirectory(\"Windows\", \"System32\");\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
144,453
|
<p>I want to get a files these attributes as integer values. </p>
|
[
{
"answer_id": 144461,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 5,
"selected": true,
"text": "FindFirst SearchRec GetFileAttributesEx"
},
{
"answer_id": 144475,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 4,
"selected": false,
"text": "function FileAge(const FileName: string; out FileDateTime: TDateTime): Boolean;\n"
},
{
"answer_id": 146430,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 3,
"selected": false,
"text": "function DSiFileTimeToDateTime(fileTime: TFileTime; var dateTime: TDateTime): boolean;\nvar\n sysTime: TSystemTime;\nbegin\n Result := FileTimeToSystemTime(fileTime, sysTime);\n if Result then\n dateTime := SystemTimeToDateTime(sysTime);\nend; { DSiFileTimeToDateTime }\n\nfunction DSiGetFileTimes(const fileName: string; var creationTime, lastAccessTime,\n lastModificationTime: TDateTime): boolean; \nvar\n fileHandle : cardinal;\n fsCreationTime : TFileTime;\n fsLastAccessTime : TFileTime;\n fsLastModificationTime: TFileTime;\nbegin\n Result := false;\n fileHandle := CreateFile(PChar(fileName), GENERIC_READ, FILE_SHARE_READ, nil,\n OPEN_EXISTING, 0, 0);\n if fileHandle <> INVALID_HANDLE_VALUE then try\n Result :=\n GetFileTime(fileHandle, @fsCreationTime, @fsLastAccessTime,\n @fsLastModificationTime) and\n DSiFileTimeToDateTime(fsCreationTime, creationTime) and\n DSiFileTimeToDateTime(fsLastAccessTime, lastAccessTime) and\n DSiFileTimeToDateTime(fsLastModificationTime, lastModificationTime);\n finally\n CloseHandle(fileHandle);\n end;\nend; { DSiGetFileTimes }\n"
},
{
"answer_id": 153872,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "function GetFileModDate(filename : string) : integer;\nvar\n F : TSearchRec;\nbegin\n FindFirst(filename,faAnyFile,F);\n Result := F.Time;\n //if you wanted a TDateTime, change the return type and use this line:\n //Result := FileDateToDatetime(F.Time);\n FindClose(F);\nend;\n"
},
{
"answer_id": 17166025,
"author": "Ian Murphy",
"author_id": 2496691,
"author_profile": "https://Stackoverflow.com/users/2496691",
"pm_score": 3,
"selected": false,
"text": "function GetFileModDate(filename : string) : TDateTime;\nvar\n F : TSearchRec;\nbegin\n FindFirst(filename,faAnyFile,F);\n Result := F.TimeStamp;\n //if you really wanted an Int, change the return type and use this line:\n //Result := F.Time;\n FindClose(F);\nend;\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
144,466
|
<p>Greetings,</p>
<p>I'm trying to find either a free .NET library or a command-line executable that lets me convert M4A files to either MP3s or WMA files. Please help :).</p>
|
[
{
"answer_id": 6774014,
"author": "cat",
"author_id": 712124,
"author_profile": "https://Stackoverflow.com/users/712124",
"pm_score": 2,
"selected": false,
"text": "ffmpeg -i infile.m4a tmp.wav\nlame tmp.wav outfile.mp3\n #!/bin/bash\n\nn=0\nmaxjobs=3\n\nfor i in *.m4a ; do\n ffmpeg -i \"$i\" \"$TMP/${i%m4a}wav\"\n (lame \"$TMP/${i%m4a}wav\" \"${i%m4a}mp3\" ; rm \"$TMP/${i%m4a}wav\") &\n\n # limit jobs\n if (( $(($((++n)) % $maxjobs)) == 0 )) ; then\n wait\n fi\n\ndone\n"
},
{
"answer_id": 22969234,
"author": "user2217261",
"author_id": 2217261,
"author_profile": "https://Stackoverflow.com/users/2217261",
"pm_score": 0,
"selected": false,
"text": "string fileName = @\"e:\\Down\\test.wmv\";\nDsConvert.ToWma(fileName, fileName + \".wma\", DsConvert.WmaProfile.Stereo128);\n"
},
{
"answer_id": 48091099,
"author": "Amz",
"author_id": 4440556,
"author_profile": "https://Stackoverflow.com/users/4440556",
"pm_score": 2,
"selected": false,
"text": "public class ConvertToMp3Manager\n{\n public PrepareTranscodeResult PrepareTranscode = null;\n public MediaTranscoder TransCoder = null;\n public StorageFile SourceAudio { get; set; }\n public StorageFile DestinationAudio { get; set; }\n public AudioFormat AudioFormat { get; set; }\n public AudioEncodingQuality AudioQuality { get; set; }\n private MediaEncodingProfile profile = null;\n public ConvertToMp3Manager(StorageFile sourceAudio, StorageFile destinationAudio, AudioFormat AudioType = AudioFormat.MP3, AudioEncodingQuality audioEncodingQuality = AudioEncodingQuality.High)\n {\n if (sourceAudio == null || destinationAudio == null)\n throw new ArgumentNullException(\"sourceAudio and destinationAudio cannot be null\");\n switch (AudioType)\n {\n case AudioFormat.AAC:\n case AudioFormat.M4A:\n profile = MediaEncodingProfile.CreateM4a(audioEncodingQuality);\n break;\n case AudioFormat.MP3:\n profile = MediaEncodingProfile.CreateMp3(audioEncodingQuality);\n break;\n case AudioFormat.WMA:\n profile = MediaEncodingProfile.CreateWma(audioEncodingQuality);\n break;\n }\n this.SourceAudio = sourceAudio;\n this.DestinationAudio = destinationAudio;\n this.AudioFormat = AudioType;\n this.AudioQuality = audioEncodingQuality;\n this.TransCoder = new MediaTranscoder();\n }\n /// <summary>\n /// Return true if audio can be transcoded\n /// </summary>\n /// <returns></returns>\n public async Task<bool> ConvertAudioAsync()\n {\n PrepareTranscode = await this.TransCoder.PrepareFileTranscodeAsync(this.SourceAudio, this.DestinationAudio, profile);\n if (PrepareTranscode.CanTranscode)\n {\n var transcodeOp = PrepareTranscode.TranscodeAsync();\n return true;\n }\n else\n return false;\n }\n public static async Task<bool> ConvertAudioAsync(StorageFile sourceAudio, StorageFile destinationAudio, AudioFormat AudioType = AudioFormat.MP3, AudioEncodingQuality audioEncodingQuality = AudioEncodingQuality.High)\n {\n ConvertToMp3Manager convertToMp3Manager = new ConvertToMp3Manager(sourceAudio, destinationAudio, AudioType, audioEncodingQuality);\n var success = await convertToMp3Manager.ConvertAudioAsync();\n return success;\n }\n}\npublic enum AudioFormat\n{\n MP3,\n AAC,\n M4A,\n WMA\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5021/"
] |
144,468
|
<p>Is there a way to track changes in Windows registry? I'd like to see what changes in the registry are made during installation of various programs. </p>
|
[
{
"answer_id": 144629,
"author": "olle",
"author_id": 22422,
"author_profile": "https://Stackoverflow.com/users/22422",
"pm_score": 1,
"selected": false,
"text": "RegistryKeyChangeEvent __InstanceCreationEvent __InstanceDeletionEvent __InstanceModificationEvent"
},
{
"answer_id": 55980128,
"author": "Fidel",
"author_id": 171846,
"author_profile": "https://Stackoverflow.com/users/171846",
"pm_score": 1,
"selected": false,
"text": "HKLM\\SYSTEM HKLM\\SOFTWARE"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11439/"
] |
144,474
|
<p>I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java:</p>
<pre>
Array (
["col_name_1"] => Array (
1 => ["col_value_1"],
2 => ["col_value_2"],
... ,
n => ["col_value_n"]
),
["col_name_n"] => Array (
1 => ["col_value_1"],
2 => ["col_value_2"],
... ,
n => ["col_value_n"]
)
)
</pre>
<p>Is there a clean way (i.e. no dirty code) to save this thing in Java? Note; I would like to use Strings as array indexes (in the first dimension) and I don't know the definite size of the arrays.. </p>
|
[
{
"answer_id": 144485,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": false,
"text": "List<String> col1Vals = new java.util.ArrayList<String>();\ncol1Vals.add(\"col_value_1\");\ncol1Vals.add(\"col_value_2\");\nMap<String, List<String>> map = new HashMap<String, List<String>>();\nmap.put(\"col_name_1\", col1Vals);\n"
},
{
"answer_id": 144486,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 4,
"selected": false,
"text": "Map<String, List<String>> HashMap ArrayList Map<String, List<String>> columns = new HashMap<String, List<String>>() {{\n put(\"col_name_1\", Arrays.asList(\"col_val_1\", \"col_val_2\", \"col_val_n\"));\n put(\"col_name_2\", Arrays.asList(\"col_val_1\", \"col_val_2\", \"col_val_n\"));\n put(\"col_name_n\", Arrays.asList(\"col_val_1\", \"col_val_2\", \"col_val_n\"));\n}};\n"
},
{
"answer_id": 144499,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "import java.util.*;\n\npublic class Foo {\n public static void main(String[] args) {\n Map<String, List<String>> m = new HashMap<String, List<String>>();\n List<String> l = new LinkedList<String>();\n l.add(\"col_value_1\");\n l.add(\"col_value_2\");\n //and so on\n m.put(\"col_name_1\",l); //repeat for the rest of the colnames\n\n //then, to get it you do\n\n List<String> rl = m.get(\"col_name_1\");\n\n }\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6618/"
] |
144,503
|
<p>I initially designed my system following the s# architecture example <a href="http://wwww.codeproject.com/KB/architecture/NHibernateBestPractices.aspx" rel="nofollow noreferrer">outlined in this codeproject article</a> (Unfortunately, I am not using NHibernate). The basic idea is that for each domain object that would need to communicate with the persistence layer you would have a corresponding Data Access Object in a different library. Each Data Access Object implements an interface and when a domain object needs access to a data access method it always codes against an interface and never against the DAOs themselves.</p>
<p>At the time, and still, I thought this design very flexible. However, as the amount of objects in my domain model has grown I am finding myself questioning if there isn't an organizational problem here. For example, almost every object in the domain ends up with a corresponding Data Access Object and Data Access Object interface. Not only that, but each one of these is in a different place which is more difficult to maintain if I want to do something simple like shift around some namespaces.</p>
<p>Interestingly enough, many of these DAOs (and their corresponding interfaces) are very simple creatures - the most common has only a single GetById() method. I end up with a whole bunch of objects such as</p>
<pre><code>public interface ICustomerDao {
Customer GetById(int id);
}
public interface IProductDao {
Product GetById(int id);
}
public interface IAutomaticWeaselDao {
AutomaticWeasel GetById(int id);
}
</code></pre>
<p>Where their implementors are usually very trivial too. This has me wondering if it wouldn't be simpler to go in a different direction, maybe switching my strategy by having a single object for simple data access tasks, and reserving the creation of dedicated Data Access Objects for those that need something a little more complicated.</p>
<pre><code>public interface SimpleObjectRepository {
Customer GetCustomerById(int id);
Product GetProductById(int id);
AutomaticWeasel GetAutomaticWeaselById(int id);
Transaction GetTransactioinById(int id);
}
public interface TransactionDao {
Transaction[] GetAllCurrentlyOngoingTransactionsInitiatedByASweatyGuyNamedCarl();
}
</code></pre>
<p>Does anyone has any experience with an architecture like this? Overall I am very happy with the set-up as it is now my only concern being management of all these little files. I am still wondering however what other approaches toward structuring the Data Access Layer exist.</p>
|
[
{
"answer_id": 144538,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 1,
"selected": false,
"text": "IQueriable T GetById<T>(int id)"
},
{
"answer_id": 144541,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 2,
"selected": false,
"text": "interface DataAccessObject\n{\npublic static function get(array $filters = array(), array $order = array(), array $limit = array());\npublic function insert();\npublic function update(); \npublic function delete();\n}\n class DataAccessObject implements DataAccessObject\n{\n public function __construct($dao_id = null) // So you can construct an empty object\n {\n // Some Code that get the values from the database and assigns them as properties\n }\n public static function get(array $filters = array(), array $order = array(), array $limit = array()) {}; // Code to implement function\n public function insert() {}; // Code to implement function\n public function update() {}; // Code to implement function \n public function delete() {}; // Code to implement function \n}\n"
},
{
"answer_id": 148410,
"author": "Owen",
"author_id": 425,
"author_profile": "https://Stackoverflow.com/users/425",
"pm_score": 2,
"selected": false,
"text": "public class BaseDAO<T> : IDAO<T> \n{\n public T Save(T entity)\n { \n //etc......\n }\n}\npublic class YourDAO : BaseDAO<YourEntity>\n{\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
144,530
|
<p>Why use one over the other?</p>
|
[
{
"answer_id": 144535,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 7,
"selected": true,
"text": "Equals() null Equals() String DateTime =="
},
{
"answer_id": 144562,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 4,
"selected": false,
"text": ".Equals .Equals StringBuilder sb = null;\nif (sb.Equals(null))\n{\n // whatever\n}\n NullReferenceException .Equals .Equals =="
},
{
"answer_id": 12680232,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 2,
"selected": false,
"text": "Equals == == == Equals string == struct class ClassName\n{\n public bool Equals(ClassName other)\n {\n if (other == null)\n {\n return false;\n }\n else\n {\n //Do your equality test here.\n }\n }\n\n public override bool Equals(object obj)\n {\n ClassName other = obj as null; //Null and non-ClassName objects will both become null\n if (obj == null)\n {\n return false;\n }\n else\n {\n return Equals(other);\n }\n }\n\n public bool operator ==(ClassName left, ClassName right)\n {\n if (left == null)\n {\n return right == null;\n }\n else\n {\n return left.Equals(right);\n }\n }\n\n public bool operator !=(ClassName left, ClassName right)\n {\n if (left == null)\n {\n return right != null;\n }\n else\n {\n return !left.Equals(right);\n }\n }\n\n public override int GetHashCode()\n {\n //Return something useful here, typically all members shifted or XORed together works\n }\n}\n"
},
{
"answer_id": 30862396,
"author": "zzfima",
"author_id": 328829,
"author_profile": "https://Stackoverflow.com/users/328829",
"pm_score": 0,
"selected": false,
"text": "public virtual bool Equals(Object obj)\n // Returns a boolean indicating if the passed in object obj is\n// Equal to this. Equality is defined as object equality for reference\n// types and bitwise equality for value types using a loader trick to\n// replace Equals with EqualsValue for value types). \n//\n Object o1 = \"vvv\";\n Object o2 = \"vvv\";\n bool b = o1.Equals(o2);\n\n o1 = 555;\n o2 = 555;\n b = o1.Equals(o2);\n\n o1 = new List<int> { 1, 2, 3 };\n o2 = new List<int> { 1, 2, 3 };\n b = o1.Equals(o2);\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
144,542
|
<p><a href="http://www.ruby-lang.org" rel="noreferrer">Ruby</a> is truly memory-hungry - but also worth every single bit. </p>
<p>What do you do to keep the memory usage low? Do you avoid big strings and use smaller arrays/hashes instead or is it no problem to concern about for you and let the garbage collector do the job?</p>
<p><strong>Edit</strong>: I found a nice article about this topic <a href="http://gnomecoder.wordpress.com/2007/10/02/rubys-garbage-collection-problem/" rel="noreferrer">here</a> - old but still interesting.</p>
|
[
{
"answer_id": 147262,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "Image#destroy!"
},
{
"answer_id": 161164,
"author": "Grant Hutchins",
"author_id": 6304,
"author_profile": "https://Stackoverflow.com/users/6304",
"pm_score": 2,
"selected": false,
"text": "str = ''\nveryLargeArray.each do |foo|\n str += foo\n # but str << foo is fine (read update below)\nend\n Array#join str = veryLargeArray.join('')\n += <<"
},
{
"answer_id": 13758791,
"author": "tokhi",
"author_id": 277740,
"author_profile": "https://Stackoverflow.com/users/277740",
"pm_score": 3,
"selected": false,
"text": "100.times{ 'foo' }\n {'joe' => 'male', 'jane' => 'female'} hash[current_user.name.to_sym] = something\n ruby-1.9.2-head >\n# Current memory usage : 6608K\n# Now, add one million randomly generated short symbols\nruby-1.9.2-head > 1000000.times { (Time.now.to_f.to_s).to_sym }\n\n# Current memory usage : 153M, even after a Garbage collector run.\n\n# Now, imagine if symbols are just 20x longer than that ?\nruby-1.9.2-head > 1000000.times { (Time.now.to_f.to_s * 20).to_sym }\n# Current memory usage : 501M\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18179/"
] |
144,550
|
<p><strong>Problem:</strong></p>
<p>Ajax suggest-search on [<em>n</em>] ingredients in recipes. That is: match recipes against multiple ingredients.</p>
<p>For instance: <code>SELECT Recipes using "flower", "salt"</code> would produce: <code>"Pizza", "Bread", "Saltwater"</code> and so forth.</p>
<p><strong>Tables:</strong></p>
<pre><code>Ingredients [
IngredientsID INT [PK],
IngredientsName VARCHAR
]
Recipes [
RecipesID INT [PK],
RecipesName VARCHAR
]
IngredientsRecipes [
IngredientsRecipesID INT [PK],
IngredientsID INT,
RecipesID INT
]
</code></pre>
<p><strong>Query:</strong></p>
<pre><code>SELECT
Recipes.RecipesID,
Recipes.RecipesName,
Ingredients.IngredientsID,
Ingredients.IngredientsName
FROM
IngredientsRecipes
INNER JOIN Ingredients
ON IngredientsRecipes.IngredientsID = Ingredients.IngredientsID
INNER JOIN Recipes
ON IngredientsRecipes.RecipesID = Recipes.RecipesID
WHERE
Ingredients.IngredientsName IN ('salt', 'water', 'flower')
</code></pre>
<p>I am currently constructing my query using ASP.NET C# because of the dynamic nature of the <code>WHERE</code> clause.</p>
<p>I bites that I have to construct the query in my code-layer instead of using a stored procedure/pure SQL, which in theory should be much faster.</p>
<p>Have you guys got any thoughts on how I would move all of the logic from my code-layer to pure SQL, or at least how I can optimize the performance of what I'm doing?</p>
<p>I am thinking along the lines of temporary tables:</p>
<p><strong>Step one</strong>: <code>SELECT IngredientsID FROM Ingredients</code> and <code>INSERT INTO temp-table</code></p>
<p><strong>Step two</strong>: <code>SELECT RecipesName FROM Recipes</code> joined with <code>IngredientsRecipes</code> joined with <code>temp-table.IngredientsID</code></p>
|
[
{
"answer_id": 144626,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 2,
"selected": false,
"text": "using System.Data;\nusing System.Data.SqlClient;\nusing System.Text;\n\nclass Foo\n{\n public static void Main ()\n {\n string[] parameters = {\"salt\", \"water\", \"flower\"};\n SqlConnection connection = new SqlConnection ();\n SqlCommand command = connection.CreateCommand ();\n StringBuilder where = new StringBuilder ();\n for (int i = 0; i < parametes.Length; i++)\n {\n if (i != 0)\n where.Append (\",\");\n where.AppendFormat (\"@Param{0}\", i);\n command.Parameters.Add (new SqlParameter (\"Param\" + i, parameters [i]));\n }\n }\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
144,570
|
<p>I thought that there was some way in .net 3.0 to give an array list a type so that it didnt just return Object's but I'm having trouble doing so. Is it possible? If so, how?</p>
|
[
{
"answer_id": 144574,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 2,
"selected": false,
"text": "<T>"
},
{
"answer_id": 144575,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "List<T> using System.Collections.Generic;\n\nvar list = new List<int>();\nlist.Add(1);\nlist.Add(\"string\"); //compile-time error!\nint i = list[0];\n"
},
{
"answer_id": 144595,
"author": "Mark",
"author_id": 18264,
"author_profile": "https://Stackoverflow.com/users/18264",
"pm_score": -1,
"selected": false,
"text": " string[] stringArray = myArrayList.ToArray(typeof(string)) as string[];\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] |
144,583
|
<p>I'm looking for a really good dialog resizer class that will stretch and shrink individual items as needed as the screen is resized. Stephan Keil has a good one (DlgResizeHelper) which basically resizes everything by a set ratio, but I'm looking for something smarter.</p>
<p>For example:</p>
<ul>
<li><p>Icons should not resize</p></li>
<li><p>Single-line text boxes should not be stretched vertically</p></li>
<li><p>Buttons should probably stay the same size</p></li>
</ul>
<p>Basically I'm looking for something to look at all of the controls, figure out that a static text field is related to a control next/below it and anchor the two together, and resize large controls in a 'smart' way so it looks good.</p>
<p>Are there such frameworks out there? I've been working on one but something ready-made would probably be better.</p>
<p>FOLLOW UP: I'm looking at the suggested solutions. Many of them require you to go in an anchor each control on the dialog. I'm looking for something smart that will figure out what the anchors ought to be, with the ability to manually anchor if the guesses are wrong. Seems like it should be possible -- most humans would agree a static text field next to an edit field should be anchored together. Guess I'm almost looking for a little AI here :)</p>
|
[
{
"answer_id": 144945,
"author": "Sergey Kornilov",
"author_id": 10969,
"author_profile": "https://Stackoverflow.com/users/10969",
"pm_score": 0,
"selected": false,
"text": "SetResize(IDC_EDIT1, 0, 0, 0.5, 1);\nSetResize(IDC_EDIT2, 0.5, 0, 1, 1);\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7442/"
] |
144,630
|
<p>I am working on an ASP.NET MVC web app that allows people to publish content, but other than publish the content to a remote server, I want to allow people to use their domain name directly. For example, the user "Tom" can have his domain name TomSite.com point to <a href="http://www.mywebapp.com/user/tom" rel="nofollow noreferrer">http://www.mywebapp.com/user/tom</a>, but the sub path will also be mapped. For example, TomSite.com/path will be mapped to www.mywebapp.com/user/tom/path, and this is transparent to the web visitor. The visitor will never see "mywebapp.com" anywhere on TomSite.com.</p>
<p>I think Smugmug.com provides such service, to allow people to use their own domain name for the photo portfolio. I want to achieve the same result.</p>
<p>How can I do this? Thanks!</p>
|
[
{
"answer_id": 145544,
"author": "Troels Thomsen",
"author_id": 20138,
"author_profile": "https://Stackoverflow.com/users/20138",
"pm_score": 3,
"selected": true,
"text": "if (Dns.GetHostEntry(\"www.user.example.com\").HostName == \"www.example.com\")\n{\n // www.user.example.com is a CNAME for www.example.com\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20067/"
] |
144,639
|
<p>By default (using the <code>plain</code> style) BibTeX orders citations alphabetically. </p>
<p>How to order the citations by order of appearance in the document?</p>
|
[
{
"answer_id": 144640,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 5,
"selected": false,
"text": "unsrt plain \\bibliographystyle{unsrt}\n\\bibliography{bibliography}\n"
},
{
"answer_id": 144665,
"author": "lindelof",
"author_id": 1428,
"author_profile": "https://Stackoverflow.com/users/1428",
"pm_score": 4,
"selected": false,
"text": "unsrt"
},
{
"answer_id": 145207,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 9,
"selected": true,
"text": "unsrt makebst biblatex biblatex \\documentclass[12pt]{article}\n\\usepackage[sorting=none]{biblatex}\n\\bibliography{journals,phd-references} % Where journals.bib and phd-references.bib are BibTeX databases\n\\begin{document}\n\\cite{robertson2007}\n\\cite{earnshaw1842}\n\\printbibliography\n\\end{document}\n"
},
{
"answer_id": 790387,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "unsrt \\bibliographystyle{ieeetr}"
},
{
"answer_id": 1514189,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "\\bibliographystyle{plain}\n \\bibliographystyle{ieeetr}\n .aux .bbl .aux .bbl"
},
{
"answer_id": 6562312,
"author": "sdaau",
"author_id": 277826,
"author_profile": "https://Stackoverflow.com/users/277826",
"pm_score": 5,
"selected": false,
"text": "...\nITERATE {presort}\n\nSORT\n...\n ...\n%% % avoid sort:\n%% ITERATE {presort}\n%%\n%% SORT\n...\n bibtex pdflatex pdflatex"
},
{
"answer_id": 13630446,
"author": "Tung",
"author_id": 865603,
"author_profile": "https://Stackoverflow.com/users/865603",
"pm_score": 2,
"selected": false,
"text": "natbib"
},
{
"answer_id": 16787602,
"author": "kebs",
"author_id": 193789,
"author_profile": "https://Stackoverflow.com/users/193789",
"pm_score": 0,
"selected": false,
"text": "\\documentclass{article}\n\n\\usepackage{databib}\n\n\\begin{document}\n% First argument is the name of new datatool database\n% Second argument is list of .bib files\n\\DTLloadbbl{mybibdata}{acmtr}\n% Sort database in order of year starting from most recent\n\\DTLsort{Year=descending}{mybibdata}\n% Add citations\n\\nocite{*}\n\n% Display bibliography\n\\DTLbibliography{mybibdata}\n\\end{document}\n"
},
{
"answer_id": 18217511,
"author": "Guest",
"author_id": 2679929,
"author_profile": "https://Stackoverflow.com/users/2679929",
"pm_score": 1,
"selected": false,
"text": "amsrefs \\usepackage{amsrefs}"
},
{
"answer_id": 25329083,
"author": "HeWhoLikesWaffles",
"author_id": 2796499,
"author_profile": "https://Stackoverflow.com/users/2796499",
"pm_score": 3,
"selected": false,
"text": "\\documentclass{article}\n\\begin{document}\n\nSo basically this is where the body of your document goes.\n\n``FreeBSD is easy to install,'' said no one ever \\cite{drugtrafficker88}.\n\n``Yeah well at least I've got chicken,'' said Leeroy Jenkins \\cite{goodenough04}.\n\n\\newpage\n\\bibliographystyle{ieeetr} % Use ieeetr to list refs in the order they're cited\n\\bibliography{references} % Or whatever your .bib file is called\n\\end{document}\n @ARTICLE{ goodenough04,\nAUTHOR = \"G. D. Goodenough and others\", \nTITLE = \"What it's like to have a sick-nasty last name\",\nJOURNAL = \"IEEE Trans. Geosci. Rem. Sens.\",\nYEAR = \"xxxx\",\nvolume = \"xx\",\nnumber = \"xx\",\npages = \"xx--xx\"\n}\n@BOOK{ drugtrafficker88,\nAUTHOR = \"G. Drugtrafficker\", \nTITLE = \"What it's Like to Have a Misleading Last Name\",\nYEAR = \"xxxx\",\nPUBLISHER = \"Harcourt Brace Jovanovich, Inc.\"\nADDRESS = \"The Florida Alps, FL, USA\"\n}\n"
},
{
"answer_id": 41662000,
"author": "Tshilidzi Mudau",
"author_id": 5695374,
"author_profile": "https://Stackoverflow.com/users/5695374",
"pm_score": 0,
"selected": false,
"text": "natbib bibliographystyle{apa} \\begin{document}\n\nThe body of the document goes here...\n\n\\newpage\n\n\\bibliography{bibliography} % Or whatever you decided to call your .bib file \n\n\\usepackage[round, comma, sort&compress ]{natbib} \n\nbibliographystyle{apa}\n\\end{document}\n"
},
{
"answer_id": 59255825,
"author": "Malak",
"author_id": 10474966,
"author_profile": "https://Stackoverflow.com/users/10474966",
"pm_score": 2,
"selected": false,
"text": "\\bibliographystyle{unsrt}\n"
},
{
"answer_id": 68309810,
"author": "sepideha",
"author_id": 6762269,
"author_profile": "https://Stackoverflow.com/users/6762269",
"pm_score": 2,
"selected": false,
"text": "\\usepackage{cite} \\bibliographystyle{unsrt}"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199/"
] |
144,642
|
<p>I require a tree / directed acyclic graph implementation something like this:</p>
<pre><code>public class TreeNode<K, V> {
private K key; // 'key' for this node, always present
private V value; // 'value' for this node, doesn't have to be set
private TreeNode<K, V> parent;
private Set<TreeNode<K, V>> children;
}
</code></pre>
<ul>
<li>There is no sorting of any kind. </li>
<li>The <code>TreeNode</code> is just a wrapper around the key and a possible value (nodes don't have to have values set).</li>
<li>I require links to both the parent and the children.</li>
</ul>
<p>Is there anything out there in the standard APIs or Commons etc that will do this for me?</p>
<p>I don't mind writing it myself (and I'm certainly <strong>not</strong> asking you folks to) I just don't want to re-invent the wheel.</p>
|
[
{
"answer_id": 144652,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 5,
"selected": true,
"text": "public class TreeNode<T>\n{\n private LinkedList<TreeNode<T>> children = new LinkedList<TreeNode<T>>();\n public T value { get; set; }\n\n public TreeNode(T value)\n {\n this.value = value;\n }\n public LinkedList<TreeNode<T>> GetChildren()\n {\n return children;\n }\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] |
144,651
|
<p>I've the following rewrite rule in .htaccess:</p>
<pre><code>RewriteRule ^groups/([^/\.]+)/?$ groupdetail.php?gname=$1 [L,NC]
</code></pre>
<p>This takes something like www.example.com/groups/groupname and calls www.example/groupdetail.php?gname=groupname. And it works just fine.</p>
<p>But all the relative links on groupdetail.php use groups/ as the relative path, and I don't want them to. How do I avoid this?</p>
<p>For example, when a user clicks on a link <code><a href="link.php"></code> on groupdetail.php?gname=groupname, he's taken to www.example/groups/link.php. I want to take the user to www.example.com/link.php.</p>
<p>Obviously, I want to URL to the user to look like "www.example.com/groups/groupname" so I don't want to use [R]/redirect.</p>
|
[
{
"answer_id": 144676,
"author": "Kevin Hakanson",
"author_id": 22514,
"author_profile": "https://Stackoverflow.com/users/22514",
"pm_score": 1,
"selected": false,
"text": "RewriteRule ^groups/([^/.]+)/?$ groupdetail.php?gname=$1 [L,NC,R]\n"
},
{
"answer_id": 155824,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "../link.php"
},
{
"answer_id": 206759,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<base href=\"\"> <head> <head>"
},
{
"answer_id": 609368,
"author": "Andy Swift",
"author_id": 72958,
"author_profile": "https://Stackoverflow.com/users/72958",
"pm_score": 0,
"selected": false,
"text": "www.example.com/groups/groupname /groups <a href=link.php> /groups www.example.com/groups/link.php <a href=/link.php> www.example.com/link.php"
},
{
"answer_id": 8336673,
"author": "Robin",
"author_id": 1074745,
"author_profile": "https://Stackoverflow.com/users/1074745",
"pm_score": 2,
"selected": false,
"text": "<base> echo '<base href=\"http://'.$_SERVER['SERVER_NAME'].str_replace(\"index.php\",\"\",$_SERVER['PHP_SELF']).'\" />';\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
144,657
|
<p>I have a Java program that uses Hibernate and MySQL to store a lot of tracing data about the use of the Eclipse IDE. This data contains a lot of strings such as method names, directories, perspective name, etc. </p>
<p>For example, an event object (which is then reflected in a record) can specify the source file and the current method, the user name, etc. Obviously, string data can repeat itself. </p>
<p>As long as it's in memory, much of it is internalized so all repeated string instances point to the same object (I make sure of that). However, with @Basic (I use annotations), Hibernate maps it into a VARCHAR(255), which means a lot of wasted space.</p>
<p>If I was coding the SQL myself, I could have replaced the VARCHAR with an index to a manually-managed string lookup table and saved the space (at the cost of extra lookups). </p>
<p>Is there some way to get Hibernate to do this for me? I'm willing to pay the performance hit for the space.</p>
|
[
{
"answer_id": 144674,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "class StringHolder {\n private Long id;\n private String string;\n\n public StringHolder() {/* Not sure if this is necessary */}\n\n public StringHolder(String string) {\n this.string = string;\n }\n\n public void getString() {\n return this.string;\n }\n}\n"
},
{
"answer_id": 144721,
"author": "Sam Martin",
"author_id": 19088,
"author_profile": "https://Stackoverflow.com/users/19088",
"pm_score": 1,
"selected": false,
"text": "class Foo {\n // client code uses this to get the value... ignored by Hibernate\n @Transient\n public String getString() {\n return getStringHolder().getString();\n }\n\n public StringHolder getStringHolder() {...}\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23072/"
] |
144,659
|
<p>So I managed to get a page with Ajax <a href="http://docs.jquery.com/UI/Tabs" rel="nofollow noreferrer">ui.tab</a> and in one of the tab I put <a href="http://projects.bundleweb.com.ar/jWYSIWYG/" rel="nofollow noreferrer">jWYSIWYG</a> textarea plugin. Unfortunately, I can only see normal textarea.</p>
<p>However, accessing the page directly (ie. not using the ajax tab) works.</p>
<p>What happened?</p>
<p>p/s: I'm new to jQuery / JavaScript / AJAX / CSS (if that even matter)</p>
|
[
{
"answer_id": 1541706,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$('#dialogContent').bind('dialogopen', function(event, ui) {\n $('textarea').wysiwyg( {\n css :burl + 'public/css/text.css',\n controls : {\n separator00 : { visible : false },\n separator01 : { visible : false },\n separator02 : { visible : false },\n separator03 : { visible : false },\n separator04 : { visible : false },\n separator05 : { visible : false },\n separator06 : { visible : false },\n separator07 : { visible : false },\n separator08 : { visible : false },\n separator09 : { separator : false},\n insertOrderedList : { visible : true },\n insertUnorderedList : { visible : true },\n undo: { visible : true },\n redo: { visible : true },\n justifyLeft: { visible : true },\n justifyCenter: { visible : true },\n justifyFull: { visible : true },\n subscript: { visible : false },\n superscript: { visible : false },\n underline: { visible : true },\n increaseFontSize : { visible : false },\n decreaseFontSize : { visible : false },\n removeFormat : { visible : false },\n h1mozilla : { visible : false },\n h2mozilla : { visible : false },\n h3mozilla : { visible : false },\n h1 : { visible : false },\n h2 : { visible : false },\n h3 : { visible : false }\n }\n });\n $('.wysiwyg').css( {\n 'width' :'350px'\n ,'height' :'180px'\n });\n $('.wysiwyg iframe').css( {\n 'width' :'350px'\n ,'height' :'150px'\n });\n}).bind('dialogbeforeclose', function(event, ui) {\n $('.wysiwyg').remove();\n});\n"
},
{
"answer_id": 1952004,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$(\"#example\").tabs();\n$('#example').bind('tabsshow', function(event, ui) {\n if (ui.tab.id == \"alinkid\") {\n $('#textfield').wysiwyg();\n }\n});\n <div id=\"example\">\n <ul>\n <li><a href=\"target\" id=\"alinkid\">Target</a></li>\n </ul>\n</div>\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15345/"
] |
144,661
|
<p>I'm currently primarily a <a href="https://en.wikipedia.org/wiki/D_(programming_language)" rel="nofollow noreferrer">D</a> programmer and am looking to add another language to my toolbox, preferably one that supports the metaprogramming hacks that just can't be done in a statically compiled language like D.</p>
<p>I've read up on Lisp a little and I would love to find a language that allows some of the cool stuff that Lisp does, but without the strange syntax, etc. of Lisp. I don't want to start a language flame war, and I'm sure both Ruby and Python have their tradeoffs, so I'll list what's important to me personally. Please tell me whether Ruby, Python, or some other language would be best for me.</p>
<p>Important:</p>
<ol>
<li>Good metaprogramming. Ability to create classes, methods, functions, etc. at runtime. Preferably, minimal distinction between code and data, Lisp style.</li>
<li>Nice, clean, sane syntax and consistent, intuitive semantics. Basically a well thought-out, fun to use, modern language.</li>
<li>Multiple paradigms. No one paradigm is right for every project, or even every small subproblem within a project.</li>
<li>An interesting language that actually affects the way one thinks about programming.</li>
</ol>
<p>Somewhat important:</p>
<ol>
<li>Performance. It would be nice if performance was decent, but when performance is a real priority, I'll use D instead.</li>
<li>Well-documented. </li>
</ol>
<p>Not important:</p>
<ol>
<li>Community size, library availability, etc. None of these are characteristics of the language itself, and all can change very quickly.</li>
<li>Job availability. I am not a full-time, professional programmer. I am a grad student and programming is tangentially relevant to my research.</li>
<li>Any features that are primarily designed with very large projects worked on by a million code monkeys in mind.</li>
</ol>
|
[
{
"answer_id": 395999,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "myList myList.collect { |f| f.description }.select { |d| d != \"\" }.join(\"\\n\")\n myList.map(&:description).reject(&:empty?).join(\"\\n\")\n descriptions = (f.description() for f in mylist)\n\"\\n\".join(filter(len, descriptions)) \n \"\\n\".join(f.description() for f in mylist if f.description())\n join \"\\n\", grep { $_ } map { $_->description } @myList;\n join \"\\n\", grep /./, map { $_->description } @myList;\n myList.map(function(e) e.description())\n .filter(function(e) e).join(\"\\n\")\n myList collect(description) select(!=\"\") join(\"\\n\")\n"
},
{
"answer_id": 1202966,
"author": "Benjamin Oakes",
"author_id": 146764,
"author_profile": "https://Stackoverflow.com/users/146764",
"pm_score": 3,
"selected": false,
"text": "#ruby-lang"
},
{
"answer_id": 4840723,
"author": "Eric Davidson",
"author_id": 595467,
"author_profile": "https://Stackoverflow.com/users/595467",
"pm_score": 3,
"selected": false,
"text": "class Ninja\n def rank\n puts \"Orange Clan\"\n end\n\n self.name #=> \"Ninja\"\nend\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23903/"
] |
144,669
|
<p>I've removed a checked in file from the CVS branch, i.e.:</p>
<pre><code>cvs remove -f file.txt
cvs commit
</code></pre>
<p>How do I restore the file?</p>
|
[
{
"answer_id": 144672,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 6,
"selected": true,
"text": "cvs add file.txt\ncvs commit file.txt\n"
},
{
"answer_id": 145377,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 5,
"selected": false,
"text": "cvs add cvs remove $ cvs remove -f file.txt\n$ cvs add file.txt\n $ cvs remove -f file.txt\n$ cvs commit\n$ cvs add file.txt\n cvs status file.txt $ cvs update -p -r rev file.txt > file.txt\n$ cvs add file.txt\n$ cvs commit\n"
},
{
"answer_id": 145418,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 2,
"selected": false,
"text": "C:\\foo>dir\n Volume in drive C is Local Disk\n Volume Serial Number is 344F-1517\n\n Directory of C:\\foo\n\n28/09/2008 05:12 PM <DIR> .\n28/09/2008 05:12 PM <DIR> ..\n28/09/2008 05:12 PM <DIR> CVS\n28/09/2008 05:11 PM 19 file.txt\n 1 File(s) 19 bytes\n 3 Dir(s) 22,686,416,896 bytes free\n\nC:\\foo>cvs status file.txt\n===================================================================\nFile: file.txt Status: Up-to-date\n\n Working revision: 1.2 Sun Sep 28 07:11:58 2008\n Repository revision: 1.2 C:\\jason\\CVSROOT/foo/file.txt,v\n Sticky Tag: (none)\n Sticky Date: (none)\n Sticky Options: (none)\n\n\nC:\\foo>cvs rm -f file.txt\ncvs remove: scheduling `file.txt' for removal\ncvs remove: use 'cvs commit' to remove this file permanently\n\nC:\\foo>cvs commit -m \"\" file.txt\nRemoving file.txt;\nC:\\jason\\CVSROOT/foo/file.txt,v <-- file.txt\nnew revision: delete; previous revision: 1.2\ndone\n\nC:\\foo>cvs status file.txt\n===================================================================\nFile: no file file.txt Status: Up-to-date\n\n Working revision: No entry for file.txt\n Repository revision: 1.3 C:\\jason\\CVSROOT/foo/Attic/file.txt,v\n\nC:\\foo>more file.txt\nCannot access file C:\\foo\\file.txt\n\nC:\\foo>dir\n Volume in drive C is Local Disk\n Volume Serial Number is 344F-1517\n\n Directory of C:\\foo\n\n28/09/2008 05:12 PM <DIR> .\n28/09/2008 05:12 PM <DIR> ..\n28/09/2008 05:12 PM <DIR> CVS\n 0 File(s) 0 bytes\n 3 Dir(s) 22,686,400,512 bytes free\n\nC:\\foo>cvs add file.txt\ncvs add: Resurrecting file `file.txt' from revision 1.2.\nU file.txt\ncvs add: Re-adding file `file.txt' (in place of dead revision 1.3).\ncvs add: use 'cvs commit' to add this file permanently\n\nC:\\foo>cvs commit -m \"\" file.txt\nChecking in file.txt;\nC:\\jason\\CVSROOT/foo/file.txt,v <-- file.txt\nnew revision: 1.4; previous revision: 1.3\ndone\n\nC:\\foo>more file.txt\nThis is a test...\n\nC:\\jason\\work\\dev1\\nrta\\foo>dir\n Volume in drive C is Local Disk\n Volume Serial Number is 344F-1517\n\n Directory of C:\\jason\\foo\n\n28/09/2008 05:15 PM <DIR> .\n28/09/2008 05:15 PM <DIR> ..\n28/09/2008 05:13 PM <DIR> CVS\n28/09/2008 05:13 PM 19 file.txt\n 1 File(s) 19 bytes\n 3 Dir(s) 22,686,375,936 bytes free\n"
},
{
"answer_id": 145462,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 2,
"selected": false,
"text": "cvs add"
},
{
"answer_id": 11774387,
"author": "vvkatwss vvkatwss",
"author_id": 1150448,
"author_profile": "https://Stackoverflow.com/users/1150448",
"pm_score": 2,
"selected": false,
"text": "cvs add file.txt\ncvs update file.txt\ncvs commit file.txt\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4704/"
] |
144,701
|
<p>I frequently start with a simple console application to try out an idea, then create a new GUI based project and copy the code in. Is there a better way? Can I convert my existing console application easily?</p>
|
[
{
"answer_id": 144720,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 7,
"selected": true,
"text": "Main Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n [STAThread] Main"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
] |
144,713
|
<p>I have an XML document with un-namespaced elements, and I want to use XSLT to add namespaces to them. Most elements will be in namespace A; a few will be in namespace B. How do I do this?</p>
|
[
{
"answer_id": 144724,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 1,
"selected": false,
"text": "<xsl:template match=\"*\">\n <xsl:element name=\"{local-name()}\" namespace=\"A\" >\n <xsl:apply-templates />\n </xsl:element>\n</xsl:template>\n\n<xsl:template match=\"a-special-element\">\n <B:a-special-element xmlns:B=\"B\">\n <xsl:apply-templates />\n </B:a-special-element>\n</xsl:template>\n"
},
{
"answer_id": 144752,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 2,
"selected": false,
"text": "namespace xsl:element <xsl:template match=\"*\">\n <xsl:element name=\"xmpl:{local-name()}\" namespace=\"http://example.com/\">\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:element>\n</xsl:template>\n\n<xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n"
},
{
"answer_id": 144775,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 5,
"selected": true,
"text": "<foo x=\"1\">\n <bar y=\"2\">\n <baz z=\"3\"/>\n </bar>\n <a-special-element n=\"8\"/>\n</foo>\n <xsl:template match=\"*\">\n <xsl:element name=\"{local-name()}\" namespace=\"A\" >\n <xsl:copy-of select=\"attribute::*\"/>\n <xsl:apply-templates />\n </xsl:element>\n </xsl:template>\n\n <xsl:template match=\"a-special-element\">\n <B:a-special-element xmlns:B=\"B\">\n <xsl:apply-templates match=\"children()\"/>\n </B:a-special-element>\n </xsl:template>\n\n</xsl:transform>\n <foo xmlns=\"A\" x=\"1\">\n <bar y=\"2\">\n <baz z=\"3\"/>\n </bar>\n <B:a-special-element xmlns:B=\"B\"/>\n</foo>\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
] |
144,731
|
<p>Are there any commonly used patterns in Javascript for storing the URL's of endpoints that will be requested in an AJAX application?</p>
<p>For example would you create a "Service" class to abstract the URL's away?</p>
|
[
{
"answer_id": 146844,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 1,
"selected": false,
"text": "function ControlValuePair(Id, Value)\n{ \n this.Id = Id;\n this.Value = Value;\n}\n\nfunction CreateCollection(ClassName) \n{\n var obj=new Array();\n eval(\"var t=new \"+ClassName+\"()\");\n for(_item in t)\n {\n eval(\"obj.\"+_item+\"=t.\"+_item);\n }\n return obj;\n}\n\nfunction ValuePairsCollection()\n{\n this.Container=\"\";\n this.Add=function(obj)\n {\n this.push(obj);\n }\n}\n"
},
{
"answer_id": 177089,
"author": "Ben Crouse",
"author_id": 6705,
"author_profile": "https://Stackoverflow.com/users/6705",
"pm_score": 1,
"selected": true,
"text": "NAMESPACE.categories.baseUri = '/categories';\nNAMESPACE.categories.getUri = function(options)\n{\n options = options || {};\n var uri = [NAMESPACE.categories.baseUri];\n\n if(options.id)\n {\n uri.push(options.id); \n }\n if(options.action)\n {\n uri.push(options.action);\n }\n if(options.format)\n {\n uri.push('?format=' + options.format);\n }\n\n return uri.join('/');\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21875/"
] |
144,745
|
<p>The prompt says that if I install the software into a directory with spaces:</p>
<blockquote>
<p>the rebuild build tool used by the D Shared Source System will fail to build</p>
</blockquote>
<p>and that I will be</p>
<blockquote>
<p>forced to reinstall in a different location</p>
</blockquote>
<p>However, I don't like random things in my C:\ drive. D, IMO, belongs in Program Files with PHP and MinGW and so on. How can I get it here?</p>
<p>If it matters, I'm using the Easy D installer package.</p>
|
[
{
"answer_id": 144763,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "subst subst x: \"c:\\program files\\d\"\n"
},
{
"answer_id": 144867,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 4,
"selected": true,
"text": "C:\\Program Files\\ C:\\ProgramFiles\\"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
144,761
|
<p>I have a problem with a string in C++ which has several words in Spanish. This means that I have a lot of words with accents and tildes. I want to replace them for their not accented counterparts. Example: I want to replace this word: "había" for habia. I tried replace it directly but with replace method of string class but I could not get that to work.</p>
<p>I'm using this code:</p>
<pre><code>for (it= dictionary.begin(); it != dictionary.end(); it++)
{
strMine=(it->first);
found=toReplace.find_first_of(strMine);
while (found!=std::string::npos)
{
strAux=(it->second);
toReplace.erase(found,strMine.length());
toReplace.insert(found,strAux);
found=toReplace.find_first_of(strMine,found+1);
}
}
</code></pre>
<p>Where <code>dictionary</code> is a map like this (with more entries):</p>
<pre><code>dictionary.insert ( std::pair<std::string,std::string>("á","a") );
dictionary.insert ( std::pair<std::string,std::string>("é","e") );
dictionary.insert ( std::pair<std::string,std::string>("í","i") );
dictionary.insert ( std::pair<std::string,std::string>("ó","o") );
dictionary.insert ( std::pair<std::string,std::string>("ú","u") );
dictionary.insert ( std::pair<std::string,std::string>("ñ","n") );
</code></pre>
<p>and <code>toReplace</code> strings is:</p>
<pre><code>std::string toReplace="á-é-í-ó-ú-ñ-á-é-í-ó-ú-ñ";
</code></pre>
<p>I obviously must be missing something. I can't figure it out.
Is there any library I can use?.</p>
<p>Thanks,</p>
|
[
{
"answer_id": 144769,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": -1,
"selected": false,
"text": "tr tr sed #!/bin/sed -f\ns/á/a/g;\ns/é/e/g;\ns/í/i/g;\ns/ó/o/g;\ns/ú/u/g;\ns/ñ/n/g;\n"
},
{
"answer_id": 144804,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 5,
"selected": true,
"text": "NFD; [:M:] remove; NFC\n"
},
{
"answer_id": 145373,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 2,
"selected": false,
"text": "std::wstring #include <iostream>\n#include <string>\n#include <iterator>\n#include <algorithm>\n#include \"translate_characters.h\"\n\nusing namespace std;\n\nint main()\n{\n string text;\n cin.unsetf(ios::skipws);\n transform(istream_iterator<char>(cin), istream_iterator<char>(),\n inserter(text, text.end()), translate_characters());\n cout << text << endl;\n return 0;\n}\n #ifndef TRANSLATE_CHARACTERS_H\n#define TRANSLATE_CHARACTERS_H\n\n#include <functional>\n#include <map>\n\nclass translate_characters : public std::unary_function<const char,char> {\npublic:\n translate_characters();\n char operator()(const char c);\n\nprivate:\n std::map<char, char> characters_map;\n};\n\n#endif // TRANSLATE_CHARACTERS_H\n #include \"translate_characters.h\"\n\nusing namespace std;\n\ntranslate_characters::translate_characters()\n{\n characters_map.insert(make_pair('e', 'a'));\n}\n\nchar translate_characters::operator()(const char c)\n{\n map<char, char>::const_iterator translation_pos(characters_map.find(c));\n if( translation_pos == characters_map.end() )\n return c;\n return translation_pos->second;\n}\n"
},
{
"answer_id": 147369,
"author": "Alejo",
"author_id": 23084,
"author_profile": "https://Stackoverflow.com/users/23084",
"pm_score": 0,
"selected": false,
"text": "for (it= dictionary.begin(); it != dictionary.end(); it++)\n{\n strMine=(it->first);\n found=toReplace.find(strMine);\n while (found != std::string::npos)\n {\n strAux=(it->second);\n toReplace.erase(found,2);\n toReplace.insert(found,strAux);\n found=toReplace.find(strMine,found+1);\n }\n} \n"
},
{
"answer_id": 52972055,
"author": "vince",
"author_id": 10552815,
"author_profile": "https://Stackoverflow.com/users/10552815",
"pm_score": -1,
"selected": false,
"text": " /// <summary>\n /// \n /// Replace any accent and foreign character by their ASCII equivalent.\n /// In other words, convert a string to an ASCII-complient string.\n /// \n /// This also get rid of special hidden character, like EOF, NUL, TAB and other '\\0', except \\n\\r\n /// \n /// Tests with accents and foreign characters:\n /// Before: \"äæǽaeöœoeüueÄAeÜUeÖOeÀÁÂÃÄÅǺĀĂĄǍΑΆẢẠẦẪẨẬẰẮẴẲẶАAàáâãåǻāăąǎªαάảạầấẫẩậằắẵẳặаaБBбbÇĆĈĊČCçćĉċčcДDдdÐĎĐΔDjðďđδdjÈÉÊËĒĔĖĘĚΕΈẼẺẸỀẾỄỂỆЕЭEèéêëēĕėęěέεẽẻẹềếễểệеэeФFфfĜĞĠĢΓГҐGĝğġģγгґgĤĦHĥħhÌÍÎÏĨĪĬǏĮİΗΉΊΙΪỈỊИЫIìíîïĩīĭǐįıηήίιϊỉịиыїiĴJĵjĶΚКKķκкkĹĻĽĿŁΛЛLĺļľŀłλлlМMмmÑŃŅŇΝНNñńņňʼnνнnÒÓÔÕŌŎǑŐƠØǾΟΌΩΏỎỌỒỐỖỔỘỜỚỠỞỢОOòóôõōŏǒőơøǿºοόωώỏọồốỗổộờớỡởợоoПPпpŔŖŘΡРRŕŗřρрrŚŜŞȘŠΣСSśŝşșšſσςсsȚŢŤŦτТTțţťŧтtÙÚÛŨŪŬŮŰŲƯǓǕǗǙǛŨỦỤỪỨỮỬỰУUùúûũūŭůűųưǔǖǘǚǜυύϋủụừứữửựуuÝŸŶΥΎΫỲỸỶỴЙYýÿŷỳỹỷỵйyВVвvŴWŵwŹŻŽΖЗZźżžζзzÆǼAEßssIJIJijijŒOEƒf'ξksπpβvμmψpsЁYoёyoЄYeєyeЇYiЖZhжzhХKhхkhЦTsцtsЧChчchШShшshЩShchщshchЪъЬьЮYuюyuЯYaяya\"\n /// After: \"aaeooeuueAAeUUeOOeAAAAAAAAAAAAAAAAAAAAAAAaaaaaaaaaaaaaaaaaaaaaaaBbCCCCCCccccccDdDDjddjEEEEEEEEEEEEEEEEEEeeeeeeeeeeeeeeeeeeFfGGGGGgggggHHhhIIIIIIIIIIIIIiiiiiiiiiiiiJJjjKKkkLLLLllllMmNNNNNnnnnnOOOOOOOOOOOOOOOOOOOOOOooooooooooooooooooooooPpRRRRrrrrSSSSSSssssssTTTTttttUUUUUUUUUUUUUUUUUUUUUUUUuuuuuuuuuuuuuuuuuuuuuuuYYYYYYYYyyyyyyyyVvWWwwZZZZzzzzAEssIJijOEf'kspvmpsYoyoYeyeYiZhzhKhkhTstsChchShshShchshchYuyuYaya\"\n /// \n /// Tests with invalid 'special hidden characters':\n /// Before: \"\\0\\0\\000\\0000Bj��rk�\\'\\\"\\\\\\0\\a\\b\\f\\n\\r\\t\\v\\u0020���oacu\\'\\\\\\'te�\"\n /// After: \"00000Bjrk'\\\"\\\\\\n\\r oacu'\\\\'te\"\n /// \n /// </summary>\n private string Normalize(string StringToClean)\n {\n string normalizedString = StringToClean.Normalize(NormalizationForm.FormD);\n StringBuilder Buffer = new StringBuilder(StringToClean.Length);\n\n for (int i = 0; i < normalizedString.Length; i++)\n {\n if (CharUnicodeInfo.GetUnicodeCategory(normalizedString[i]) != UnicodeCategory.NonSpacingMark)\n {\n Buffer.Append(normalizedString[i]);\n }\n }\n\n string PreAsciiCompliant = Buffer.ToString().Normalize(NormalizationForm.FormC);\n StringBuilder AsciiComplient = new StringBuilder(PreAsciiCompliant.Length);\n\n foreach (char character in PreAsciiCompliant)\n {\n //Reject all special characters except \\n\\r (Carriage-Return and Line-Feed). \n //Get rid of special hidden character, like EOF, NUL, TAB and other '\\0'\n if (((int)character >= 32 && (int)character < 127) || ((int)character == 10 || (int)character == 13)) \n {\n AsciiComplient.Append(character);\n }\n }\n return AsciiComplient.ToString().Trim(); // Remove spaces at start and end of string if any\n }\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23084/"
] |
144,774
|
<p>I'm writing a program that uses <a href="http://msdn.microsoft.com/en-us/library/dd145102(VS.85).aspx" rel="nofollow noreferrer"><code>SetWindowRgn</code></a> to make transparent holes in a window that belongs to another process. (This is done only when the user explicitly requests it.)</p>
<p>The program has to assume that the target window may already have holes which need to be preserved, so before it calls <code>SetWindowRgn</code>, it calls <a href="http://msdn.microsoft.com/en-us/library/dd144950(VS.85).aspx" rel="nofollow noreferrer"><code>GetWindowRgn</code></a> to get the current region, then combines the current region with the new one and calls <code>SetWindowRgn</code>:</p>
<pre><code>HRGN rgnOld = CreateRectRgn ( 0, 0, 0, 0 );
int regionType = GetWindowRgn ( hwnd, rgnOld );
</code></pre>
<p>This works fine in XP, but the call to <code>GetWindowRgn</code> fails in Vista. I've tried turning off Aero and elevating my thread's privilege to <code>SE_DEBUG_NAME</code> with <a href="http://msdn.microsoft.com/en-us/library/aa375202(VS.85).aspx" rel="nofollow noreferrer"><code>AdjustTokenPrivileges</code></a>, but neither helps.</p>
<p>GetLastError() doesn't seem to return a valid value for GetWindowRgn -- it returns 0 on one machine and 5 (Access denied) on another.</p>
<p>Can anyone tell me what I'm doing wrong or suggest a different approach? </p>
|
[
{
"answer_id": 144856,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "SetWindowRgn()"
},
{
"answer_id": 144896,
"author": "HitScan",
"author_id": 9490,
"author_profile": "https://Stackoverflow.com/users/9490",
"pm_score": 1,
"selected": false,
"text": "GetWindowRgn()"
},
{
"answer_id": 146411,
"author": "Martin Plante",
"author_id": 4898,
"author_profile": "https://Stackoverflow.com/users/4898",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <assemblyIdentity version=\"1.0.0.0\" processorArchitecture=\"X86\" name=\"yourAssemblyNameWithoutExtension\" type=\"win32\"/>\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"true\" />\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly>\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23091/"
] |
144,783
|
<p>Should each class in my C# project get its own file (in your opinion)?</p>
|
[
{
"answer_id": 144791,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 8,
"selected": true,
"text": "partial"
},
{
"answer_id": 145356,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "public partial class MessageDescriptor : IDescriptor<MessageDescriptorProto> {}\npublic partial class FileDescriptor : IDescriptor<FileDescriptorProto> {}\n"
},
{
"answer_id": 146516,
"author": "Wes Haggard",
"author_id": 12784,
"author_profile": "https://Stackoverflow.com/users/12784",
"pm_score": 3,
"selected": false,
"text": "public partial class Foo \n{\n // Foo implementation\n}\n public partial class Foo\n{\n private class Bar\n {\n // Bar implementation\n }\n}\n"
}
] |
2008/09/27
|
[
"https://Stackoverflow.com/questions/144783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7529/"
] |
144,807
|
<p>Unfortunately, sometimes the only way to debug a program is by going through its long log files. </p>
<p>I searched for a decent log viewer for a while now, and haven't found a real solution. The only program that seemed to be most appropriate was <a href="http://logging.apache.org/chainsaw/2.x/download.html" rel="noreferrer">Chainsaw</a> with its Socket connector but after a few short uses the program proved to be buggy and unresponsive at best. </p>
<p>For my purposes, a log viewer should at least be able to mark log levels (for example with different colors) and perform easy filtering based on packages and free-text. </p>
<p>Is there any other (free) log viewer? I'm looking for anything that could work well with log4j. </p>
|
[
{
"answer_id": 7943087,
"author": "Kumba",
"author_id": 482691,
"author_profile": "https://Stackoverflow.com/users/482691",
"pm_score": 2,
"selected": false,
"text": "# Display level 6 alerts from 192.168.5.90 in WireShark\nsyslog.level == 6 && ip.addr == 192.168.5.90\n"
},
{
"answer_id": 31480019,
"author": "gliviu",
"author_id": 1126555,
"author_profile": "https://Stackoverflow.com/users/1126555",
"pm_score": 0,
"selected": false,
"text": "echo \"this string\" | lch -red.bold this -blue string\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23094/"
] |
144,810
|
<p>Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it's pretty easy), and I thought it would be cool if I were able to make a 'console' on my webpage (as in, you press the ` key like you do in <a href="http://en.wiktionary.org/wiki/first-person_shooter" rel="noreferrer">FPS</a> games, etc.), and then have it Ajax itself back to the server in-order to do stuff.</p>
<p>I originally thought the best way would be to just get the text inside the textarea, and then split it, or should I use the keyup event, convert the keycode returned to an ASCII character, append the character to a string and send the string to the server (then empty the string).</p>
<p>I couldn't find any information on getting text from a textarea, all I got was keyup information. Also, how can I convert the keycode returned to an ASCII character?</p>
|
[
{
"answer_id": 144818,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 4,
"selected": false,
"text": "testArea.value\n"
},
{
"answer_id": 144836,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 11,
"selected": true,
"text": "$('input#mybutton').click(function() {\n var text = $('textarea#mytextarea').val();\n //send to server and process response\n});\n"
},
{
"answer_id": 144871,
"author": "RodgerB",
"author_id": 20900,
"author_profile": "https://Stackoverflow.com/users/20900",
"pm_score": 3,
"selected": false,
"text": "var char = String.fromCharCode(v_code);\n"
},
{
"answer_id": 3183413,
"author": "p3drosola",
"author_id": 249161,
"author_profile": "https://Stackoverflow.com/users/249161",
"pm_score": 5,
"selected": false,
"text": "-------------------------------\n| consle output ... |\n| more output |\n| prevous commands and data |\n-------------------------------\n> This is an input box.\n"
},
{
"answer_id": 6345384,
"author": "eric",
"author_id": 797867,
"author_profile": "https://Stackoverflow.com/users/797867",
"pm_score": 3,
"selected": false,
"text": "$('console').keyup(function(event){\n $.get(\"url\", { keyCode: event.which }, ... );\n return true;\n});\n"
},
{
"answer_id": 24203284,
"author": "Thomas Koelle",
"author_id": 2854001,
"author_profile": "https://Stackoverflow.com/users/2854001",
"pm_score": 6,
"selected": false,
"text": "$('#myTextBox').val();\n $('#myTextBox').val('new value');\n"
},
{
"answer_id": 55601204,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 0,
"selected": false,
"text": "function keys(e) {\n msg.innerHTML = `last key: ${String.fromCharCode(e.keyCode)}`\n \n if(e.key == 'Enter') {\n console.log('send: ', mycon.value);\n mycon.value='';\n e.preventDefault();\n }\n} Push enter to 'send'<br>\n<textarea id='mycon' onkeydown=\"keys(event)\"></textarea>\n\n<div id=\"msg\"></div> document.addEventListener('keyup', keys);\n\nlet conShow = false\n\nfunction keys(e) {\n if (e.code == 'Backquote') {\n conShow = !conShow;\n mycon.classList.toggle(\"showcon\");\n } else {\n if (conShow) {\n if (e.code == \"Enter\") {\n conTextOld.innerHTML+= '<br>' + conText.innerHTML;\n let command=conText.innerHTML.replace(/ /g,' ');\n conText.innerHTML='';\n console.log('Send to server:', command); \n } \n else if (e.code == \"Backspace\") {\n conText.innerHTML = conText.innerText.slice(0, -1);\n } else if (e.code == \"Space\") {\n conText.innerHTML = conText.innerText + ' '\n } else {\n conText.innerHTML = conText.innerText + e.key;\n }\n\n }\n }\n} body {\n margin: 0\n}\n\n.con {\n display: flex;\n flex-direction: column;\n justify-content: flex-end;\n align-items: flex-start;\n width: 100%;\n height: 90px;\n background: rgba(255, 0, 0, 0.4);\n position: fixed;\n top: -90px;\n transition: top 0.5s ease-out 0.2s;\n font-family: monospace;\n}\n\n.showcon {\n top: 0px;\n}\n\n.conTextOld {\n color: white;\n}\n\n.line {\n display: flex;\n flex-direction: row;\n}\n\n.conText{ color: yellow; }\n\n.carret {\n height: 20px;\n width: 10px;\n background: red;\n margin-left: 1px;\n}\n\n.start { color: red; margin-right: 2px} Click here and Press tilde ` (and Enter for \"send\")\n\n<div id=\"mycon\" class=\"con\">\n <div id='conTextOld' class='conTextOld'>Hello!</div>\n <div class=\"line\">\n <div class='start'> > </div>\n <div id='conText' class=\"conText\"></div>\n <div class='carret'></div>\n </div>\n</div>"
},
{
"answer_id": 62113839,
"author": "user889030",
"author_id": 889030,
"author_profile": "https://Stackoverflow.com/users/889030",
"pm_score": 2,
"selected": false,
"text": "// by name\n<textarea name=\"comment\"></textarea>\nlet text_area_data = $('textarea[name=\"comment\"]').val();\n\n// by id\n<textarea id=\"comment\" name=\"comment\"></textarea>\nlet text_area_data = $('textarea#comment').val();\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20900/"
] |
144,824
|
<p>Can you use the bash "getopts" function twice in the same script?</p>
<p>I have a set of options that would mean different things depending on the value of a specific option. Since I can't guarantee that getopts will evaluate that specific option first, I would like to run getopts one time, using only that specific option, then run it a second time using the other options.</p>
|
[
{
"answer_id": 144838,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 4,
"selected": true,
"text": "#!/bin/bash\n\nset -- -1\nwhile getopts 1 opt; do\n case \"${opt}\" in\n 1) echo \"Worked!\";;\n *) exit 1;\n esac\ndone\n\nOPTIND=1\nset -- -2\nwhile getopts 2 opt; do\n case \"${opt}\" in\n 2) echo \"Worked!\";;\n *) exit 1;\n esac\ndone\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17925/"
] |
144,833
|
<p>I know that attributes are extremely useful. There are some predefined ones such as <code>[Browsable(false)]</code> which allows you to hide properties in the properties tab. Here is a good question explaining attributes: <a href="https://stackoverflow.com/questions/20346/c-what-are-attributes">What are attributes in .NET?</a></p>
<p><strong>What are the predefined attributes (and their namespace) you actually use in your projects?</strong> </p>
|
[
{
"answer_id": 144841,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 6,
"selected": false,
"text": "[Serializable]"
},
{
"answer_id": 144847,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 8,
"selected": false,
"text": "[Flags] [Flags] \nenum SandwichStuff\n{\n Cheese = 1,\n Pickles = 2,\n Chips = 4,\n Ham = 8,\n Eggs = 16,\n PeanutButter = 32,\n Jam = 64\n};\n\npublic Sandwich MakeSandwich(SandwichStuff stuff)\n{\n Console.WriteLine(stuff.ToString());\n // ...\n}\n\n// ...\n\nMakeSandwich(SandwichStuff.Cheese \n | SandwichStuff.Ham \n | SandwichStuff.PeanutButter);\n// produces console output: \"Cheese, Ham, PeanutButter\"\n"
},
{
"answer_id": 144849,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": " [Serializable]\n [WebMethod]\n"
},
{
"answer_id": 144850,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 6,
"selected": false,
"text": "[Attribute]"
},
{
"answer_id": 144851,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 8,
"selected": false,
"text": "System.Obsolete Conditional attribute"
},
{
"answer_id": 144909,
"author": "Redwood",
"author_id": 1512,
"author_profile": "https://Stackoverflow.com/users/1512",
"pm_score": 5,
"selected": false,
"text": "[DefaultValue]"
},
{
"answer_id": 144929,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 9,
"selected": false,
"text": "[DebuggerDisplay] [DebuggerDisplay(\"FirstName={FirstName}, LastName={LastName}\")]\nclass Customer\n{\n public string FirstName;\n public string LastName;\n}\n [WebMethod] CacheDuration"
},
{
"answer_id": 144934,
"author": "Adrian Wible",
"author_id": 23105,
"author_profile": "https://Stackoverflow.com/users/23105",
"pm_score": 5,
"selected": false,
"text": "[TestFixture] [Test]"
},
{
"answer_id": 144939,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": false,
"text": "[DebuggerStepThrough]"
},
{
"answer_id": 144942,
"author": "ElGringoGrande",
"author_id": 23100,
"author_profile": "https://Stackoverflow.com/users/23100",
"pm_score": 3,
"selected": false,
"text": "System.ComponentModel.EditorBrowsableAttribute System.ComponentModel.BindableAttribute DefaultValue System.ComponentModel.BrowsableAttribute Flags System.STAThreadAttribute\n System.ThreadStaticAttribute"
},
{
"answer_id": 145204,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 3,
"selected": false,
"text": "XmlRoot XmlElement XmlAttribute"
},
{
"answer_id": 147792,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "[Conditional(\"FOO\")] [MethodImpl(...)] [PrincipalPermission(...)] [TypeForwardedTo(...)] System.ComponentModel [TypeDescriptionProvider(...)] [TypeConverter(...)] [Editor(...)]"
},
{
"answer_id": 197063,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 4,
"selected": false,
"text": "[TypeConverter(typeof(ExpandableObjectConverter))]\n [Obfuscation]\n [assembly:ObfuscateAssemblyAttribute(true)]"
},
{
"answer_id": 204958,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "[XmlIgnore]\n"
},
{
"answer_id": 205078,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "// on configuration sections\n[ConfigurationProperty] \n\n// in asp.net\n[NotifyParentProperty(true)]\n"
},
{
"answer_id": 205416,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 4,
"selected": false,
"text": "[DataObjectMethod] [DataObjectMethod(DataObjectMethodType.Select)] \n[DataObjectMethod(DataObjectMethodType.Delete)] \n[DataObjectMethod(DataObjectMethodType.Update)] \n[DataObjectMethod(DataObjectMethodType.Insert)] \n"
},
{
"answer_id": 225964,
"author": "Ahmed Atia",
"author_id": 14118,
"author_profile": "https://Stackoverflow.com/users/14118",
"pm_score": 4,
"selected": false,
"text": "[ComVisible(false)]\n"
},
{
"answer_id": 329878,
"author": "Ajaxx",
"author_id": 25228,
"author_profile": "https://Stackoverflow.com/users/25228",
"pm_score": 5,
"selected": false,
"text": "[ThreadStatic] class MyContextInformation : IDisposable {\n [ThreadStatic] private static MyContextInformation current;\n\n public static MyContextInformation Current {\n get { return current; }\n }\n\n private MyContextInformation previous;\n\n\n public MyContextInformation(Object myData) {\n this.myData = myData;\n previous = current;\n current = this;\n }\n\n public void Dispose() {\n current = previous;\n }\n}\n using(new MyContextInformation(someInfoInContext)) {\n ...\n}\n"
},
{
"answer_id": 411535,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 4,
"selected": false,
"text": "DesignerSerializationVisibilityAttribute [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic Foo Bar {\n get { return baz; }\n set { baz = value; }\n}\n"
},
{
"answer_id": 637195,
"author": "Anthony Brien",
"author_id": 76939,
"author_profile": "https://Stackoverflow.com/users/76939",
"pm_score": 7,
"selected": false,
"text": "DisplayName Description DefaultValue [DisplayName(\"Error color\")]\n[Description(\"The color used on nodes containing errors.\")]\n[DefaultValue(Color.Red)]\npublic Color ErrorColor\n{\n ...\n} \n Description"
},
{
"answer_id": 801499,
"author": "CSharper",
"author_id": 70799,
"author_profile": "https://Stackoverflow.com/users/70799",
"pm_score": 3,
"selected": false,
"text": "[System.Security.Permissions.PermissionSetAttribute] // usage:\npublic class FullConditionUITypeEditor : UITypeEditor\n{\n // The immediate caller is required to have been granted the FullTrust permission.\n [PermissionSetAttribute(SecurityAction.LinkDemand, Name = \"FullTrust\")]\n public FullConditionUITypeEditor() { }\n}\n"
},
{
"answer_id": 892654,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 7,
"selected": false,
"text": "Conditional [Conditional(\"DEBUG\")]\npublic void DebugOnlyFunction()\n{\n // your code here\n}\n Debug.Write"
},
{
"answer_id": 971286,
"author": "Neil",
"author_id": 24315,
"author_profile": "https://Stackoverflow.com/users/24315",
"pm_score": 5,
"selected": false,
"text": "[ImmutableObject(true)]\n"
},
{
"answer_id": 1432920,
"author": "Kevin Driedger",
"author_id": 9587,
"author_profile": "https://Stackoverflow.com/users/9587",
"pm_score": 3,
"selected": false,
"text": "[DeploymentItem(\"myFile1.txt\")]"
},
{
"answer_id": 8220547,
"author": "Ming Yeh",
"author_id": 946092,
"author_profile": "https://Stackoverflow.com/users/946092",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Firm ID\n/// </summary>\n[ChineseDescription(\"送样单位编号\")]\n[ValidRequired()]\npublic string FirmGUID\n{\n get { return _firmGUID; }\n set { _firmGUID = value; }\n}\n namespace Reform.Water.Business.Common\n{\n/// <summary>\n/// Validation Utility\n/// </summary>\npublic static class ValidationUtility\n{\n /// <summary>\n /// Data entity validation\n /// </summary>\n /// <param name=\"data\">Data entity object</param>\n /// <returns>return true if the object is valid, otherwise return false</returns>\n public static bool Validate(object data)\n {\n bool result = true;\n PropertyInfo[] properties = data.GetType().GetProperties();\n foreach (PropertyInfo p in properties)\n {\n //Length validatioin\n Attribute attribute = Attribute.GetCustomAttribute(p,typeof(ValidLengthAttribute), false);\n if (attribute != null)\n {\n ValidLengthAttribute validLengthAttribute = attribute as ValidLengthAttribute;\n if (validLengthAttribute != null)\n {\n int maxLength = validLengthAttribute.MaxLength;\n int minLength = validLengthAttribute.MinLength;\n string stringValue = p.GetValue(data, null).ToString();\n if (stringValue.Length < minLength || stringValue.Length > maxLength)\n {\n return false;\n }\n }\n }\n //Range validation\n attribute = Attribute.GetCustomAttribute(p,typeof(ValidRangeAttribute), false);\n if (attribute != null)\n {\n ValidRangeAttribute validRangeAttribute = attribute as ValidRangeAttribute;\n if (validRangeAttribute != null)\n {\n decimal maxValue = decimal.MaxValue;\n decimal minValue = decimal.MinValue;\n decimal.TryParse(validRangeAttribute.MaxValueString, out maxValue);\n decimal.TryParse(validRangeAttribute.MinValueString, out minValue);\n decimal decimalValue = 0;\n decimal.TryParse(p.GetValue(data, null).ToString(), out decimalValue);\n if (decimalValue < minValue || decimalValue > maxValue)\n {\n return false;\n }\n }\n }\n //Regex validation\n attribute = Attribute.GetCustomAttribute(p,typeof(ValidRegExAttribute), false);\n if (attribute != null)\n {\n ValidRegExAttribute validRegExAttribute = attribute as ValidRegExAttribute;\n if (validRegExAttribute != null)\n {\n string objectStringValue = p.GetValue(data, null).ToString();\n string regExString = validRegExAttribute.RegExString;\n Regex regEx = new Regex(regExString);\n if (regEx.Match(objectStringValue) == null)\n {\n return false;\n }\n }\n }\n //Required field validation\n attribute = Attribute.GetCustomAttribute(p,typeof(ValidRequiredAttribute), false);\n if (attribute != null)\n {\n ValidRequiredAttribute validRequiredAttribute = attribute as ValidRequiredAttribute;\n if (validRequiredAttribute != null)\n {\n object requiredPropertyValue = p.GetValue(data, null);\n if (requiredPropertyValue == null || string.IsNullOrEmpty(requiredPropertyValue.ToString()))\n {\n return false;\n }\n }\n }\n }\n return result;\n }\n}\n}\n"
},
{
"answer_id": 10949381,
"author": "smdrager",
"author_id": 356550,
"author_profile": "https://Stackoverflow.com/users/356550",
"pm_score": 3,
"selected": false,
"text": "[EditorBrowsable(EditorBrowsableState.Never)] [ActionName(\"Name\")]"
},
{
"answer_id": 12457425,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 2,
"selected": false,
"text": "[Serializable] [WebMethod] [DefaultValue] [Description(\"description here\")] [assembly: System.CLSCompliant(true)]\n[assembly: AssemblyCulture(\"\")]\n[assembly: AssemblyDescription(\"\")]\n"
},
{
"answer_id": 12903824,
"author": "Eric Javier Hernandez Saura",
"author_id": 1499972,
"author_profile": "https://Stackoverflow.com/users/1499972",
"pm_score": 3,
"selected": false,
"text": "STAThreadAttribute \n static class Program\n{\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n}\n SuppressMessageAttribute\n [SuppressMessage(\"Microsoft.Performance\", \"CA1801:ReviewUnusedParameters\", MessageId = \"isChecked\")]\n[SuppressMessage(\"Microsoft.Performance\", \"CA1804:RemoveUnusedLocals\", MessageId = \"fileIdentifier\")]\nstatic void FileNode(string name, bool isChecked)\n{\n string fileIdentifier = name;\n string fileName = name;\n string version = String.Empty;\n}\n"
},
{
"answer_id": 13726796,
"author": "Felix K.",
"author_id": 739912,
"author_profile": "https://Stackoverflow.com/users/739912",
"pm_score": 5,
"selected": false,
"text": "public static class CustomDebug\n{\n [DebuggerHidden]\n public static void Assert(Boolean condition, Func<Exception> exceptionCreator) { ... }\n}\n\n...\n\n// The following assert fails, and because of the attribute the exception is shown at this line\n// Isn't affecting the stack trace\nCustomDebug.Assert(false, () => new Exception()); \n [DebuggerHidden]\npublic Element GetElementAt(Vector2 position)\n{\n return GetElementAt(position.X, position.Y);\n}\n\npublic Element GetElementAt(Single x, Single y) { ... }\n GetElementAt(new Vector2(10, 10))"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
144,872
|
<p>I'm using an XYPlot in JFreeChart. All the lines on it are XYSeries objects. Both axes are NumberAxis objects. The Y-Axis range is from 0-1, with ticks every .1. Along with displaying the numbers though, I'd like to display text on the Y-Axis, like High/Medium/Low. High would cover .7-1, etc. What is the best way to go about doing this? </p>
|
[
{
"answer_id": 21879964,
"author": "Salem Gharbi",
"author_id": 2711813,
"author_profile": "https://Stackoverflow.com/users/2711813",
"pm_score": 0,
"selected": false,
"text": "XYTextAnnotation textAnnotaion = new XYTextAnnotation(description, xMid, yMid);\nplot.addAnnotation(textAnnotaion);\ntextAnnotaion.setRotationAngle(90.0);\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/723/"
] |
144,892
|
<p>What's the easiest way to centre a <code>java.awt.Window</code>, such as a <code>JFrame</code> or a <code>JDialog</code>?</p>
|
[
{
"answer_id": 144950,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 6,
"selected": false,
"text": "public static void centreWindow(Window frame) {\n Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();\n int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);\n int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);\n frame.setLocation(x, y);\n}\n"
},
{
"answer_id": 7398014,
"author": "Thulani Chivandikwa",
"author_id": 611628,
"author_profile": "https://Stackoverflow.com/users/611628",
"pm_score": 2,
"selected": false,
"text": "public class BorderLayoutPanel {\n\n private JFrame mainFrame;\n private JButton btnLeft, btnRight, btnTop, btnBottom, btnCenter;\n\n public BorderLayoutPanel() {\n mainFrame = new JFrame(\"Border Layout Example\");\n btnLeft = new JButton(\"LEFT\");\n btnRight = new JButton(\"RIGHT\");\n btnTop = new JButton(\"TOP\");\n btnBottom = new JButton(\"BOTTOM\");\n btnCenter = new JButton(\"CENTER\");\n }\n\n public void SetLayout() {\n mainFrame.add(btnTop, BorderLayout.NORTH);\n mainFrame.add(btnBottom, BorderLayout.SOUTH);\n mainFrame.add(btnLeft, BorderLayout.EAST);\n mainFrame.add(btnRight, BorderLayout.WEST);\n mainFrame.add(btnCenter, BorderLayout.CENTER);\n // mainFrame.setSize(200, 200);\n // or\n mainFrame.pack();\n mainFrame.setVisible(true);\n\n //take up the default look and feel specified by windows themes\n mainFrame.setDefaultLookAndFeelDecorated(true);\n\n //make the window startup position be centered\n mainFrame.setLocationRelativeTo(null);\n\n mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);\n }\n}\n"
},
{
"answer_id": 12658942,
"author": "Jonathan Caraballo",
"author_id": 1709355,
"author_profile": "https://Stackoverflow.com/users/1709355",
"pm_score": 2,
"selected": false,
"text": "frame.setLocationRelativeTo(null);\n Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();\nint x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);\nint y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);\nframe.setLocation(x, y);\n Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();\nJLabel emptyLabel = new JLabel(\"\");\nemptyLabel.setPreferredSize(new Dimension( (int)dimension.getWidth() / 2, (int)dimension.getHeight()/2 ));\nframe.getContentPane().add(emptyLabel, BorderLayout.CENTER);\nframe.setLocation((int)dimension.getWidth()/4, (int)dimension.getHeight()/4);\n"
},
{
"answer_id": 13668582,
"author": "Viswanath Lekshmanan",
"author_id": 1870173,
"author_profile": "https://Stackoverflow.com/users/1870173",
"pm_score": 0,
"selected": false,
"text": ".getHeight() getwidth() System.out.println(frame.getHeight()); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); \nint x=(int)((dimension.getWidth() - 450)/2);\nint y=(int)((dimension.getHeight() - 450)/2);\njf.setLocation(x, y); \n"
},
{
"answer_id": 16327279,
"author": "Dzmitry Sevkovich",
"author_id": 2305760,
"author_profile": "https://Stackoverflow.com/users/2305760",
"pm_score": 5,
"selected": false,
"text": "setLocationRelativeTo(null) setSize(x,y) pack()"
},
{
"answer_id": 19746437,
"author": "Peter Szabo",
"author_id": 499770,
"author_profile": "https://Stackoverflow.com/users/499770",
"pm_score": 4,
"selected": false,
"text": "setLocationRelativeTo(null)\n setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);\n private void setWindowPosition(JFrame window, int screen)\n{ \n GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();\n GraphicsDevice[] allDevices = env.getScreenDevices();\n int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;\n\n if (screen < allDevices.length && screen > -1)\n {\n topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;\n topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;\n\n screenX = allDevices[screen].getDefaultConfiguration().getBounds().width;\n screenY = allDevices[screen].getDefaultConfiguration().getBounds().height;\n }\n else\n {\n topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;\n topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;\n\n screenX = allDevices[0].getDefaultConfiguration().getBounds().width;\n screenY = allDevices[0].getDefaultConfiguration().getBounds().height;\n }\n\n windowPosX = ((screenX - window.getWidth()) / 2) + topLeftX;\n windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;\n\n window.setLocation(windowPosX, windowPosY);\n}\n"
},
{
"answer_id": 27512597,
"author": "borchvm",
"author_id": 3115822,
"author_profile": "https://Stackoverflow.com/users/3115822",
"pm_score": 0,
"selected": false,
"text": "public class SwingExample implements Runnable {\n\n @Override\n public void run() {\n // Create the window\n final JFrame f = new JFrame(\"Hello, World!\");\n SwingExample.centerWindow(f);\n f.setPreferredSize(new Dimension(500, 250));\n f.setMaximumSize(new Dimension(10000, 200));\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n\n public static void centerWindow(JFrame frame) {\n Insets insets = frame.getInsets();\n frame.setSize(new Dimension(insets.left + insets.right + 500, insets.top + insets.bottom + 250));\n frame.setVisible(true);\n frame.setResizable(false);\n\n Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();\n int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);\n int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);\n frame.setLocation(x, y);\n }\n}\n"
},
{
"answer_id": 28894916,
"author": "Julien",
"author_id": 675034,
"author_profile": "https://Stackoverflow.com/users/675034",
"pm_score": 1,
"selected": false,
"text": "Window public static final void centerWindow(final Window window) {\n GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();\n Rectangle r = screen.getDefaultConfiguration().getBounds();\n int x = (r.width - window.getWidth()) / 2 + r.x;\n int y = (r.height - window.getHeight()) / 2 + r.y;\n window.setLocation(x, y);\n}\n"
},
{
"answer_id": 29057613,
"author": "Clay Ellis",
"author_id": 4283188,
"author_profile": "https://Stackoverflow.com/users/4283188",
"pm_score": 2,
"selected": false,
"text": "setLocationRelativeTo(null) setLocation(x,y) pack() pack()"
},
{
"answer_id": 29587499,
"author": "TheLooker",
"author_id": 4745010,
"author_profile": "https://Stackoverflow.com/users/4745010",
"pm_score": 3,
"selected": false,
"text": "package my.SampleUIdemo;\nimport java.awt.*;\n\npublic class classSampleUIdemo extends javax.swing.JFrame {\n /// \n public classSampleUIdemo() {\n initComponents();\n CenteredFrame(this); // <--- Here ya go.\n }\n // ...\n // void main() and other public method declarations here...\n\n /// modular approach\n public void CenteredFrame(javax.swing.JFrame objFrame){\n Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();\n int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;\n int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;\n objFrame.setLocation(iCoordX, iCoordY); \n } \n\n}\n package my.SampleUIdemo;\nimport java.awt.*;\n\npublic class classSampleUIdemo extends javax.swing.JFrame {\n /// \n public classSampleUIdemo() {\n initComponents(); \n //------>> Insert your code here to center main jFrame.\n Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();\n int iCoordX = (objDimension.width - this.getWidth()) / 2;\n int iCoordY = (objDimension.height - this.getHeight()) / 2;\n this.setLocation(iCoordX, iCoordY); \n //------>> \n } \n // ...\n // void main() and other public method declarations here...\n\n}\n package my.SampleUIdemo;\n import java.awt.*;\n public class classSampleUIdemo extends javax.swing.JFrame {\n /// \n public classSampleUIdemo() {\n initComponents();\n this.setLocationRelativeTo(null); // <<--- plain and simple\n }\n // ...\n // void main() and other public method declarations here...\n }\n"
},
{
"answer_id": 34869526,
"author": "manikant gautam",
"author_id": 2837359,
"author_profile": "https://Stackoverflow.com/users/2837359",
"pm_score": 1,
"selected": false,
"text": "Frame frame = new Frame(\"Centered Frame\");\nDimension dimemsion = Toolkit.getDefaultToolkit().getScreenSize();\nframe.setLocation(dimemsion.width/2-frame.getSize().width/2, dimemsion.height/2-frame.getSize().height/2);\n"
},
{
"answer_id": 43732518,
"author": "Aman Goel",
"author_id": 2765792,
"author_profile": "https://Stackoverflow.com/users/2765792",
"pm_score": 2,
"selected": false,
"text": "public class SwingContainerDemo {\n\nprivate JFrame mainFrame;\n\nprivate JPanel controlPanel;\n\nprivate JLabel msglabel;\n\nFrame.setLayout(new FlowLayout());\n\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n //headerLabel = new JLabel(\"\", JLabel.CENTER); \n /* statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n */ msglabel = new JLabel(\"Welcome to TutorialsPoint SWING Tutorial.\", JLabel.CENTER);\n\n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n //mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n // mainFrame.add(statusLabel);\n\n mainFrame.setUndecorated(true);\n mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n mainFrame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);\n mainFrame.setVisible(true); \n\n centreWindow(mainFrame);\n public static void centreWindow(Window frame) {\n Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();\n int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);\n int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);\n frame.setLocation(x, 0);\n}\n\n\npublic void showJFrameDemo(){\n /* headerLabel.setText(\"Container in action: JFrame\"); */\n final JFrame frame = new JFrame();\n frame.setSize(300, 300);\n frame.setLayout(new FlowLayout()); \n frame.add(msglabel);\n\n frame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n frame.dispose();\n } \n }); \n\n\n\n JButton okButton = new JButton(\"Capture\");\n okButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n // statusLabel.setText(\"A Frame shown to the user.\");\n // frame.setVisible(true);\n mainFrame.setState(Frame.ICONIFIED);\n Robot robot = null;\n try {\n robot = new Robot();\n } catch (AWTException e1) {\n // TODO Auto-generated catch block\n e1.printStackTrace();\n }\n final Dimension screenSize = Toolkit.getDefaultToolkit().\n getScreenSize();\n final BufferedImage screen = robot.createScreenCapture(\n new Rectangle(screenSize));\n\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n new ScreenCaptureRectangle(screen);\n }\n });\n mainFrame.setState(Frame.NORMAL);\n }\n });\n controlPanel.add(okButton);\n mainFrame.setVisible(true); \n new SwingContainerDemo().showJFrameDemo();\n"
},
{
"answer_id": 53922973,
"author": "Marinel P",
"author_id": 7578726,
"author_profile": "https://Stackoverflow.com/users/7578726",
"pm_score": 2,
"selected": false,
"text": "JFrame window;\n\npublic myWindow() {\n\n window = new JFrame();\n window.setSize(1200,800);\n window.setLocationRelativeTo(null); // this line set the window in the center of thr screen\n window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n window.getContentPane().setBackground(Color.BLACK);\n window.setLayout(null); // disable the default layout to use custom one.\n window.setVisible(true); // to show the window on the screen.\n}\n"
},
{
"answer_id": 63260529,
"author": "Adir D",
"author_id": 6130501,
"author_profile": "https://Stackoverflow.com/users/6130501",
"pm_score": 0,
"selected": false,
"text": "pack();\n setLocationRelativeTo(null);\n"
},
{
"answer_id": 66723315,
"author": "Tuhin Mitra",
"author_id": 8201723,
"author_profile": "https://Stackoverflow.com/users/8201723",
"pm_score": 0,
"selected": false,
"text": "the window is at the center of the window public static void centreWindow(JFrame frame, int width, int height) {\n Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();\n int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);\n int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);\n\n // calculate perfect center\n int perf_x = (int) x - width/2;\n int perf_y = (int) y - height/2;\n\n frame.setLocation(perf_x, perf_y);\n }\n"
},
{
"answer_id": 72511347,
"author": "Tolga Acgul",
"author_id": 10055125,
"author_profile": "https://Stackoverflow.com/users/10055125",
"pm_score": 0,
"selected": false,
"text": "int x = (Toolkit.getDefaultToolkit().getScreenSize().width) - getSize().width) / 2;\nint y = (Toolkit.getDefaultToolkit().getScreenSize().height) - getSize().height) / 2;\nsetLocation(x,y);\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10433/"
] |
144,898
|
<p>Code below is not working as expected to detect if it is in design mode (VS.Net 2003 - Control Library):</p>
<p>if (this.Site != null && this.Site.DesignMode == true) <br>
{<br>
// Design Mode<br>
}<br>
else<br>
{<br>
// Run-time<br>
}<br></p>
<p>It is used in a complex user control, deriving from another user control and including other user controls on it.<br>
Is there another way to detect design time in a VS.NET 2003 or what is the problem with the code above? </p>
|
[
{
"answer_id": 297987,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 4,
"selected": true,
"text": "DesignMode if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime) GetService(typeof(IDesignerHost))"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23087/"
] |
144,902
|
<p>Recently I had to do some very processing heavy stuff with data stored in a DataSet. It was heavy enough that I ended up using a tool to help identify some bottlenecks in my code. When I was analyzing the bottlenecks, I noticed that although DataSet lookups were not terribly slow (they weren't the bottleneck), it was slower than I expected. I always assumed that DataSets used some sort of HashTable style implementation which would make lookups O(1) (or at least thats what I think HashTables are). The speed of my lookups seemed to be significantly slower than this.</p>
<p>I was wondering if anyone who knows anything about the implementation of .NET's DataSet class would care to share what they know.</p>
<p>If I do something like this : </p>
<pre><code>DataTable dt = new DataTable();
if(dt.Columns.Contains("SomeColumn"))
{
object o = dt.Rows[0]["SomeColumn"];
}
</code></pre>
<p>How fast would the lookup time be for the <code>Contains(...)</code> method, and for retrieving the value to store in <code>Object o</code>? I would have thought it be very fast like a HashTable (assuming what I understand about HashTables is correct) but it doesn't seem like it...</p>
<p>I wrote that code from memory so some things may not be "syntactically correct".</p>
|
[
{
"answer_id": 145299,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 2,
"selected": false,
"text": "const int SomeTable_SomeColumn = 0;\n\nDataTable dt = new DataTable();\nif(dt.Columns.Contains(SomeTable_SomeColumn))\n{\n object o = dt.Rows[0][SomeTable_SomeColumn];\n}\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
144,957
|
<p>How have you used the Exception.Data property in C# projects that you've worked on? </p>
<p>I'd like answers that suggest a pattern, rather than those that are very specific to your app.</p>
|
[
{
"answer_id": 30399137,
"author": "Chris Marisic",
"author_id": 37055,
"author_profile": "https://Stackoverflow.com/users/37055",
"pm_score": 5,
"selected": false,
"text": ".Data IDictionary foreach(var kvp in exception.Data) object foreach (DictionaryEntry de in e.Data)\n Console.WriteLine(\" Key: {0,-20} Value: {1}\", \n \"'\" + de.Key.ToString() + \"'\", de.Value);\n , -20 var messageBuilder = new StringBuilder();\n\ndo\n{ \n foreach (DictionaryEntry kvp in exception.Data)\n messageBuilder.AppendFormat(\"{0} : {1}\\n\", kvp.Key, kvp.Value);\n\n messageBuilder.AppendLine(exception.Message);\n\n\n} while ((exception = exception.InnerException) != null);\n\nreturn messageBuilder.ToString();\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7529/"
] |
144,960
|
<p>Can this be done? How?</p>
<hr>
<p>I want to write my own extension. Can Get the current page sorcecode in my own extension?</p>
|
[
{
"answer_id": 145419,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 2,
"selected": false,
"text": "view-source:http://stackoverflow.com/posts/edit/145419\n"
},
{
"answer_id": 145768,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "view-source Ctrl+U"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
] |
144,965
|
<p>I have Visual Studio 2005 Professional ENU installed and want to create GUIDs using its Create GUIDs utility. However, I cannot find it under the Tools menu. What should I do to get this utility? Thanks</p>
|
[
{
"answer_id": 144970,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "9a005ff3-5dee-4667-b5b9-7663fee2b0f9\ndb031ebf-7ffa-4604-a6b6-7d60a38c60ca\n96f1854c-3654-46a7-8f57-20eb23f62375\nf43a4642-db72-4ed5-a9e7-32fc2c53d1f1\n6fa5c074-d68c-4871-b26f-1e0b51374865\n17cf6675-fce6-42ce-8501-f19dadbe0c6d\n65c681ad-701e-4bc6-a373-2351d9fc1910\n3eab6e3d-4040-4beb-9c79-57a0bd7c84c9\n3aae1801-c595-4f0b-a36c-56f41e5858dd\n310f9053-319e-457c-aedf-ba9a1cd6a1cb\n for (int i = 0; i < 10; i++)\n {\n Console.WriteLine([GET THE WHOLE SOURCE! ONLY $19.99!]);\n }\n"
},
{
"answer_id": 144987,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 2,
"selected": false,
"text": "Public Module GUIDGenModule\n\n Sub Create_GUID()\n DTE.ActiveDocument.Selection.Text = System.Guid.NewGuid().ToString(\"D\").ToUpper()\n End Sub\n\nEnd Module\n"
},
{
"answer_id": 145062,
"author": "Goyuix",
"author_id": 243,
"author_profile": "https://Stackoverflow.com/users/243",
"pm_score": 0,
"selected": false,
"text": "[guid]::NewGuid().ToString()\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8203/"
] |
144,980
|
<p>Greetings.</p>
<p>I'm trying to implement some multithreaded code in an application. The purpose of this code is to validate items that the database gives it. Validation can take quite a while (a few hundred ms to a few seconds), so this process needs to be forked off into its own thread for each item.</p>
<p>The database may give it 20 or 30 items a second in the beginning, but that begins to decline rapidly, eventually reaching about 65K items over 24 hours, at which point the application exits.</p>
<p>I'd like it if anyone more knowledgeable could take a peek at my code and see if there's any obvious problems. No one I work with knows multithreading, so I'm really just on my own, on this one.</p>
<p>Here's the code. It's kinda long but should be pretty clear. Let me know if you have any feedback or advice. Thanks!</p>
<pre><code>public class ItemValidationService
{
/// <summary>
/// The object to lock on in this class, for multithreading purposes.
/// </summary>
private static object locker = new object();
/// <summary>Items that have been validated.</summary>
private HashSet<int> validatedItems;
/// <summary>Items that are currently being validated.</summary>
private HashSet<int> validatingItems;
/// <summary>Remove an item from the index if its links are bad.</summary>
/// <param name="id">The ID of the item.</param>
public void ValidateItem(int id)
{
lock (locker)
{
if
(
!this.validatedItems.Contains(id) &&
!this.validatingItems.Contains(id)
){
ThreadPool.QueueUserWorkItem(sender =>
{
this.Validate(id);
});
}
}
} // method
private void Validate(int itemId)
{
lock (locker)
{
this.validatingItems.Add(itemId);
}
// *********************************************
// Time-consuming routine to validate an item...
// *********************************************
lock (locker)
{
this.validatingItems.Remove(itemId);
this.validatedItems.Add(itemId);
}
} // method
} // class
</code></pre>
|
[
{
"answer_id": 145087,
"author": "Ted Elliott",
"author_id": 16501,
"author_profile": "https://Stackoverflow.com/users/16501",
"pm_score": 2,
"selected": false,
"text": "Environment.ProcessorCount"
},
{
"answer_id": 145089,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 1,
"selected": false,
"text": "ValidateItem(int id) ValidateItem(id) QueueUserWorkItem()"
},
{
"answer_id": 146706,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 1,
"selected": false,
"text": "this.validatingItems.Add(itemId);\n"
},
{
"answer_id": 58311502,
"author": "Nandan",
"author_id": 4268162,
"author_profile": "https://Stackoverflow.com/users/4268162",
"pm_score": 0,
"selected": false,
"text": "Producer-Consumer producing consumer ConcurrentDictionary<TKey, TValue> lock-free"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] |
144,983
|
<p>Every time I start Emacs I see a page of help text and a bunch of messages suggesting that I try the tutorial. How do I stop this from happening?</p>
|
[
{
"answer_id": 144984,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 4,
"selected": true,
"text": ".emacs"
},
{
"answer_id": 144986,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": false,
"text": ";; inhibit-startup-echo-area-message MUST be set to a hardcoded \n;; string of your login name \n(setq inhibit-startup-echo-area-message \"USERNAME\")\n(setq inhibit-startup-message t)\n"
},
{
"answer_id": 208850,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 2,
"selected": false,
"text": "~/.emacs.el (setq inhibit-startup-message t)\n (setq inhibit-startup-screen t) inhibit-startup-echo-area-message t inhibit-startup-echo-area-message"
},
{
"answer_id": 28530989,
"author": "rgtk",
"author_id": 1106189,
"author_profile": "https://Stackoverflow.com/users/1106189",
"pm_score": 2,
"selected": false,
"text": ";; Hide advertisement from minibuffer\n(defun display-startup-echo-area-message ()\n (message \"\"))\n"
},
{
"answer_id": 44552601,
"author": "dodona",
"author_id": 5758211,
"author_profile": "https://Stackoverflow.com/users/5758211",
"pm_score": 0,
"selected": false,
"text": "(eval '(setq inhibit-startup-echo-area-message \"YOUR-USER-NAME\"))\n"
},
{
"answer_id": 51551825,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "(setq inhibit-startup-message t\ninhibit-startup-echo-area-message t) \n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11138/"
] |
144,985
|
<p>I was reading <a href="https://stackoverflow.com/questions/144735/best-way-to-get-started-with-programming-other-things-than-your-computer#144843">this</a> answer previously and it got me interested in purchasing a Nintendo DS Lite for learning to program embedded devices. Before I go out and splurge on a DS I had a few questions:</p>
<ol>
<li><p>Are there any restrictions on what you can program? The post I indicated earlier seemed to say there weren't, but clarification would be nice.</p></li>
<li><p>Would I be better off buying an arduino (or similar) and going that route? I like the DS because it already has a lot of hardware built in.</p></li>
<li><p>I'm thinking of getting a CycloDS Evo card, is there a better option for homebrew? </p></li>
<li><p>What are the best resources to learn about DS development?</p></li>
</ol>
<p>Thanks for your time, If you have a DS and program on it, I'd love you hear your opinion, or alternatively if you have a better idea, I'd like to hear it too.</p>
<p>Thanks =]</p>
|
[
{
"answer_id": 158909,
"author": "Cristián Romo",
"author_id": 1256,
"author_profile": "https://Stackoverflow.com/users/1256",
"pm_score": 5,
"selected": true,
"text": "examples"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15534/"
] |
144,993
|
<p>A lot of literature talks about using inline functions to "avoid the overhead of a function call". However I haven't seen quantifiable data. What is the actual overhead of a function call i.e. what sort of performance increase do we achieve by inlining functions?</p>
|
[
{
"answer_id": 14329151,
"author": "doug65536",
"author_id": 1127972,
"author_profile": "https://Stackoverflow.com/users/1127972",
"pm_score": 2,
"selected": false,
"text": "Foo::result_type MakeMeFaster()\n{\n Foo t = 0;\n for (auto i = 0; i < 1000; ++i)\n t += CheckOverhead(SomethingUnpredictible());\n return t.result();\n}\n\nFoo CheckOverhead(int i)\n{\n auto n = CalculatePi_1000_digits();\n return i * n;\n}\n Foo::result_type MakeMeFaster()\n{\n Foo t;\n auto _hidden_optimizer_tmp = CalculatePi_1000_digits();\n for (auto i = 0; i < 1000; ++i)\n t += SomethingUnpredictible() * _hidden_optimizer_tmp;\n return t.result();\n}\n"
},
{
"answer_id": 28419241,
"author": "teeks99",
"author_id": 17949,
"author_profile": "https://Stackoverflow.com/users/17949",
"pm_score": 1,
"selected": false,
"text": "#include <boost/timer/timer.hpp>\n#include <iostream>\n#include <cmath>\n\ndouble sum;\ndouble a = 42, b = 53;\n\n//#define ITERATIONS 1000000 // 1 million - for testing\n//#define ITERATIONS 10000000000 // 10 billion ~ 10s per run\n//#define WORK_UNIT sum += a + b\n/* output\n8.609619s wall, 8.611255s user + 0.000000s system = 8.611255s CPU(100.0%)\n8.604478s wall, 8.611255s user + 0.000000s system = 8.611255s CPU(100.1%)\n8.610679s wall, 8.595655s user + 0.000000s system = 8.595655s CPU(99.8%)\n9.5e+011 9.5e+011 9.5e+011\n*/\n\n#define ITERATIONS 100000000 // 100 million ~ 10s per run\n#define WORK_UNIT sum += std::sqrt(a*a + b*b + sum) + std::sin(sum) + std::cos(sum)\n/* output\n8.485689s wall, 8.486454s user + 0.000000s system = 8.486454s CPU (100.0%)\n8.494153s wall, 8.486454s user + 0.000000s system = 8.486454s CPU (99.9%)\n8.467291s wall, 8.470854s user + 0.000000s system = 8.470854s CPU (100.0%)\n2.50001e+015 2.50001e+015 2.50001e+015\n*/\n\n\n// ------------------------------\ndouble simple()\n{\n sum = 0;\n boost::timer::auto_cpu_timer t;\n for (unsigned long long i = 0; i < ITERATIONS; i++)\n {\n WORK_UNIT;\n }\n return sum;\n}\n\n// ------------------------------\nvoid call6()\n{\n WORK_UNIT;\n}\nvoid call5(){ call6(); }\nvoid call4(){ call5(); }\nvoid call3(){ call4(); }\nvoid call2(){ call3(); }\nvoid call1(){ call2(); }\n\ndouble calls()\n{\n sum = 0;\n boost::timer::auto_cpu_timer t;\n\n for (unsigned long long i = 0; i < ITERATIONS; i++)\n {\n call1();\n }\n return sum;\n}\n\n// ------------------------------\nclass Obj3{\npublic:\n void runIt(){\n WORK_UNIT;\n }\n};\n\nclass Obj2{\npublic:\n Obj2(){it = new Obj3();}\n ~Obj2(){delete it;}\n void runIt(){it->runIt();}\n Obj3* it;\n};\n\nclass Obj1{\npublic:\n void runIt(){it.runIt();}\n Obj2 it;\n};\n\ndouble objects()\n{\n sum = 0;\n Obj1 obj;\n\n boost::timer::auto_cpu_timer t;\n for (unsigned long long i = 0; i < ITERATIONS; i++)\n {\n obj.runIt();\n }\n return sum;\n}\n// ------------------------------\n\n\nint main(int argc, char** argv)\n{\n double ssum = 0;\n double csum = 0;\n double osum = 0;\n\n ssum = simple();\n csum = calls();\n osum = objects();\n\n std::cout << ssum << \" \" << csum << \" \" << osum << std::endl;\n}\n sum += std::sqrt(a*a + b*b + sum) + std::sin(sum) + std::cos(sum)\n 8.485689s wall, 8.486454s user + 0.000000s system = 8.486454s CPU (100.0%)\n8.494153s wall, 8.486454s user + 0.000000s system = 8.486454s CPU (99.9%)\n8.467291s wall, 8.470854s user + 0.000000s system = 8.470854s CPU (100.0%)\n2.50001e+015 2.50001e+015 2.50001e+015\n sum += a + b\n"
},
{
"answer_id": 38815159,
"author": "PSkocik",
"author_id": 1084774,
"author_profile": "https://Stackoverflow.com/users/1084774",
"pm_score": 5,
"selected": false,
"text": "typedef unsigned long ulong;\nulong inc(ulong x){\n return x+1;\n}\n #include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned long ulong;\n\n#ifdef EXTERN \nulong inc(ulong);\n#else\nstatic inline ulong inc(ulong x){\n return x+1;\n}\n#endif\n\nint main(int argc, char** argv){\n if (argc < 1+1)\n return 1;\n ulong i, sum = 0, cnt;\n cnt = atoi(argv[1]);\n for(i=0;i<cnt;i++){\n sum+=inc(i);\n }\n printf(\"%lu\\n\", sum);\n return 0;\n}\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/144993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
] |
145,006
|
<p>Very simply put, I have the following code snippet:</p>
<pre><code>FILE* test = fopen("C:\\core.u", "w");
printf("Filepointer at: %d\n", ftell(test));
fwrite(data, size, 1, test);
printf("Written: %d bytes.\n", size);
fseek(test, 0, SEEK_END);
printf("Filepointer is now at %d.\n", ftell(test));
fclose(test);
</code></pre>
<p>and it outputs:</p>
<pre><code>Filepointer at: 0
Written: 73105 bytes.
Filepointer is now at 74160.
</code></pre>
<p>Why is that? Why does the number of bytes written not match the file pointer?</p>
|
[
{
"answer_id": 145013,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": true,
"text": "\"c:\\\" \"wb\" FILE* test = fopen(\"C:\\\\core.u\", \"wb\");\n 7.19.5.3 The fopen function r w a rb wb ab r+ w+ a+ r+b rb+ w+b wb+ a+b ab+ w wb"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
145,017
|
<p>I haven't been around Java development for 8 years, but am starting to build a NetBeans Web Application. When I walk through the Web Application wizard, it asks for the server I'm going to be using. </p>
<p>What would be the best and simplest server for me to start using with NetBeans?</p>
|
[
{
"answer_id": 228524,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "http://localhost:4848 \n http://glassfish.dev.java.net/downloads/quickstart/index.html\n http://download.java.net/javaee5/screencasts/admin-console/index.html\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289/"
] |
145,025
|
<p>I'm implementing a secure WCF service. Authentication is done using username / password or Windows credentials. The service is hosted in a Windows Service process. Now, I'm trying to find out the best way to implement <em>authorization</em> for each service operation.</p>
<p>For example, consider the following method:</p>
<pre><code>public EntityInfo GetEntityInfo(string entityId);
</code></pre>
<p>As you may know, in WCF, there is an OperationContext object from which you can retrieve the security credentials passed in by the caller/client. Now,<em>authentication</em> would have already finished by the time the first line in the method is called. However, how do we implement authorization if the decision depends on the input data itself? For example, in the above case, say 'admin' users(whose permissions etc are stored in a database), are allowed to get entity info, and other users should not be allowed... where do we put the authorization checks?</p>
<p>Say we put it in the first line of the method like so:</p>
<pre><code>CheckAccessPermission(PermissionType.GetEntity, user, entityId) //user is pulled from the current OperationContext
</code></pre>
<p>Now, there are a couple of questions:</p>
<ol>
<li><p>Do we validate the entityId (for example check null / empty value etc) BEFORE the authorization check or INSIDE the authorization check? In other words, if authorization checks should be included in every method, is that a good pattern? Which should happen first - argument validation or authorization?</p></li>
<li><p>How do we unit test a WCF service when authorization checks are all over the place like this, and we don't have an OperationContext in the unit test!? (Assuming I'm tryin to test this service class implementation directly without any of the WCF setup).</p></li>
</ol>
<p>Any ideas guys?</p>
|
[
{
"answer_id": 146615,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 3,
"selected": true,
"text": "public abstract class MyServiceImpl\n{\n public void MyMethod(string entityId)\n {\n CheckPermissions(entityId);\n //move along...\n }\n protected abstract bool CheckPermissions(string entityId);\n}\n\npublic class MyServiceUnitTest\n{\n private bool CheckPermissions(string entityId)\n {\n return true;\n }\n}\n\npublic class MyServiceMyAuth\n{\n private bool CheckPermissions(string entityId)\n {\n //do some custom authentication\n return true;\n }\n}\n"
},
{
"answer_id": 654545,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 3,
"selected": false,
"text": "class MyService : IMyService\n{\n public MyService() : this(new UserAuthorization()) { }\n public MyService(IAuthorization auth) { _auth = auth; }\n\n private IAuthorization _auth;\n\n public EntityInfo GetEntityInfo(string entityId)\n {\n _auth.CheckAccessPermission(PermissionType.GetEntity, \n user, entityId);\n\n //Get the entity info\n }\n}\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6995/"
] |
145,052
|
<p>Is there any libraries that would allow me to use the same known notation as we use in BeanUtils for extracting POJO parameters, but for easily replacing placeholders in a string?</p>
<p>I know it would be possible to roll my own, using BeanUtils itself or other libraries with similar features, but I didn't want to reinvent the wheel.</p>
<p>I would like to take a String as follows:</p>
<pre><code>String s = "User ${user.name} just placed an order. Deliver is to be
made to ${user.address.street}, ${user.address.number} - ${user.address.city} /
${user.address.state}";
</code></pre>
<p>And passing one instance of the User class below:</p>
<pre><code>public class User {
private String name;
private Address address;
// (...)
public String getName() { return name; }
public Address getAddress() { return address; }
}
public class Address {
private String street;
private int number;
private String city;
private String state;
public String getStreet() { return street; }
public int getNumber() { return number; }
// other getters...
}
</code></pre>
<p>To something like:</p>
<pre><code>System.out.println(BeanUtilsReplacer.replaceString(s, user));
</code></pre>
<p>Would get each placeholder replaced with actual values.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 145156,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 1,
"selected": false,
"text": "foxtype = 'quick'\nfoxcolor = ['b', 'r', 'o', 'w', 'n']\nprintln \"The $foxtype ${foxcolor.join()} fox\"\n public int countOfActors(Actor exampleActor) {\n\n // notice how the named parameters match the properties of the above 'Actor' class\n String sql = \"select count(0) from T_ACTOR where first_name = :firstName and last_name = :lastName\";\n\n SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor);\n\n return this.namedParameterJdbcTemplate.queryForInt(sql, namedParameters);\n}\n"
},
{
"answer_id": 145173,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 3,
"selected": true,
"text": "import java.lang.reflect.InvocationTargetException;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.apache.commons.beanutils.BeanUtils;\n\npublic class BeanUtilsReplacer\n{\n private static Pattern lookupPattern = Pattern.compile(\"\\\\$\\\\{([^\\\\}]+)\\\\}\");\n\n public static String replaceString(String input, Map<String, Object> context)\n throws IllegalAccessException, InvocationTargetException, NoSuchMethodException\n {\n int position = 0;\n StringBuffer result = new StringBuffer();\n\n Matcher m = lookupPattern.matcher(input);\n while (m.find())\n {\n result.append(input.substring(position, m.start()));\n result.append(BeanUtils.getNestedProperty(context, m.group(1)));\n position = m.end();\n }\n\n if (position == 0)\n {\n return input;\n }\n else\n {\n result.append(input.substring(position));\n return result.toString();\n }\n }\n}\n Map<String, Object> context = new HashMap<String, Object>();\ncontext.put(\"user\", user);\nSystem.out.println(BeanUtilsReplacer.replaceString(s, context));\n"
},
{
"answer_id": 145477,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 1,
"selected": false,
"text": " /* ------------------------------------------------------------------- */ \n /* You usually do it only once in the whole application life-cycle: */ \n\n /* Create and adjust the configuration */\n Configuration cfg = new Configuration();\n cfg.setDirectoryForTemplateLoading(\n new File(\"/where/you/store/templates\"));\n cfg.setObjectWrapper(new DefaultObjectWrapper());\n\n /* ------------------------------------------------------------------- */ \n /* You usually do these for many times in the application life-cycle: */ \n\n /* Get or create a template */\n Template temp = cfg.getTemplate(\"test.ftl\");\n\n /* Create a data-model */\n Map root = new HashMap();\n root.put(\"user\", \"Big Joe\");\n Map latest = new HashMap();\n root.put(\"latestProduct\", latest);\n latest.put(\"url\", \"products/greenmouse.html\");\n latest.put(\"name\", \"green mouse\");\n\n /* Merge data-model with template */\n Writer out = new OutputStreamWriter(System.out);\n temp.process(root, out);\n out.flush();\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14540/"
] |
145,056
|
<p>A friend came across a quadratic Bézier curve function in his codebase that used a gigantic rats nest of a switch table to perform the computation. He challenged me to find a single, short expression that would allow him to replace the gigantic block of code.</p>
<p>In attempting to satisfy two different curiosities, I thought I'd try implementing the function in OCaml. I'm a very novice OCaml programmer and I'm also unfamiliar with the function and this <em>specific</em> implementation is hard to come by via Google.</p>
<p>Critiques on both the function's performance/correctness as well as its implementation are very much appreciated.</p>
<p>Implementation of <a href="http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B.C3.A9zier_curves" rel="nofollow noreferrer">Quadratic Bézier Curve</a>:</p>
<pre><code>let rec b2 n =
let p1 = -10. in
let p2 = 10. in
let q = n*.n in
let rec b2i n i hd =
if i > n then
List.rev hd
else
let t = i /. n in
b2i n (i+.1.) ((((1.-.t)**2.)*.p1+.(2.*.t*.(1.-.t)*.q)+.(t**2.)*.p2) :: hd)
in
b2i n 0. []
;;
let floatprint lst =
List.iter (fun f -> Printf.printf "%f; " f) lst ;;
floatprint (b2 8.);;
</code></pre>
|
[
{
"answer_id": 145142,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "List.rev b2i List.rev ?(epsilon=0.1)"
},
{
"answer_id": 146000,
"author": "Thelema",
"author_id": 12874,
"author_profile": "https://Stackoverflow.com/users/12874",
"pm_score": 3,
"selected": true,
"text": "let b i = \n let t = i /. n in\n let tminus = (1.-.t) in\n (tminus *. tminus *. p0) +. (2. *. t *. tminus *. p1) +. (t *. t * p2)\nin\nList.map b ([generate list 1.0; 2.0; ... n.0])\n let rec count m n = if m > n then [] else m :: (count (m+.1.) n)\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
] |
145,096
|
<p>I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this?</p>
|
[
{
"answer_id": 145098,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 7,
"selected": true,
"text": "int *i = malloc(sizeof(int) * 5); \n int *i = (int *) malloc(sizeof(int) * 5)\n void fn(void)\n {\n goto flack;\n int i = 1;\n flack:\n ;\n }\n"
},
{
"answer_id": 145099,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "int virtual;\n"
},
{
"answer_id": 145136,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "extern void function();\n #include <stdio.h> printf() sizeof('c')\n long long"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23126/"
] |
145,103
|
<p>I need to do some performance benchmarks on .NET programs (C#) in Windows, but I haven't done benchmarking much in the Windows world. I've looked into using the Windows 2000/XP Performance monitor with custom counters for this, but I don't think this is quite what I want.</p>
<p>Are there any good system facilities for this in Windows XP, or do I need to just use System.Diagnostics.Stopwatch [edit] and write text logs for manual interpretation, or is there something else?</p>
<p>Edit: is there anything beyond <code>System.Diagnostics.Stopwatch</code>?</p>
|
[
{
"answer_id": 145113,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": false,
"text": "using System.Diagnostics;\n....\n\nStopwatch sw = new Stopwatch();\n\nsw.Start();\n\n// Code you want to time...\n\n// Note: for averaged accuracy (without other OS effects), \n// run timed code multiple times in a loop \n// and then divide by the number of runs.\n\nsw.Stop();\n\nConsole.WriteLine(\"Took \" + sw.ElapsedTicks + \" Ticks\");\n"
},
{
"answer_id": 1500888,
"author": "Justin R.",
"author_id": 4593,
"author_profile": "https://Stackoverflow.com/users/4593",
"pm_score": 2,
"selected": false,
"text": "> measure-command { your.exe arg1 }\n\nDays : 0\nHours : 0\nMinutes : 0\nSeconds : 4\nMilliseconds : 996\nTicks : 49963029\nTotalDays : 5.78275798611111E-05\nTotalHours : 0.00138786191666667\nTotalMinutes : 0.083271715\nTotalSeconds : 4.9963029\nTotalMilliseconds : 4996.3029\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
] |
145,110
|
<p>My understanding is that C/C++ produces native code to run on a particular machine architecture. Conversely, languages like Java and C# run on top of a virtual machine which abstracts away the native architecture. Logically it would seem impossible for Java or C# to match the speed of C++ because of this intermediate step, however I've been told that the latest compilers ("hot spot") can attain this speed or even exceed it.</p>
<p>Perhaps this is more of a compiler question than a language question, but can anyone explain in plain English how it is possible for one of these virtual machine languages to perform better than a native language?</p>
|
[
{
"answer_id": 145559,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 8,
"selected": false,
"text": "using finally using readonly final const using"
},
{
"answer_id": 7318496,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 1,
"selected": false,
"text": "System.Reflection.Emit"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23126/"
] |
145,131
|
<p>I work with a lot of web applications that are driven by databases of varying complexity on the backend. Typically, there's an <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" rel="noreferrer">ORM</a> layer separate from the business and presentation logic. This makes unit-testing the business logic fairly straightforward; things can be implemented in discrete modules and any data needed for the test can be faked through object mocking.</p>
<p>But testing the ORM and database itself has always been fraught with problems and compromises. </p>
<p>Over the years, I have tried a few strategies, none of which completely satisfied me.</p>
<ul>
<li><p>Load a test database with known data. Run tests against the ORM and confirm that the right data comes back. The disadvantage here is that your test DB has to keep up with any schema changes in the application database, and might get out of sync. It also relies on artificial data, and may not expose bugs that occur due to stupid user input. Finally, if the test database is small, it won't reveal inefficiencies like a missing index. (OK, that last one isn't really what unit testing should be used for, but it doesn't hurt.)</p></li>
<li><p>Load a copy of the production database and test against that. The problem here is that you may have no idea what's in the production DB at any given time; your tests may need to be rewritten if data changes over time. </p></li>
</ul>
<p>Some people have pointed out that both of these strategies rely on specific data, and a unit test should test only functionality. To that end, I've seen suggested:</p>
<ul>
<li>Use a mock database server, and check only that the ORM is sending the correct queries in response to a given method call.</li>
</ul>
<p>What strategies have you used for testing database-driven applications, if any? What has worked the best for you?</p>
|
[
{
"answer_id": 18004673,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 4,
"selected": false,
"text": "MockConnection"
},
{
"answer_id": 52240164,
"author": "Roman-Stop RU aggression in UA",
"author_id": 2231972,
"author_profile": "https://Stackoverflow.com/users/2231972",
"pm_score": 2,
"selected": false,
"text": "Comment Post Authors @Test\npublic void savedCommentCanBeRead() {\n // Builder is needed to declaratively specify the entity with all attributes relevant\n // for this specific test\n // Missing attributes are generated with reasonable values\n // factory's responsibility is to create entity (and all entities required by it\n // in our example Author) in the DB\n Post post = factory.create(PostBuilder.post());\n\n Comment comment = CommentBuilder.comment().forPost(post).build();\n\n sut.save(comment);\n\n Comment savedComment = sut.get(comment.getId());\n\n // this checks fields that are directly stored\n assertThat(saveComment, fieldwiseEqualTo(comment));\n // if there are some fields that are generated during save check them separately\n assertThat(saveComment.getGeneratedField(), equalTo(expectedValue)); \n}\n DEFERRED CONSTRAINTS Author"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20745/"
] |
145,154
|
<p>My singleton accessor method is usually some variant of:</p>
<pre><code>static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
</code></pre>
<p>What could I be doing to improve this?</p>
|
[
{
"answer_id": 145164,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 7,
"selected": false,
"text": "@interface MySingleton : NSObject\n{\n}\n\n+ (MySingleton *)sharedSingleton;\n@end\n\n@implementation MySingleton\n\n+ (MySingleton *)sharedSingleton\n{\n static MySingleton *sharedSingleton;\n\n @synchronized(self)\n {\n if (!sharedSingleton)\n sharedSingleton = [[MySingleton alloc] init];\n\n return sharedSingleton;\n }\n}\n\n@end\n"
},
{
"answer_id": 145232,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 2,
"selected": false,
"text": "@interface MySingleton : NSObject {\n}\n\n+(MySingleton *)sharedManager;\n\n@end\n\n\n@implementation MySingleton\n\nstatic MySingleton *sharedMySingleton = nil;\n\n+(MySingleton*)sharedManager {\n @synchronized(self) {\n if (sharedMySingleton == nil) {\n [[self alloc] init]; // assignment not done here\n }\n }\n return sharedMySingleton;\n}\n\n\n+(id)allocWithZone:(NSZone *)zone {\n @synchronized(self) {\n if (sharedMySingleton == nil) {\n sharedMySingleton = [super allocWithZone:zone];\n return sharedMySingleton; // assignment and return on first allocation\n }\n }\n return nil; //on subsequent allocation attempts return nil\n}\n\n\n-(void)dealloc {\n [super dealloc];\n}\n\n-(id)copyWithZone:(NSZone *)zone {\n return self;\n}\n\n\n-(id)retain {\n return self;\n}\n\n\n-(unsigned)retainCount {\n return UINT_MAX; //denotes an object that cannot be release\n}\n\n\n-(void)release {\n //do nothing \n}\n\n\n-(id)autorelease {\n return self; \n}\n\n\n-(id)init {\n self = [super init];\n sharedMySingleton = self;\n\n //initialize here\n\n return self;\n}\n\n@end\n"
},
{
"answer_id": 145395,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 6,
"selected": false,
"text": "+ (id)sharedFoo\n{\n static dispatch_once_t once;\n static MyFoo *sharedFoo;\n dispatch_once(&once, ^ { sharedFoo = [[self alloc] init]; });\n return sharedFoo;\n}\n"
},
{
"answer_id": 343191,
"author": "Robbie Hanson",
"author_id": 43522,
"author_profile": "https://Stackoverflow.com/users/43522",
"pm_score": 9,
"selected": true,
"text": "+(void)initialize initialize initialize static MySingleton *sharedSingleton;\n\n+ (void)initialize\n{\n static BOOL initialized = NO;\n if(!initialized)\n {\n initialized = YES;\n sharedSingleton = [[MySingleton alloc] init];\n }\n}\n"
},
{
"answer_id": 1036460,
"author": "Gregory Higley",
"author_id": 27779,
"author_profile": "https://Stackoverflow.com/users/27779",
"pm_score": -1,
"selected": false,
"text": "@implementation Singleton\n\nstatic Singleton *singleton = nil;\n\n- (id)init {\n static BOOL initialized = NO;\n if (!initialized) {\n self = [super init];\n singleton = self;\n initialized = YES;\n }\n return self;\n}\n\n+ (id)allocWithZone:(NSZone*)zone {\n @synchronized (self) {\n if (!singleton)\n singleton = [super allocWithZone:zone]; \n }\n return singleton;\n}\n\n+ (Singleton*)sharedSingleton {\n if (!singleton)\n [[Singleton alloc] init];\n return singleton;\n}\n\n@end\n -retain"
},
{
"answer_id": 2060615,
"author": "Rob Dotson",
"author_id": 250263,
"author_profile": "https://Stackoverflow.com/users/250263",
"pm_score": 0,
"selected": false,
"text": "@implementation MYSingleton\n\nstatic MYSingleton * sharedInstance = nil;\n\n+( id )sharedInstance {\n @synchronized( [ MYSingleton class ] ) {\n if( sharedInstance == nil )\n sharedInstance = [ [ MYSingleton alloc ] init ];\n }\n\n return sharedInstance;\n}\n\n+( id )allocWithZone:( NSZone * )zone {\n @synchronized( [ MYSingleton class ] ) {\n if( sharedInstance == nil )\n sharedInstance = [ super allocWithZone:zone ];\n }\n\n return sharedInstance;\n}\n\n-( id )init {\n @synchronized( [ MYSingleton class ] ) {\n self = [ super init ];\n if( self != nil ) {\n // Insert initialization code here\n }\n\n return self;\n }\n}\n\n@end\n"
},
{
"answer_id": 2294440,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 3,
"selected": false,
"text": "// Volatile to make sure we are not foiled by CPU caches\nstatic volatile ALBackendRequestManager *sharedInstance;\n\n// There's no need to call this directly, as method swizzling in sharedInstance\n// means this will get called after the singleton is initialized.\n+ (MySingleton *)simpleSharedInstance\n{\n return (MySingleton *)sharedInstance;\n}\n\n+ (MySingleton*)sharedInstance\n{\n @synchronized(self)\n {\n if (sharedInstance == nil)\n {\n sharedInstance = [[MySingleton alloc] init];\n // Replace expensive thread-safe method \n // with the simpler one that just returns the allocated instance.\n SEL origSel = @selector(sharedInstance);\n SEL newSel = @selector(simpleSharedInstance);\n Method origMethod = class_getClassMethod(self, origSel);\n Method newMethod = class_getClassMethod(self, newSel);\n method_exchangeImplementations(origMethod, newMethod);\n }\n }\n return (MySingleton *)sharedInstance;\n}\n"
},
{
"answer_id": 2449664,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 6,
"selected": false,
"text": "#import <libkern/OSAtomic.h>\n\nstatic void * volatile sharedInstance = nil; \n\n+ (className *) sharedInstance { \n while (!sharedInstance) { \n className *temp = [[self alloc] init]; \n if(!OSAtomicCompareAndSwapPtrBarrier(0x0, temp, &sharedInstance)) {\n [temp release]; \n } \n } \n return sharedInstance; \n}\n sharedInstance while sharedInstance sharedInstance sharedInstance sharedInstance OSAtomicCompareAndSwapPtrBarrier"
},
{
"answer_id": 2461717,
"author": "Jompe",
"author_id": 295600,
"author_profile": "https://Stackoverflow.com/users/295600",
"pm_score": 2,
"selected": false,
"text": "+ (MySingleton*)sharedInstance\n{\n if (sharedInstance == nil) {\n @synchronized(self) {\n if (sharedInstance == nil) {\n sharedInstance = [[MySingleton alloc] init];\n }\n }\n }\n return (MySingleton *)sharedInstance;\n}\n"
},
{
"answer_id": 3068795,
"author": "user370199",
"author_id": 370199,
"author_profile": "https://Stackoverflow.com/users/370199",
"pm_score": 0,
"selected": false,
"text": "static mySingleton *obj=nil;\n\n@implementation mySingleton\n\n-(id) init {\n if(obj != nil){ \n [self release];\n return obj;\n } else if(self = [super init]) {\n obj = self;\n } \n return obj;\n}\n\n+(mySingleton*) getSharedInstance {\n @synchronized(self){\n if(obj == nil) {\n obj = [[mySingleton alloc] init];\n }\n }\n return obj;\n}\n\n- (id)retain {\n return self;\n}\n\n- (id)copy {\n return self;\n}\n\n- (unsigned)retainCount {\n return UINT_MAX; // denotes an object that cannot be released\n}\n\n- (void)release {\n if(obj != self){\n [super release];\n }\n //do nothing\n}\n\n- (id)autorelease {\n return self;\n}\n\n-(void) dealloc {\n [super dealloc];\n}\n@end\n"
},
{
"answer_id": 4312421,
"author": "obscenum",
"author_id": 524927,
"author_profile": "https://Stackoverflow.com/users/524927",
"pm_score": 3,
"selected": false,
"text": "static id sharedInstance = nil;\n\n#define DEFINE_SHARED_INSTANCE + (id) sharedInstance { return [self sharedInstance:&sharedInstance]; } \\\n + (id) allocWithZone:(NSZone *)zone { return [self allocWithZone:zone forInstance:&sharedInstance]; }\n\n@interface Singleton : NSObject {\n\n}\n\n+ (id) sharedInstance;\n+ (id) sharedInstance:(id*)inst;\n\n+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst;\n\n@end\n #import \"Singleton.h\"\n\n\n@implementation Singleton\n\n\n+ (id) sharedInstance { \n return [self sharedInstance:&sharedInstance];\n}\n\n+ (id) sharedInstance:(id*)inst {\n @synchronized(self)\n {\n if (*inst == nil)\n *inst = [[self alloc] init];\n }\n return *inst;\n}\n\n+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst {\n @synchronized(self) {\n if (*inst == nil) {\n *inst = [super allocWithZone:zone];\n return *inst; // assignment and return on first allocation\n }\n }\n return nil; // on subsequent allocation attempts return nil\n}\n\n- (id)copyWithZone:(NSZone *)zone {\n return self;\n}\n\n- (id)retain {\n return self;\n}\n\n- (unsigned)retainCount {\n return UINT_MAX; // denotes an object that cannot be released\n}\n\n- (void)release {\n //do nothing\n}\n\n- (id)autorelease {\n return self;\n}\n\n\n@end\n #import \"Singleton.h\"\n\n@interface SomeClass : Singleton {\n\n}\n\n@end\n\n@implementation SomeClass \n\nDEFINE_SHARED_INSTANCE;\n\n@end\n"
},
{
"answer_id": 4708837,
"author": "Dan Rosenstark",
"author_id": 8047,
"author_profile": "https://Stackoverflow.com/users/8047",
"pm_score": 0,
"selected": false,
"text": "static Server *instance;\n\n+ (Server *)instance { return instance; }\n\n+ (id)hiddenAlloc\n{\n return [super alloc];\n}\n\n+ (id)alloc\n{\n return [[self instance] retain];\n}\n\n\n+ (void)initialize\n{\n static BOOL initialized = NO;\n if(!initialized)\n {\n initialized = YES;\n instance = [[Server hiddenAlloc] init];\n }\n}\n\n- (id) init\n{\n if (instance)\n return self;\n self = [super init];\n if (self != nil) {\n // whatever\n }\n return self;\n}\n"
},
{
"answer_id": 4777258,
"author": "deleted_user",
"author_id": 490696,
"author_profile": "https://Stackoverflow.com/users/490696",
"pm_score": -1,
"selected": false,
"text": "+ (MySingleton*)sharedInstance\n{\n @synchronized(self) <-------- self does not exist at class scope\n {\n if (sharedInstance == nil)\n sharedInstance = [[MySingleton alloc] init];\n }\n return sharedInstance;\n}\n + (MySingleton*)getInstance\n{\n @synchronized([MySingleton class]) \n {\n if (sharedInstance == nil)\n sharedInstance = [[MySingleton alloc] init];\n }\n return sharedInstance;\n}\n"
},
{
"answer_id": 6271064,
"author": "lorean",
"author_id": 717439,
"author_profile": "https://Stackoverflow.com/users/717439",
"pm_score": 4,
"selected": false,
"text": "+ (void) initialize {\n _instance = [[MySingletonClass alloc] init] // <----- Wrong!\n}\n\n+ (void) initialize {\n if (self == [MySingletonClass class]){ // <----- Correct!\n _instance = [[MySingletonClass alloc] init] \n }\n}\n [[MySingletonClass getInstance] addObserver:self forKeyPath:@\"foo\" options:0 context:nil]\n +initialize - (id) init { <----- Wrong!\n if (_instance != nil) {\n // Some hack\n }\n else {\n // Do stuff\n }\n return self;\n}\n - (id) init { <----- Correct!\n NSAssert(_instance == nil, @\"Duplication initialization of singleton\");\n self = [super init];\n if (self){\n // Do stuff\n }\n return self;\n}\n @implementation MySingletonClass\nstatic MySingletonClass * _instance;\n+ (void) initialize {\n if (self == [MySingletonClass class]){\n _instance = [[MySingletonClass alloc] init];\n }\n}\n\n- (id) init {\n ZAssert (_instance == nil, @\"Duplication initialization of singleton\");\n self = [super init];\n if (self) {\n // Initialization\n }\n return self;\n}\n\n+ (id) getInstance {\n return _instance;\n}\n@end\n"
},
{
"answer_id": 8232992,
"author": "Nate",
"author_id": 761771,
"author_profile": "https://Stackoverflow.com/users/761771",
"pm_score": 0,
"selected": false,
"text": "Singeton.h /**\n @abstract Helps define the interface of a singleton.\n @param TYPE The type of this singleton.\n @param NAME The name of the singleton accessor. Must match the name used in the implementation.\n @discussion\n Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.\n */\n#define SingletonInterface(TYPE, NAME) \\\n+ (TYPE *)NAME;\n\n\n/**\n @abstract Helps define the implementation of a singleton.\n @param TYPE The type of this singleton.\n @param NAME The name of the singleton accessor. Must match the name used in the interface.\n @discussion\n Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.\n */\n#define SingletonImplementation(TYPE, NAME) \\\nstatic TYPE *__ ## NAME; \\\n\\\n\\\n+ (void)initialize \\\n{ \\\n static BOOL initialized = NO; \\\n if(!initialized) \\\n { \\\n initialized = YES; \\\n __ ## NAME = [[TYPE alloc] init]; \\\n } \\\n} \\\n\\\n\\\n+ (TYPE *)NAME \\\n{ \\\n return __ ## NAME; \\\n}\n MyManager.h @interface MyManager\n\nSingletonInterface(MyManager, sharedManager);\n\n// ...\n\n@end\n MyManager.m @implementation MyManager\n\n- (id)init\n{\n self = [super init];\n if (self) {\n // Initialization code here.\n }\n\n return self;\n}\n\nSingletonImplementation(MyManager, sharedManager);\n\n// ...\n\n@end\n"
},
{
"answer_id": 8671831,
"author": "Tony",
"author_id": 692499,
"author_profile": "https://Stackoverflow.com/users/692499",
"pm_score": 2,
"selected": false,
"text": "static MyClass *gInstance = NULL;\n\n+ (MyClass *)instance\n{\n if (gInstance == NULL) {\n @synchronized(self)\n {\n if (gInstance == NULL)\n gInstance = [[self alloc] init];\n }\n }\n\n return(gInstance);\n}\n"
},
{
"answer_id": 9187363,
"author": "quellish",
"author_id": 1059025,
"author_profile": "https://Stackoverflow.com/users/1059025",
"pm_score": 3,
"selected": false,
"text": "static SomeSingleton *instance = NULL;\n\n@implementation SomeSingleton\n\n+ (id) instance {\n static dispatch_once_t onceToken;\n dispatch_once(&onceToken, ^{\n if (instance == NULL){\n instance = [[super allocWithZone:NULL] init];\n }\n });\n return instance;\n}\n\n+ (id) allocWithZone:(NSZone *)paramZone {\n return [[self instance] retain];\n}\n\n- (id) copyWithZone:(NSZone *)paramZone {\n return self;\n}\n\n- (id) autorelease {\n return self;\n}\n\n- (NSUInteger) retainCount {\n return NSUIntegerMax;\n}\n\n- (id) retain {\n return self;\n}\n\n@end\n"
},
{
"answer_id": 9235774,
"author": "chunkyguy",
"author_id": 286094,
"author_profile": "https://Stackoverflow.com/users/286094",
"pm_score": 0,
"selected": false,
"text": "[[Librarian sharedInstance] openLibrary]\n [Librarian openLibrary]\n"
},
{
"answer_id": 9826878,
"author": "JJD",
"author_id": 356895,
"author_profile": "https://Stackoverflow.com/users/356895",
"pm_score": 0,
"selected": false,
"text": "static MySingleton* sharedSingleton = nil;\n\n+ (void)initialize {\n static BOOL initialized = NO;\n if (!initialized) {\n initialized = YES;\n sharedSingleton = [[self alloc] init];\n }\n}\n\n- (id)init {\n self = [super init];\n if (self) {\n // Member initialization here.\n }\n return self;\n}\n"
},
{
"answer_id": 10439812,
"author": "kevinlawler",
"author_id": 365478,
"author_profile": "https://Stackoverflow.com/users/365478",
"pm_score": 1,
"selected": false,
"text": "alloc init"
},
{
"answer_id": 14015047,
"author": "TienDC",
"author_id": 1266274,
"author_profile": "https://Stackoverflow.com/users/1266274",
"pm_score": 0,
"selected": false,
"text": "static id instanceOfXXX = nil;\n\n+ (id) sharedXXX\n{\n static volatile BOOL initialized = NO;\n\n if (!initialized)\n {\n @synchronized([XXX class])\n {\n if (!initialized)\n {\n instanceOfXXX = [[XXX alloc] init];\n initialized = YES;\n }\n }\n }\n\n return instanceOfXXX;\n}\n"
},
{
"answer_id": 14949104,
"author": "Zolt",
"author_id": 884625,
"author_profile": "https://Stackoverflow.com/users/884625",
"pm_score": 0,
"selected": false,
"text": "+(SingletonObject *) sharedManager\n{\n static SingletonObject * sharedResourcesObj = nil;\n\n @synchronized(self)\n {\n if (!sharedResourcesObj)\n {\n sharedResourcesObj = [[SingletonObject alloc] init];\n }\n }\n\n return sharedResourcesObj;\n}\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23113/"
] |
145,155
|
<p>I am making a Python gui project that needs to duplicate the look of a Windows gui environment (ie Explorer). I have my own custom icons to draw but they should be selectable by the same methods as usual; click, ctrl-click, drag box etc. Are any of the gui toolkits going to help with this or will I have to implement it all myself. If there aren't any tools to help with this advice would be greatly appreciated.</p>
<p><em>edit</em> I am not trying to recreate explorer, that would be madness. I simply want to be able to take icons and lay them out in a scrollable window. Any number of them may be selected at once. It would be great if there was something that could select/deselect them in the same (appearing at least) way that Windows does. Then all I would need is a list of all the selected icons.</p>
|
[
{
"answer_id": 145162,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": true,
"text": "gtk.IconView"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176/"
] |
145,169
|
<p>I'm using the current version of restful_authentication that is found on github and I'm having a bunch of strange session issues. The server seems to be somehow assigning sessions to users it shouldn't be. This only happens when crossing the logged out/logged in barrier.</p>
<p>Here's an example. With no sessions active on the server, I log in to an account with user A. On another machine, I log in with user B. Then when logging out of user B, sometime after the logout redirect happens, I will be logged in as user A. From this point, I can continue to navigate the site as if I had logged in as that user! Something I've observed via the logs is that when this hijack happens, the session IDs are not the same. User A is logged in in both sessions, but the session ID's are completely different. This is just one example of what might happen. I can't reproduce the issue reliably as it is seemingly random. </p>
<p>It doesn't seem to be a symptom of the environment or the server it's running on. I can reproduce the problem using both mongrel and passenger. I've also seen it in development and production. I am using db-based sessions in this application and it is running on Rails 2.1.1. I applied the stateful option when calling the generator. Otherwise no other modifications have been made to how sessions are handled.</p>
<p>Update
Here is the offending method which came directly from restful_authentication.</p>
<pre><code># Accesses the current user from the session.
# Future calls avoid the database because nil is not equal to false.
def current_user
@current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false
end
</code></pre>
|
[
{
"answer_id": 147032,
"author": "Nathan de Vries",
"author_id": 11109,
"author_profile": "https://Stackoverflow.com/users/11109",
"pm_score": 2,
"selected": false,
"text": "User.current_user"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23128/"
] |
145,175
|
<p>Right now I write expressions in the <code>*scratch*</code> buffer and test them by evaluating with <kbd>C-x</kbd> <kbd>C-e</kbd>. I would really appreciate having an interactive interpreter like SLIME or irb, in which I could test Emacs Lisp expressions.</p>
|
[
{
"answer_id": 145205,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 1,
"selected": false,
"text": "*scratch*"
},
{
"answer_id": 145212,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 1,
"selected": false,
"text": "(require 'cl)\n\n(defun read-expression ()\n (condition-case\n err\n (read-string \"> \")\n (error\n (message \"Error reading '%s'\" form)\n (message (format \"%s\" err)))))\n\n(defun read-expression-from-string (str)\n (condition-case\n err\n (read-from-string str)\n (error\n (message \"Error parsing '%s'\" str)\n (message (format \"%s\" err))\n nil)))\n\n(defun repl ()\n (loop for expr = (read-string \"> \") then (read-expression)\n do\n (let ((form (car (read-expression-from-string expr))))\n (condition-case\n err\n (message \" => %s\" (eval form))\n (error\n (message \"Error evaluating '%s'\" form)\n (message (format \"%s\" err)))))))\n\n(repl)\n kburton@hypothesis:~/projects/elisp$ emacs -batch -l test.el\nLoading 00debian-vars...\n> (defvar x '(lambda (y) (* y 100)))\n => x\n> (funcall x 0.25)\n => 25.0\n> \nkburton@hypothesis:~/projects/elisp$\n"
},
{
"answer_id": 145218,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 3,
"selected": false,
"text": "*scratch* M-x set-variable debug-on-error t\n C-j C-x C-e * * * *scratch* * * * ielm M-x ielm\n"
},
{
"answer_id": 146251,
"author": "Greg Mattes",
"author_id": 13940,
"author_profile": "https://Stackoverflow.com/users/13940",
"pm_score": 7,
"selected": true,
"text": "M-x ielm\n"
},
{
"answer_id": 2090294,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 4,
"selected": false,
"text": "M-x eshell\n ~ $ ls\nfoo.txt\nbar.txt\n~ $ (+ 1 1)\n2\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21998/"
] |
145,190
|
<p>I'm trying to come up with a way to estimate the number of English words a translation from Japanese will turn into. Japanese has three main scripts -- <a href="http://en.wikipedia.org/wiki/Kanji" rel="nofollow noreferrer">Kanji</a>, <a href="http://en.wikipedia.org/wiki/Hiragana" rel="nofollow noreferrer">Hiragana</a>, and <a href="http://en.wikipedia.org/wiki/Katakana" rel="nofollow noreferrer">Katakana</a> -- and each has a different average character-to-word ratio (Kanji being the lowest, Katakana the highest).</p>
<p><strong>Examples:</strong></p>
<ul>
<li>computer: コンピュータ (Katakana - 6
characters); 計算機 (Kanji: 3
characters)</li>
<li>whale: くじら (Hiragana --
3 characters); 鯨 (Kanji: 1
character)</li>
</ul>
<p>As data, I have a large glossary of Japanese words and their English translations, and a fairly large corpus of matched Japanese source documents and their English translations. I want to come up with a formula that will count numbers of Kanji, Hiragana, and Katakana characters in a source text, and estimate the number of English words this is likely to turn into.</p>
|
[
{
"answer_id": 145235,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "Expected increase\n1-5 100%\n6-12 80%\n13-20 60%\n21-30 40%\n31-50 20%\nover 50 10%\n"
},
{
"answer_id": 146427,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 2,
"selected": true,
"text": "approx_english_words = a1*no_characters_in_script1 + a2 * no_chars_in_script2 + a3 * no_chars_in_script3"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10658/"
] |
145,209
|
<p>I want to mount some internal and external NTFS drives in CentOS 5.2, preferably automatically upon boot-up. Doesn't matter if it's read/write or read-only, but read/write would be preferred, if it's safe.</p>
<p>Edit: Thanks for all answers, I summarized them below =)</p>
|
[
{
"answer_id": 145219,
"author": "PostMan",
"author_id": 18405,
"author_profile": "https://Stackoverflow.com/users/18405",
"pm_score": 3,
"selected": false,
"text": "fdisk -l\n mount /dev/sda2 /mnt/windows\n yum install ntfs-3g\n /dev/sda2 /mnt/temp ntfs defaults 0 0\n"
},
{
"answer_id": 145237,
"author": "DV.",
"author_id": 18406,
"author_profile": "https://Stackoverflow.com/users/18406",
"pm_score": 4,
"selected": true,
"text": "su mkdir /mnt/iomega80\nmkdir /mnt/iogear250\n yum install util-linux\n /sbin/fdisk -l Disk /dev/sdc: 250.0 GB, 250059350016 bytes\n255 heads, 63 sectors/track, 30401 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\n\n Device Boot Start End Blocks Id System\n**/dev/sdc1** * 1 30401 244196001 7 HPFS/NTFS\n\nDisk /dev/sdd: 82.3 GB, 82348278272 bytes\n255 heads, 63 sectors/track, 10011 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\n\n Device Boot Start End Blocks Id System\n**/dev/sdd1** * 1 10011 80413326 7 HPFS/NTFS\n /dev/sdc1 /dev/sdd1 wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.3.6-1.el5.rf.i386.rpm\nrpm -Uhv rpmforge-release-0.3.6-1.el5.rf.i386.rpm \n yum install fuse fuse-ntfs-3g dkms dkms-fuse\n mount -t ntfs-3g /dev/sdc1 /mnt/iogear250\nmount -t ntfs-3g /dev/sdd1 /mnt/iomega80\n /etc/fstab /dev/sdc1 /mnt/iogear250 ntfs-3g rw,umask=0000,defaults 0 0\n/dev/sdd1 /mnt/iomega80 ntfs-3g rw,umask=0000,defaults 0 0\n"
},
{
"answer_id": 42056904,
"author": "Esther",
"author_id": 948935,
"author_profile": "https://Stackoverflow.com/users/948935",
"pm_score": 0,
"selected": false,
"text": "yum install epel-release\n yum install ntfs-3g\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18406/"
] |
145,241
|
<h2><strong>Edit: I have solved this by myself. See <a href="https://stackoverflow.com/questions/145241/change-the-value-of-a-text-box-to-its-current-order-in-a-sortable-tab/145388#145388">my answer below</a></strong></h2>
<p>I have set up a nice sortable table with jQuery and it is quite nice. But now i want to extend it.</p>
<p>Each table row has a text box, and i want i am after is to, every time a row is dropped, the text boxes update to reflect the order of the text boxes. <strong>E.g. The text box up the top always has the value of '1', the second is always '2' and so on.</strong></p>
<p>I am using jQuery and the <a href="http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/" rel="nofollow noreferrer">Table Drag and Drop JQuery plugin</a></p>
<h3>Code</h3>
<p><strong>Javascript:</strong></p>
<pre><code><script type = "text/javascript" >
$(document).ready(function () {
$("#table-2").tableDnD({
onDrop: function (table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Order: ";
for (var i = 0; i < rows.length; i++) {
debugStr += rows[i].id + ", ";
}
console.log(debugStr)
document.forms['productform'].sort1.value = debugStr;
document.forms['productform'].sort2.value = debugStr;
document.forms['productform'].sort3.value = debugStr;
document.forms['productform'].sort4.value = debugStr;
},
});
});
</script>
</code></pre>
<p><strong>HTML Table:</strong></p>
<pre class="lang-html prettyprint-override"><code><form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr>
<td>Product</td>
<td>Order</td>
</tr>
</thead>
<tbody>
<tr class="row1" id="Pol">
<td><a href="1/">Pol</a></td>
<td><input type="textbox" name="sort1"/></td>
</tr>
<tr class="row2" id="Evo">
<td><a href="2/">Evo</a></td>
<td><input type="textbox" name="sort2"/></td>
</tr>
<tr class="row3" id="Kal">
<td><a href="3/">Kal</a></td>
<td><input type="textbox" name="sort3"/></td>
</tr>
<tr class="row4" id="Lok">
<td><a href="4/">Lok</a></td>
<td><input type="textbox" name="sort4"/></td>
</tr>
</tbody>
</table>
</form>
</code></pre>
|
[
{
"answer_id": 145284,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 0,
"selected": false,
"text": "$(\"input:text\", \"#table-2\").each( function(i){ this.value=i+1; });\n"
},
{
"answer_id": 145388,
"author": "Josh Hunt",
"author_id": 2592,
"author_profile": "https://Stackoverflow.com/users/2592",
"pm_score": 2,
"selected": true,
"text": "<form name=\"productform\">\n <table cellspacing=\"0\" id=\"table-2\" name=\"productform\"> \n <thead>\n <tr><td>Product</td> <td>Order</td></tr> \n </thead>\n\n <tbody>\n <tr class=\"row1\" id=\"Pol\"> <td><a href=\"1/\">Pol</a></td> <td><input id=\"Pol_field\" type=\"textbox\" name=\"sort1\"/></td> </tr>\n <tr class=\"row2\" id=\"Evo\"> <td><a href=\"2/\">Evo</a></td> <td><input id=\"Evo_field\" type=\"textbox\" name=\"sort2\"/></td> </tr>\n <tr class=\"row3\" id=\"Kal\"> <td><a href=\"3/\">Kal</a></td> <td><input id=\"Kal_field\" type=\"textbox\" name=\"sort3\"/></td> </tr>\n <tr class=\"row4\" id=\"Lok\"> <td><a href=\"4/\">Lok</a></td> <td><input id=\"Lok_field\" type=\"textbox\" name=\"sort4\"/></td> </tr>\n </tbody> \n </table>\n</form>\n for (var i=0; i < rows.length; i++) {\n $('#' + rows[i].id + \"_field\").val(i+1);\n}\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] |
145,262
|
<p>I have a home-spun 2000 lines VBScript script, that has become progressively slow with each additional code I add. It was created as a private debugging aid and now that it has become really useful. I want to polish it and ship it along with our product.</p>
<p>I thought I could speed it up by compiling it and making it an EXE. Furthermore I want to have a user interface for my tool, which might be possible once I use the extra libraries that the compiling platform might give me. I'm also considering extending the script by calling <a href="http://en.wikipedia.org/wiki/Windows_API" rel="nofollow noreferrer">Win32</a> functions for whatever missing functionalities I require. </p>
<p>I have VB 6.0 or I can buy an external compiler. But I also need the created program (not the compiler itself) to run fine in Windows Vista. What are my best options? </p>
|
[
{
"answer_id": 641813,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "wscript.echo \"Begin: \" & Time\ntStartTime = Timer\n'... do stuff ...\ntStopTime = Timer\nwscript.echo \"Elapsed time: \" & tStopTime - tStartTime\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17224/"
] |
145,263
|
<p><a href="http://en.wikipedia.org/wiki/Total_functional_programming" rel="noreferrer">Wikipedia</a> has this to say:</p>
<blockquote>
<p>Total functional programming (also
known as strong functional
programming, to be contrasted with
ordinary, or weak functional
programming) is a programming paradigm
which restricts the range of programs
to those which are provably
terminating.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>These restrictions mean that total
functional programming is not
Turing-complete. However, the set of
algorithms which can be used is still
huge. For example, any algorithm which
has had an asymptotic upper bound
calculated for it can be trivially
transformed into a
provably-terminating function by using
the upper bound as an extra argument
which is decremented upon each
iteration or recursion.</p>
</blockquote>
<p>There is also a Lambda The Ultimate Post about a paper on <a href="http://lambda-the-ultimate.org/node/2003" rel="noreferrer">Total Functional Programming</a>.</p>
<p>I hadn't come across that until last week on a mailing list.</p>
<p>Are there any more resources, references or any example implementations that you know of?</p>
|
[
{
"answer_id": 145318,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 6,
"selected": true,
"text": "v v"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
] |
145,270
|
<p>What would be the quickest way to construct a Python binding to a C or C++ library?</p>
<p>(I am using Windows if this matters.)</p>
|
[
{
"answer_id": 145283,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 6,
"selected": false,
"text": "/* File : example.c */\nint fact(int n) {\n if (n <= 1) return 1;\n else return n*fact(n-1);\n}\n /* example.i */\n%module example\n%{\n/* Put header files here or function declarations like below */\nextern int fact(int n);\n%}\n\nextern int fact(int n);\n swig -python example.i\ngcc -fPIC -c example.c example_wrap.c -I/usr/local/include/python2.7\ngcc -shared example.o example_wrap.o -o _example.so\n >>> import example\n>>> example.fact(5)\n120\n"
},
{
"answer_id": 145649,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 10,
"selected": false,
"text": "#include <iostream>\n\nclass Foo{\n public:\n void bar(){\n std::cout << \"Hello\" << std::endl;\n }\n};\n extern \"C\" {\n Foo* Foo_new(){ return new Foo(); }\n void Foo_bar(Foo* foo){ foo->bar(); }\n}\n g++ -c -fPIC foo.cpp -o foo.o\ng++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o\n from ctypes import cdll\nlib = cdll.LoadLibrary('./libfoo.so')\n\nclass Foo(object):\n def __init__(self):\n self.obj = lib.Foo_new()\n\n def bar(self):\n lib.Foo_bar(self.obj)\n f = Foo()\nf.bar() #and you will see \"Hello\" on the screen\n"
},
{
"answer_id": 23865947,
"author": "Antonello",
"author_id": 1586860,
"author_profile": "https://Stackoverflow.com/users/1586860",
"pm_score": 6,
"selected": false,
"text": "#include <vector>\n#include \"code.h\"\n\nusing namespace std;\n\nvector<double> average (vector< vector<double> > i_matrix) {\n\n // Compute average of each row..\n vector <double> averages;\n for (int r = 0; r < i_matrix.size(); r++){\n double rsum = 0.0;\n double ncols= i_matrix[r].size();\n for (int c = 0; c< i_matrix[r].size(); c++){\n rsum += i_matrix[r][c];\n }\n averages.push_back(rsum/ncols);\n }\n return averages;\n}\n #ifndef _code\n#define _code\n\n#include <vector>\n\nstd::vector<double> average (std::vector< std::vector<double> > i_matrix);\n\n#endif\n g++ -c -fPIC code.cpp\n %module code\n%{\n#include \"code.h\"\n%}\n%include \"std_vector.i\"\nnamespace std {\n\n /* On a side note, the names VecDouble and VecVecdouble can be changed, but the order of first the inner vector matters! */\n %template(VecDouble) vector<double>;\n %template(VecVecdouble) vector< vector<double> >;\n}\n\n%include \"code.h\"\n swig -c++ -python code.i\n g++ -c -fPIC code_wrap.cxx -I/usr/include/python2.7 -I/usr/lib/python2.7\ng++ -shared -Wl,-soname,_code.so -o _code.so code.o code_wrap.o\n #!/usr/bin/env python\n\nimport code\na= [[3,5,7],[8,10,12]]\nprint a\nb = code.average(a)\nprint \"Assignment done\"\nprint a\nprint b\n"
},
{
"answer_id": 32264764,
"author": "Jadav Bheda",
"author_id": 454023,
"author_profile": "https://Stackoverflow.com/users/454023",
"pm_score": 3,
"selected": false,
"text": ">>> from ctypes import *\n>>> libc = cdll.msvcrt\n>>> print libc.time(None)\n1438069008\n>>> printf = libc.printf\n>>> printf(\"Hello, %s\\n\", \"World!\")\nHello, World!\n14\n>>> printf(\"%d bottles of beer\\n\", 42)\n42 bottles of beer\n19\n"
},
{
"answer_id": 34515909,
"author": "nicodjimenez",
"author_id": 2559219,
"author_profile": "https://Stackoverflow.com/users/2559219",
"pm_score": 3,
"selected": false,
"text": "runcython"
},
{
"answer_id": 38542539,
"author": "Tom Wenseleers",
"author_id": 1887645,
"author_profile": "https://Stackoverflow.com/users/1887645",
"pm_score": 6,
"selected": false,
"text": "pybind11"
},
{
"answer_id": 49120918,
"author": "Wim Lavrijsen",
"author_id": 9448377,
"author_profile": "https://Stackoverflow.com/users/9448377",
"pm_score": 5,
"selected": false,
"text": " $ pip install cppyy\n $ cat foo.h\n class Foo {\n public:\n void bar();\n };\n\n $ cat foo.cpp\n #include \"foo.h\"\n #include <iostream>\n\n void Foo::bar() { std::cout << \"Hello\" << std::endl; }\n $ g++ -c -fPIC foo.cpp -o foo.o\n $ g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o\n $ python\n >>> import cppyy\n >>> cppyy.include(\"foo.h\")\n >>> cppyy.load_library(\"foo\")\n >>> from cppyy.gbl import Foo\n >>> f = Foo()\n >>> f.bar()\n Hello\n >>>\n $ python\n >>> import cppyy\n >>> f = cppyy.gbl.Foo()\n >>> f.bar()\n Hello\n >>>\n >>> v = cppyy.gbl.std.vector[cppyy.gbl.Foo]()\n >>> v.push_back(f)\n >>> len(v)\n 1\n >>> v[0].bar()\n Hello\n >>>\n"
},
{
"answer_id": 59407195,
"author": "Garfield",
"author_id": 12564188,
"author_profile": "https://Stackoverflow.com/users/12564188",
"pm_score": 4,
"selected": false,
"text": "import cppyy\nimport numpy as np\ncppyy.include('Buffer.h')\n\n\ns = cppyy.gbl.Buffer()\nnumpy_array = np.empty(32000, np.float64)\ns.get_numpy_array(numpy_array.data, numpy_array.size)\nprint(numpy_array[:20])\n struct Buffer {\n void get_numpy_array(double *ad, int size) {\n for( long i=0; i < size; i++)\n ad[i]=i;\n }\n};\n"
},
{
"answer_id": 60374990,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "#include <string>\n\n#include <pybind11/pybind11.h>\n\nstruct ClassTest {\n ClassTest(const std::string &name, int i) : name(name), i(i) { }\n void setName(const std::string &name_) { name = name_; }\n const std::string getName() const { return name + \"z\"; }\n void setI(const int i) { this->i = i; }\n const int getI() const { return i + 1; }\n std::string name;\n int i;\n};\n\nnamespace py = pybind11;\n\nPYBIND11_PLUGIN(class_test) {\n py::module m(\"my_module\", \"pybind11 example plugin\");\n py::class_<ClassTest>(m, \"ClassTest\")\n .def(py::init<const std::string &, int>())\n .def(\"setName\", &ClassTest::setName)\n .def(\"getName\", &ClassTest::getName)\n .def_readwrite(\"name\", &ClassTest::name)\n .def(\"setI\", &ClassTest::setI)\n .def(\"getI\", &ClassTest::getI)\n .def_readwrite(\"i\", &ClassTest::i);\n return m.ptr();\n}\n #!/usr/bin/env python3\n\nimport class_test\n\nmy_class_test = class_test.ClassTest(\"abc\", 1);\nprint(my_class_test.getName())\nprint(my_class_test.getI())\nmy_class_test.setName(\"012\")\nmy_class_test.setI(2)\nprint(my_class_test.getName())\nprint(my_class_test.getI())\nassert(my_class_test.getName() == \"012z\")\nassert(my_class_test.getI() == 3)\n #!/usr/bin/env bash\nset -eux\nsudo apt install pybind11-dev\ng++ `python3-config --cflags` -shared -std=c++11 -fPIC class_test.cpp \\\n -o class_test`python3-config --extension-suffix` `python3-config --libs`\n./class_test_main.py\n abcz\n2\n012z\n3\n my_class_test.setI(\"abc\")\n Traceback (most recent call last):\n File \"/home/ciro/test/./class_test_main.py\", line 9, in <module>\n my_class_test.setI(\"abc\")\nTypeError: setI(): incompatible function arguments. The following argument types are supported:\n 1. (self: my_module.ClassTest, arg0: int) -> None\n\nInvoked with: <my_module.ClassTest object at 0x7f2980254fb0>, 'abc'\n ClassTest name std::string str class_test.cpython-36m-x86_64-linux-gnu.so class_test_main.py class_test Boost.Python"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
] |
145,291
|
<p>Can you have smart behavior for the home key in Emacs? By smart I mean that instead of going to the character number 0, it should go to the first non-blank character, and go to 0 on a second pressing, and back to the first non-blank in a third and so on.
Having smart end would be nice as well.</p>
|
[
{
"answer_id": 145359,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 7,
"selected": true,
"text": "(defun smart-beginning-of-line ()\n \"Move point to first non-whitespace character or beginning-of-line.\n\nMove point to the first non-whitespace character on this line.\nIf point was already at that position, move point to beginning of line.\"\n (interactive \"^\") ; Use (interactive) in Emacs 22 or older\n (let ((oldpos (point)))\n (back-to-indentation)\n (and (= oldpos (point))\n (beginning-of-line))))\n\n(global-set-key [home] 'smart-beginning-of-line)\n (beginning-of-line-text) (back-to-indentation) (back-to-indentation) (beginning-of-line-text)"
},
{
"answer_id": 145360,
"author": "Robert Vuković",
"author_id": 438025,
"author_profile": "https://Stackoverflow.com/users/438025",
"pm_score": 4,
"selected": false,
"text": "\n(defun My-smart-home () \"Odd home to beginning of line, even home to beginning of text/code.\"\n (interactive)\n (if (and (eq last-command 'My-smart-home)\n (/= (line-beginning-position) (point)))\n (beginning-of-line)\n (beginning-of-line-text))\n)\n\n(global-set-key [home] 'My-smart-home)\n"
},
{
"answer_id": 3802932,
"author": "Gerard Thornley",
"author_id": 459363,
"author_profile": "https://Stackoverflow.com/users/459363",
"pm_score": 3,
"selected": false,
"text": "^' and"
},
{
"answer_id": 25699185,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 0,
"selected": false,
"text": "beggining-of-line (defun my-smart-beginning-of-line ()\n \"Move point to beginning-of-line. If repeat command it cycle\nposition between `back-to-indentation' and `beginning-of-line'.\"\n (interactive \"^\")\n (if (and (eq last-command 'my-smart-beginning-of-line)\n (= (line-beginning-position) (point)))\n (back-to-indentation)\n (beginning-of-line)))\n\n(global-set-key [home] 'my-smart-beginning-of-line)\n"
},
{
"answer_id": 34477529,
"author": "amynbe",
"author_id": 326162,
"author_profile": "https://Stackoverflow.com/users/326162",
"pm_score": 2,
"selected": false,
"text": "mwim"
},
{
"answer_id": 58807168,
"author": "Bach Lien",
"author_id": 3973676,
"author_profile": "https://Stackoverflow.com/users/3973676",
"pm_score": 1,
"selected": false,
"text": "(defun smart-beginning-of-line ()\n \"Move point to beginning-of-line or first non-whitespace character\"\n (interactive \"^\")\n (let ((p (point)))\n (beginning-of-visual-line)\n (if (= p (point)) (back-to-indentation))\n (if (= p (point)) (beginning-of-line))))\n(global-set-key [home] 'smart-beginning-of-line)\n(global-set-key \"\\C-a\" 'smart-beginning-of-line)\n [home] \"\\C-a\" interactive \"^\""
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
145,304
|
<p>I have been trying to learn multi-threaded programming in C# and I am confused about when it is best to use a thread pool vs. create my own threads. One book recommends using a thread pool for small tasks only (whatever that means), but I can't seem to find any real guidelines.</p>
<p>What are some pros and cons of thread pools vs creating my own threads? And what are some example use cases for each?</p>
|
[
{
"answer_id": 145420,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 3,
"selected": false,
"text": "FileStream BeginRead EndRead HttpWebRequest BeginGetResponse EndGetResponse"
},
{
"answer_id": 208621,
"author": "noocyte",
"author_id": 11220,
"author_profile": "https://Stackoverflow.com/users/11220",
"pm_score": 0,
"selected": false,
"text": "using System.Collections.Generic;\nusing System.Threading;\n\nnamespace ThreadSafeQueue {\n public class ThreadSafeQueue<T> {\n private Queue<T> _queue;\n\n public ThreadSafeQueue() {\n _queue = new Queue<T>();\n }\n\n public void EnqueueSafe(T item) {\n lock ( this ) {\n _queue.Enqueue(item);\n if ( _queue.Count >= 1 )\n Monitor.Pulse(this);\n }\n }\n\n public T DequeueSafe() {\n lock ( this ) {\n while ( _queue.Count <= 0 )\n Monitor.Wait(this);\n\n return this.DeEnqueueUnblock();\n\n }\n }\n\n private T DeEnqueueUnblock() {\n return _queue.Dequeue();\n }\n }\n}\n"
}
] |
2008/09/28
|
[
"https://Stackoverflow.com/questions/145304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.