qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
119,929
<p>I need to convert SAS data tables into flat files (or "ASCII files" as they were called once, as opposed to binary files). And only one flat file for each original SAS table. The challenging thing is that I want the flat file to contain some structural information of the original SAS table also, specifically:</p> <ul> <li>Variable/Column name</li> <li>Variable/Column label</li> <li>Variable/Column type</li> <li>Variable/Column length</li> <li>Variable/Column format</li> <li>Variable/Column informat</li> </ul> <p>Additional information:</p> <ul> <li>I will only need to convert small data (&lt; 100 obs).</li> <li>Performance is not an issue (within reasonable limits).</li> <li>The flat file should form a basis for recreating the original SAS table, I don't need to be able to use the file directly as a table in DATA or PROC steps.</li> </ul> <p>The standard SAS tables, transport files, XPORT files, etc are all binary format files, and the standard XML table format in SAS and CSV-files don't preserve table structure. So obviously these options don't help.</p> <p>What is my best option?</p>
[ { "answer_id": 539422, "author": "Rog", "author_id": 65338, "author_profile": "https://Stackoverflow.com/users/65338", "pm_score": 2, "selected": false, "text": "proc sql;\ndescribe table sashelp.class;\nquit;\n" }, { "answer_id": 2297136, "author": "secoskyj", "author_id": 243363, "author_profile": "https://Stackoverflow.com/users/243363", "pm_score": 2, "selected": false, "text": "libname myfiles 'SAS-library';\nlibname trans xml92 'XML-document' xmltype=export;\nproc copy in=myfiles out=trans;\n select class;\nrun;\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18968/" ]
119,941
<p>I want to create variables inside function from dictionary.</p> <p>Lets say I have a dictionary</p> <pre><code>bar = {'a': 1, 'b': 2, 'c': 3} </code></pre> <p>and function</p> <pre><code>def foo(): pass </code></pre> <p>What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values</p> <p>So in the end it should be similar to</p> <pre><code>def foo(): a = 1 b = 2 c = 3 </code></pre> <p>Is it possible at all? And if it does, how to do such thing?</p>
[ { "answer_id": 119964, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 1, "selected": false, "text": "some_code = ' return a+b+c'\nexec \"def foo():\\n \" + '\\n '.join('%s = %s' for k,v in bar.items()) + '\\n' + some_code\n" }, { "answer_id": 119983, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": true, "text": "foo.__dict__.update(bar)" }, { "answer_id": 120103, "author": "user20955", "author_id": 20955, "author_profile": "https://Stackoverflow.com/users/20955", "pm_score": 1, "selected": false, "text": "first_name = form.cleaned_data['first_name']\nlast_name = form.cleaned_data['last_name'] ..\n" }, { "answer_id": 120214, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "class Bunch(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\nb=Bunch(**form.cleaned_data)\n\nprint b.first_name, b.last_name\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20955/" ]
119,961
<p>Normally you can do this:</p> <pre><code>&lt;select size="3"&gt; &lt;option&gt;blah&lt;/option&gt; &lt;option&gt;blah&lt;/option&gt; &lt;option&gt;blah&lt;/option&gt; &lt;/select&gt; </code></pre> <p>And it would render as a selectionbox where all three options are visible (without dropping down)<br> I'm looking for a way to set this size attribute from css.</p>
[ { "answer_id": 122357, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 4, "selected": true, "text": "size = options.length;\n" }, { "answer_id": 971690, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "select { width: 5em; height: 5em; }\n" }, { "answer_id": 22340882, "author": "marco", "author_id": 3408725, "author_profile": "https://Stackoverflow.com/users/3408725", "pm_score": 2, "selected": false, "text": "select[attr=size] {\n width:auto;\n height:auto;\n}\n" }, { "answer_id": 31245377, "author": "kimomat", "author_id": 1329470, "author_profile": "https://Stackoverflow.com/users/1329470", "pm_score": 1, "selected": false, "text": "select[size]{\n/*your style here */\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
119,980
<p>Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?</p> <p>I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.</p> <p><strong>Edit:</strong> From link provided in accepted answer:</p> <p>Include Silverlight.js (from Silverlight SDK)</p> <pre><code>Silverlight.isInstalled("2.0"); </code></pre>
[ { "answer_id": 119992, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 5, "selected": true, "text": "Silverlight.isInstalled(\"4.0\")" }, { "answer_id": 120638, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 0, "selected": false, "text": "var hasSilverlight = Boolean(window.Silverlight);\n\nvar hasSilverlight2 = hasSilverlight && Silverlight.isInstalled('2.0');\n" }, { "answer_id": 3684918, "author": "Deano", "author_id": 335567, "author_profile": "https://Stackoverflow.com/users/335567", "pm_score": 0, "selected": false, "text": "\n\nif (Silverlight.isInstalled)\n{\nalert (\"Congrats. Your web browser is enabled with Silverlight Runtime\");\n}\n\n" }, { "answer_id": 4731064, "author": "Hong", "author_id": 355456, "author_profile": "https://Stackoverflow.com/users/355456", "pm_score": 0, "selected": false, "text": " if (Silverlight.isInstalled(\"1.0\")) {\n try {\n alert(\"Silverlight Version 1.0 or above is installed\");\n }\n catch (err) {\n alert(err.Description);\n }\n }\n else {\n alert(\"No Silverlight is installed\");\n }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
119,994
<p>We run full re-indexes every 7 days (i.e. creating the index from scratch) on our Lucene index and incremental indexes every 2 hours or so. Our index has around 700,000 documents and a full index takes around 17 hours (which isn't a problem).</p> <p>When we do incremental indexes, we only index content that has changed in the past two hours, so it takes much less time - around half an hour. However, we've noticed that a lot of this time (maybe 10 minutes) is spent running the IndexWriter.optimize() method.</p> <p>The <a href="http://wiki.apache.org/lucene-java/LuceneFAQ#head-fd848c31f4dc7b91727be6f40a7f5fbe2c66cfb8" rel="noreferrer">LuceneFAQ</a> mentions that:</p> <blockquote> <p>The IndexWriter class supports an optimize() method that compacts the index database and speeds up queries. You may want to use this method after performing a complete indexing of your document set or after incremental updates of the index. If your incremental update adds documents frequently, you want to perform the optimization only once in a while to avoid the extra overhead of the optimization.</p> </blockquote> <p>...but this doesn't seem to give any definition for what "frequently" means. Optimizing is CPU intensive and VERY IO-intensive, so we'd rather not be doing it if we can get away with it. How much is the hit of running queries on an un-optimized index (I'm thinking especially in terms of query performance after a full re-index compared to after 20 incremental indexes where, say, 50,000 documents have changed)? Should we be optimising after every incremental index or is the performance hit not worth it?</p>
[ { "answer_id": 120376, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 5, "selected": true, "text": "optimize()" }, { "answer_id": 390533, "author": "James Brady", "author_id": 29903, "author_profile": "https://Stackoverflow.com/users/29903", "pm_score": 2, "selected": false, "text": "optimize" }, { "answer_id": 3870475, "author": "Steen", "author_id": 1448983, "author_profile": "https://Stackoverflow.com/users/1448983", "pm_score": 2, "selected": false, "text": "optimize()" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6282/" ]
119,999
<p>How can I setup a shared ccache without falling into a permissions problem?</p> <p>I would like to run a nightly or CI build with latest changes and share all created binaries throughout the R&amp;D using a large ccache repository.</p>
[ { "answer_id": 3099439, "author": "Joel Rosdahl", "author_id": 331771, "author_profile": "https://Stackoverflow.com/users/331771", "pm_score": 4, "selected": false, "text": "CCACHE_DIR" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1656532/" ]
120,000
<p>I had recently a problem with oom-killer starting to kill processes after some time. I could see that the memory was consumed, but by the time I got to the server it wasn't clear anymore what consumed it. Is there a good non-obvious place to get more info about oom-killer? E.g. detailed info about processes at the time of activation, detailed info about killed processes and reasons for the choice?</p> <p>I'm looking for a specific place to find this information, specific tool to gather it or some configuration to improve oom-killer reporting. I'm not looking for generic info about oom-killer. /var/messages by default will only contain a detailed report on the free/allocated memory, but not specific processes it was allocated to.</p>
[ { "answer_id": 120063, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 1, "selected": false, "text": "malloc(3)" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20022/" ]
120,001
<p>I am looking for a free tool to load Excel data sheet into an Oracle database. I tried the Oracle SQL developer, but it keeps throwing a NullPointerException. Any ideas?</p>
[ { "answer_id": 120021, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "CREATE TABLE" }, { "answer_id": 120222, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "Utilities > Data Load/Unload > Load > Load Spreadsheet Data\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233512/" ]
120,016
<p>I have the following XML structure:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;course xml:lang="nl"&gt; &lt;body&gt; &lt;item id="787900813228567" view="12000" title="0x|Beschrijving" engtitle="0x|Description"&gt;&lt;![CDATA[Dit college leert studenten hoe ze een onderzoek kunn$ &lt;item id="5453116633894965" view="12000" title="0x|Onderwijsvorm" engtitle="0x|Method of instruction"&gt;&lt;![CDATA[instructiecollege]]&gt;&lt;/item&gt; &lt;item id="7433550075448316" view="12000" title="0x|Toetsing" engtitle="0x|Examination"&gt;&lt;![CDATA[Opdrachten/werkstuk]]&gt;&lt;/item&gt; &lt;item id="015071401858970545" view="12000" title="0x|Literatuur" engtitle="0x|Required reading"&gt;&lt;![CDATA[Wayne C. Booth, Gregory G. Colomb, Joseph M. Wi$ &lt;item id="5960589172957031" view="12000" title="0x|Uitbreiding" engtitle="0x|Expansion"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="3610066867901779" view="12000" title="0x|Aansluiting" engtitle="0x|Place in study program"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="19232369892482925" view="12000" title="0x|Toegangseisen" engtitle="0x|Course requirements"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="3332396346891524" view="12000" title="0x|Doelgroep" engtitle="0x|Target audience"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="6606851872934866" view="12000" title="0x|Aanmelden bij" engtitle="0x|Enrollment at"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="1478643580820973" view="12000" title="0x|Informatie bij" engtitle="0x|Information at"&gt;&lt;![CDATA[Docent]]&gt;&lt;/item&gt; &lt;item id="9710608434763993" view="12000" title="0x|Rooster" engtitle="0x|Schedule"&gt;&lt;![CDATA[1e semester, maandag 15.00-17.00, zaal 1175/030]]&gt;&lt;/item&gt; &lt;/body&gt; &lt;/course&gt; </code></pre> <p>I want to get the data from one of the item tags. To get to this tag, I use the following xpath:</p> <pre><code>$description = $xml-&gt;xpath("//item[@title='0x|Beschrijving']"); </code></pre> <p>This does indeed return an array in the form of:</p> <pre><code>Array ( [0] =&gt; SimpleXMLElement Object ( [@attributes] =&gt; Array ( [id] =&gt; 787900813228567 [view] =&gt; 12000 [title] =&gt; 0x|Beschrijving [engtitle] =&gt; 0x|Description ) ) ) </code></pre> <p>But where is the actual information (that is stored between the item tags) located? I must be doing something wrong, but I can't figure out what that might be... Probably something really simple... Help would be appreciated.</p>
[ { "answer_id": 120069, "author": "Marc Gear", "author_id": 6563, "author_profile": "https://Stackoverflow.com/users/6563", "pm_score": 2, "selected": false, "text": "echo $description[0];\n" }, { "answer_id": 120070, "author": "Eric_WVGG", "author_id": 82944, "author_profile": "https://Stackoverflow.com/users/82944", "pm_score": 1, "selected": false, "text": "$description = $xml->xpath(\"//item[@title='0x|Beschrijving']\");\n\nwhile(list( , $node) = each($description)) {\n\necho($node);\n\n}\n" }, { "answer_id": 120072, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 5, "selected": true, "text": "<?php\n$xml = simplexml_load_file('file.xml', NULL, LIBXML_NOCDATA);\n$description = $xml->xpath(\"//item[@title='0x|Beschrijving']\");\nvar_dump($description);\n?>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18922/" ]
120,033
<p>In C++, it's not possible to initialize array members in the initialization list, thus member objects should have default constructors and they should be properly initialized in the constructor. Is there any (reasonable) workaround for this apart from not using arrays?</p> <p>[Anything that can be initialized using only the initialization list is in our application far preferable to using the constructor, as that data can be allocated and initialized by the compiler and linker, and every CPU clock cycle counts, even before <code>main</code>. However, it is not always possible to have a default constructor for every class, and besides, reinitializing the data again in the constructor rather defeats the purpose anyway.]</p> <p>E.g. I'd like to have something like this (but this one doesn't work):</p> <pre><code>class OtherClass { private: int data; public: OtherClass(int i) : data(i) {}; // No default constructor! }; class Foo { private: OtherClass inst[3]; // Array size fixed and known ahead of time. public: Foo(...) : inst[0](0), inst[1](1), inst[2](2) {}; }; </code></pre> <p>The only workaround I'm aware of is the non-array one:</p> <pre><code>class Foo { private: OtherClass inst0; OtherClass inst1; OtherClass inst2; OtherClass *inst[3]; public: Foo(...) : inst0(0), inst1(1), inst2(2) { inst[0]=&amp;inst0; inst[1]=&amp;inst1; inst[2]=&amp;inst2; }; }; </code></pre> <p><b>Edit</b>: It should be stressed that <code>OtherClass</code> has no default constructor, and that it is very desirable to have the linker be able to allocate any memory needed (one or more static instances of <code>Foo</code> will be created), using the heap is essentially <i>verboten</i>. I've updated the examples above to highlight the first point.</p>
[ { "answer_id": 120084, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 3, "selected": true, "text": " class Foo\n {\n private:\n char inst[3*sizeof(OtherClass)]; // Array size fixed. OtherClass has no default ctor.\n\n // use Inst to access, not inst\n OtherClass &Inst(int i) {return (OtherClass *)inst+i;}\n const OtherClass &Inst(int i) const {return (const OtherClass *)inst+i;}\n public:\n Foo(...)\n {\n new (Inst(0)) OtherClass(...);\n new (Inst(1)) OtherClass(...);\n new (Inst(2)) OtherClass(...);\n }\n ~Foo()\n {\n Inst(0)->~OtherClass();\n Inst(1)->~OtherClass();\n Inst(2)->~OtherClass();\n }\n };\n" }, { "answer_id": 120089, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 2, "selected": false, "text": "class A {\npublic:\n A ()\n : m_a() // All elements are value-initialized (which for int means zero'd)\n {\n }\n\nprivate:\n int m_a[3];\n};\n" }, { "answer_id": 120129, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "#include \"stdafx.h\"\n#include <algorithm>\n#include <cassert>\n\nclass C {\npublic: // for the sake of demonstration...\n typedef int t_is[4] ;\n t_is is;\n bool initialized;\n\n C() : initialized( false )\n {\n }\n\n C( int deflt )\n : initialized( sf_bInit( is, deflt ) )\n {}\n\n static bool sf_bInit( t_is& av_is, const int i ){\n std::fill( av_is, av_is + sizeof( av_is )/sizeof( av_is[0] ), i );\n return true;\n }\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\n C c(1), d;\n\n assert( c.is[0] == 1 );\n\n return 0;\n}\n" }, { "answer_id": 686574, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "class ProxyOtherClass : public OtherClass {\npublic: \n ProxyOtherClass() : OtherClass(0) {}\n};\n\nclass Foo {\nprivate:\n ProxyOtherClass inst[3]; // Array size fixed and known ahead of time.\npublic:\n Foo(...) {}\n};\n" }, { "answer_id": 1547362, "author": "foxthrot", "author_id": 187579, "author_profile": "https://Stackoverflow.com/users/187579", "pm_score": 0, "selected": false, "text": "class Foo {\nprivate:\n OtherClass *inst[3];\npublic:\n Foo(...) {\n inst[0]=new OtherClass(1);\n inst[1]=new OtherClass(2);\n inst[2]=new OtherClass(3);\n };\n\n ~Foo() {\n delete [] inst; \n }\n\n};\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20957/" ]
120,054
<p>I am selecting rows from a table, but some of the columns are a text type, but they always have numeric data in them. How can I format them as numbers?</p> <p>e.g. column quantity heading 'Quantity' format 999,999</p> <p>However, since the column in the table is text, the numeric formatting is ignored.</p>
[ { "answer_id": 120136, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 1, "selected": false, "text": "to_char(to_number(quantity), '999,999')\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4834/" ]
120,059
<p>I am releasing a database build to SQL Server 2000 via a batch file using isql. The batch file is used so multiple files are released consistently to different SQL Servers (development, test, live).</p> <p>The SQL Server uses ANSI code page 1252 (from sp_helpsort) but isql is an OEM client using code page 437. This means that all extended characters (with ASCII code > 128) are converted when the scripts are run, leading to inconsistent results when characters like “£” are included in the script. Differences are explained in this <a href="http://support.microsoft.com/?scid=kb;EN-US;153449" rel="nofollow noreferrer">Microsoft knowledgebase article</a>.</p> <p>Possible solutions are: -</p> <ul> <li>Save the script using Unicode and use osql.</li> <li>Turn off the AutoAnsiToOem setting using the SQL Server Client Network Utility (that writes a registry key).</li> </ul> <p>Both these options rely on various people doing things consistently. All have to select the same code page option when saving a file OR all people performing the builds have to have the same option set for AutoAnsiToOem.</p> <p>Is there a way to force the use of a code page either in the SQL script OR in the batch file that calls it, so that the build is always released consistently, regardless of how the file is saved or the various settings of whoever performs the release?</p>
[ { "answer_id": 120257, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 3, "selected": true, "text": "isql" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5096/" ]
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
[ { "answer_id": 120118, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 7, "selected": true, "text": "import urllib2\nopener = urllib2.build_opener()\nopener.addheaders = [('User-agent', 'Mozilla/5.0')]\ninfile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes')\npage = infile.read()\n" }, { "answer_id": 4795011, "author": "Finn Årup Nielsen", "author_id": 589165, "author_profile": "https://Stackoverflow.com/users/589165", "pm_score": 0, "selected": false, "text": "import urllib\ns = urllib.urlopen('http://en.wikipedia.org/w/index.php?action=raw&title=Albert_Einstein').read()\n" }, { "answer_id": 25927059, "author": "Aziz Alto", "author_id": 2839786, "author_profile": "https://Stackoverflow.com/users/2839786", "pm_score": 2, "selected": false, "text": "requests" }, { "answer_id": 33645006, "author": "skierpage", "author_id": 1162195, "author_profile": "https://Stackoverflow.com/users/1162195", "pm_score": 1, "selected": false, "text": "?printable=yes" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20999/" ]
120,065
<p>Assume that we have N erlang nodes, running same application. I want to share an mnesia table T1 with all N nodes, which I see no problem. However, I want to share another mnesia table T2 with pairs of nodes. I mean the contents of T2 will be identical and replicated to/with only sharing pair. In another words, I want N/2 different contents for T2 table. Is this possible with mnesia, not with renaming T2 for each distinct pair of nodes?</p>
[ { "answer_id": 120987, "author": "uwiger", "author_id": 6834, "author_profile": "https://Stackoverflow.com/users/6834", "pm_score": 3, "selected": false, "text": "mnesia_frag_hash" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21000/" ]
120,071
<p>I have a string of arbitrary length, and starting at position p0, I need to find the first occurrence of one of three 3-letter patterns.</p> <p>Assume the string contain only letters. I need to find the count of triplets starting at position p0 and jumping forward in triplets until the first occurrence of either 'aaa' or 'bbb' or 'ccc'.</p> <p>Is this even possible using just a regex?</p>
[ { "answer_id": 120094, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 4, "selected": false, "text": "$string=~/^ # from the start of the string\n (?:.{$p0}) # skip (don't capture) \"$p0\" occurrences of any character\n (?:...)*? # skip 3 characters at a time,\n # as few times as possible (non-greedy)\n (aaa|bbb|ccc) # capture aaa or bbb or ccc as $1\n /x;\n" }, { "answer_id": 120141, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": "pos $string = $start_from;\n$string =~ m/\\G # anchor to previous pos()\n ((?:...)*?) # capture everything up to the match\n (aaa|bbb|ccc)\n /xs or die \"No match\"\nmy $result = length($1) / 3;\n" }, { "answer_id": 122794, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 0, "selected": false, "text": "my @expected_triplets = qw<aaa bbb ccc>;\nmy $data_string \n = 'fjeidoaaaivtrxxcccfznaaauitbbbfzjasdjfncccftjtjqznnjgjaaajeitjgbbblafjan'\n ;\nmy $place = 0;\nmy @triplets = grep { length } split /(...)/, $data_string;\nmy %occurrence_for = map { $_, [] } @expected_triplets;\nforeach my $i ( 0..@triplets ) {\n my $triplet = $triplets[$i];\n push( @{$occurrence_for{$triplet}}, $i ) if exists $occurrence_for{$triplet};\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ]
120,083
<p>Is there a way to alter the precision of an existing decimal column in Microsoft SQL Server?</p>
[ { "answer_id": 120821, "author": "VanSkalen", "author_id": 7367, "author_profile": "https://Stackoverflow.com/users/7367", "pm_score": 9, "selected": true, "text": "ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)\n" }, { "answer_id": 22895155, "author": "bnieland", "author_id": 279393, "author_profile": "https://Stackoverflow.com/users/279393", "pm_score": 4, "selected": false, "text": "ALTER TABLE MyTable ADD NewColumnName DECIMAL(16, 2);\nGO\n\nUPDATE MyTable\nSET NewColumnName = OldColumnName;\nGO\n\nALTER TABLE CONTRACTS DROP COLUMN OldColumnName;\nGO\n\n\nEXEC sp_rename\n @objname = 'MyTable.NewColumnName',\n @newname = 'OldColumnName',\n @objtype = 'COLUMN'\nGO\n" }, { "answer_id": 41933919, "author": "H Shah", "author_id": 7489262, "author_profile": "https://Stackoverflow.com/users/7489262", "pm_score": 1, "selected": false, "text": "ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DATA_TYPE();\n" }, { "answer_id": 68805771, "author": "Nilucshan Siva", "author_id": 6459557, "author_profile": "https://Stackoverflow.com/users/6459557", "pm_score": 0, "selected": false, "text": "ALTER TABLE <TABLE_NAME> MODIFY <COLUMN_NAME> <DATA_TYPE>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12767/" ]
120,102
<p>My stored procedure is called as below from an SQL instegartion package within SQL Server 2005</p> <p>EXEC ? = Validation.PopulateFaultsFileDetails ? , 0</p> <p>Though i'm not sure what the ? means</p>
[ { "answer_id": 120231, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 2, "selected": true, "text": "dim result\nSQL = \"EXEC ? = Validation.PopulateFaultsFileDetails ? , 0\"\nSQL.execute(result, 99) // pass in 99 to the stored proc\ndebug.print result\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
120,114
<p>I am using following PHP code to connect to MS Access database:</p> <pre><code>$odb_conn = new COM("ADODB.Connection"); $connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". $db_path.";"; $odb_conn-&gt;open($connstr); </code></pre> <p>How can I retrieve database catalog/metadata from the mdb file?</p> <p><strong>FOUND THE SOLUTION</strong></p> <pre><code>$rs_meta = $odb_conn-&gt;OpenSchema(20, array(Null, Null, Null, "TABLE")); </code></pre>
[ { "answer_id": 120195, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 0, "selected": false, "text": "MSysObjects" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6561/" ]
120,116
<p>I have been tasked with implementing a PKI library in C# for a company project, and have been unable to find a good implementation of it. There appear to be multiple libraries, and many broken links pointing to MSDN libraries that have been removed. I've seen people using Crypt32.dll, people building their own libraries, people using P/Invoke to access system certificate stores, people extending the built-in libraries, examples that simply don't apply to C# (e.g. Java examples), and commercial libraries.</p> <p>My question is, which implementation/library is most recommended for simple encryption/decryption of data?</p> <p>As some background for what I plan to do with it, I simply need to encrypt messages using a private key (.pfx), and decrypt with public keys (.cer). Message signing and authentication isn't required at this level of the project, although it may be in future. I have seen reference to encryption lengths which make me uneasy. We need to be able to encrypt any length message (within reason, of course!). Is this something I need to worry about, and if so, is there a way to deal with it?</p> <p>I would prefer not to store public/private keys in the windows certificate manager if at all possible, but if it makes implementation significantly simpler, so be it.</p> <p>I realize PKI and encryption is a large and complex subject, but I'm hoping for a relatively simple library anyway... (one can hope, right?)</p> <p>Thanks!</p>
[ { "answer_id": 120230, "author": "Alan Mendelevich", "author_id": 19546, "author_profile": "https://Stackoverflow.com/users/19546", "pm_score": 0, "selected": false, "text": "RSACryptoServiceProvider rscp = new RSACryptoServiceProvider();\nrscp.FromXmlString(\"<RSAKeyValue><Modulus>key data gere</Modulus><Exponent></Exponent></RSAKeyValue>\");\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21002/" ]
120,158
<p>We have a discussion going on in my team at the moment, and I'd be interested in other views. Suppose we have a RESTful web service whose role is to annotate documents by applying a variety of analysis algorithms and services. The basic interaction in clear: we have a resource which is the document collection; the client POSTs a new document to the collection, gets back the URI of the new document, then can GET that <code>docURI</code> to get the document back or GET <code>{docURI}/metadata</code> to see the general metadata, <code>{docURI}/ne</code> for named entities, etc. The problem is that some of the analyses may take a long time to complete. Suppose the client GETs the metadata URI before the analysis is complete, because it wants to be able to show partial or incremental results in the UI. Repeating the GET in future may yield more results.</p> <p>Solutions we've discussed include:</p> <ul> <li>keeping the HTTP connection open until all analyses are done (which doesn't seem scalable) </li> <li>using <code>content-length</code> and <code>accept-range</code> headers to get incremental content (but we don't know in advance how long the final content will be) </li> <li>providing an Atom feed for each resource so the client subscribes to update events rather than simply GETting the resource (seems overly complicated and possibly resource hungry if there are many active documents) </li> <li>just having GET return whatever is available at the time (but it still leaves the problem of the client knowing when we're finally done) <em>[edited to remove reference to idempotency following comments]</em>.</li> </ul> <p>Any opinions, or suggestions for alternative ways to handle long-lived or asynchronous interactions in a RESTful architecture?</p> <p>Ian</p>
[ { "answer_id": 120337, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 2, "selected": false, "text": "GET {docURI}/metadata" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6716/" ]
120,170
<p>I'm doing some testing on Firefox toolbars for the sake of learning and I can't find out any information on how to store the contents of a "search" drop-down inside the user's profile.</p> <p>Is there any tutorial on how to sort this out?</p>
[ { "answer_id": 121358, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 2, "selected": true, "text": "<textbox id=\"search_with_history\" />\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
120,180
<p>I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it!</p> <p>I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated!</p> <p>To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc.</p>
[ { "answer_id": 121456, "author": "Mat Mannion", "author_id": 6282, "author_profile": "https://Stackoverflow.com/users/6282", "pm_score": 6, "selected": true, "text": "import java.io.IOException;\nimport java.io.Reader;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.lucene.analysis.Analyzer;\nimport org.apache.lucene.analysis.ISOLatin1AccentFilter;\nimport org.apache.lucene.analysis.LowerCaseFilter;\nimport org.apache.lucene.analysis.StopFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter;\nimport org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side;\nimport org.apache.lucene.analysis.standard.StandardFilter;\nimport org.apache.lucene.analysis.standard.StandardTokenizer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.index.IndexReader;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.index.Term;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.Sort;\nimport org.apache.lucene.search.TermQuery;\nimport org.apache.lucene.search.TopDocs;\nimport org.apache.lucene.search.spell.LuceneDictionary;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\n\n/**\n * Search term auto-completer, works for single terms (so use on the last term\n * of the query).\n * <p>\n * Returns more popular terms first.\n * \n * @author Mat Mannion, M.Mannion@warwick.ac.uk\n */\npublic final class Autocompleter {\n\n private static final String GRAMMED_WORDS_FIELD = \"words\";\n\n private static final String SOURCE_WORD_FIELD = \"sourceWord\";\n\n private static final String COUNT_FIELD = \"count\";\n\n private static final String[] ENGLISH_STOP_WORDS = {\n \"a\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"but\", \"by\",\n \"for\", \"i\", \"if\", \"in\", \"into\", \"is\",\n \"no\", \"not\", \"of\", \"on\", \"or\", \"s\", \"such\",\n \"t\", \"that\", \"the\", \"their\", \"then\", \"there\", \"these\",\n \"they\", \"this\", \"to\", \"was\", \"will\", \"with\"\n };\n\n private final Directory autoCompleteDirectory;\n\n private IndexReader autoCompleteReader;\n\n private IndexSearcher autoCompleteSearcher;\n\n public Autocompleter(String autoCompleteDir) throws IOException {\n this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir,\n null);\n\n reOpenReader();\n }\n\n public List<String> suggestTermsFor(String term) throws IOException {\n // get the top 5 terms for query\n Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term));\n Sort sort = new Sort(COUNT_FIELD, true);\n\n TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort);\n List<String> suggestions = new ArrayList<String>();\n for (ScoreDoc doc : docs.scoreDocs) {\n suggestions.add(autoCompleteReader.document(doc.doc).get(\n SOURCE_WORD_FIELD));\n }\n\n return suggestions;\n }\n\n @SuppressWarnings(\"unchecked\")\n public void reIndex(Directory sourceDirectory, String fieldToAutocomplete)\n throws CorruptIndexException, IOException {\n // build a dictionary (from the spell package)\n IndexReader sourceReader = IndexReader.open(sourceDirectory);\n\n LuceneDictionary dict = new LuceneDictionary(sourceReader,\n fieldToAutocomplete);\n\n // code from\n // org.apache.lucene.search.spell.SpellChecker.indexDictionary(\n // Dictionary)\n IndexReader.unlock(autoCompleteDirectory);\n\n // use a custom analyzer so we can do EdgeNGramFiltering\n IndexWriter writer = new IndexWriter(autoCompleteDirectory,\n new Analyzer() {\n public TokenStream tokenStream(String fieldName,\n Reader reader) {\n TokenStream result = new StandardTokenizer(reader);\n\n result = new StandardFilter(result);\n result = new LowerCaseFilter(result);\n result = new ISOLatin1AccentFilter(result);\n result = new StopFilter(result,\n ENGLISH_STOP_WORDS);\n result = new EdgeNGramTokenFilter(\n result, Side.FRONT,1, 20);\n\n return result;\n }\n }, true);\n\n writer.setMergeFactor(300);\n writer.setMaxBufferedDocs(150);\n\n // go through every word, storing the original word (incl. n-grams) \n // and the number of times it occurs\n Map<String, Integer> wordsMap = new HashMap<String, Integer>();\n\n Iterator<String> iter = (Iterator<String>) dict.getWordsIterator();\n while (iter.hasNext()) {\n String word = iter.next();\n\n int len = word.length();\n if (len < 3) {\n continue; // too short we bail but \"too long\" is fine...\n }\n\n if (wordsMap.containsKey(word)) {\n throw new IllegalStateException(\n \"This should never happen in Lucene 2.3.2\");\n // wordsMap.put(word, wordsMap.get(word) + 1);\n } else {\n // use the number of documents this word appears in\n wordsMap.put(word, sourceReader.docFreq(new Term(\n fieldToAutocomplete, word)));\n }\n }\n\n for (String word : wordsMap.keySet()) {\n // ok index the word\n Document doc = new Document();\n doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES,\n Field.Index.UN_TOKENIZED)); // orig term\n doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES,\n Field.Index.TOKENIZED)); // grammed\n doc.add(new Field(COUNT_FIELD,\n Integer.toString(wordsMap.get(word)), Field.Store.NO,\n Field.Index.UN_TOKENIZED)); // count\n\n writer.addDocument(doc);\n }\n\n sourceReader.close();\n\n // close writer\n writer.optimize();\n writer.close();\n\n // re-open our reader\n reOpenReader();\n }\n\n private void reOpenReader() throws CorruptIndexException, IOException {\n if (autoCompleteReader == null) {\n autoCompleteReader = IndexReader.open(autoCompleteDirectory);\n } else {\n autoCompleteReader.reopen();\n }\n\n autoCompleteSearcher = new IndexSearcher(autoCompleteReader);\n }\n\n public static void main(String[] args) throws Exception {\n Autocompleter autocomplete = new Autocompleter(\"/index/autocomplete\");\n\n // run this to re-index from the current index, shouldn't need to do\n // this very often\n // autocomplete.reIndex(FSDirectory.getDirectory(\"/index/live\", null),\n // \"content\");\n\n String term = \"steve\";\n\n System.out.println(autocomplete.suggestTermsFor(term));\n // prints [steve, steven, stevens, stevenson, stevenage]\n }\n\n}\n" }, { "answer_id": 9183416, "author": "ThisIsTheDave", "author_id": 70578, "author_profile": "https://Stackoverflow.com/users/70578", "pm_score": 5, "selected": false, "text": "<input id=\"search-input\" name=\"query\" placeholder=\"Search database.\" type=\"text\" />\n" }, { "answer_id": 11435645, "author": "megawatts", "author_id": 1037199, "author_profile": "https://Stackoverflow.com/users/1037199", "pm_score": 2, "selected": false, "text": "using System.IO;\nusing System.Collections;\nusing Lucene.Net.Analysis;\nusing Lucene.Net.Analysis.Tokenattributes;\nusing Lucene.Net.Util;\n\nnamespace Lucene.Net.Analysis.NGram\n{\n\n/**\n * Tokenizes the given token into n-grams of given size(s).\n * <p>\n * This {@link TokenFilter} create n-grams from the beginning edge or ending edge of a input token.\n * </p>\n */\npublic class EdgeNGramTokenFilter : TokenFilter\n{\n public static Side DEFAULT_SIDE = Side.FRONT;\n public static int DEFAULT_MAX_GRAM_SIZE = 1;\n public static int DEFAULT_MIN_GRAM_SIZE = 1;\n\n // Replace this with an enum when the Java 1.5 upgrade is made, the impl will be simplified\n /** Specifies which side of the input the n-gram should be generated from */\n public class Side\n {\n private string label;\n\n /** Get the n-gram from the front of the input */\n public static Side FRONT = new Side(\"front\");\n\n /** Get the n-gram from the end of the input */\n public static Side BACK = new Side(\"back\");\n\n // Private ctor\n private Side(string label) { this.label = label; }\n\n public string getLabel() { return label; }\n\n // Get the appropriate Side from a string\n public static Side getSide(string sideName)\n {\n if (FRONT.getLabel().Equals(sideName))\n {\n return FRONT;\n }\n else if (BACK.getLabel().Equals(sideName))\n {\n return BACK;\n }\n return null;\n }\n }\n\n private int minGram;\n private int maxGram;\n private Side side;\n private char[] curTermBuffer;\n private int curTermLength;\n private int curGramSize;\n private int tokStart;\n\n private TermAttribute termAtt;\n private OffsetAttribute offsetAtt;\n\n protected EdgeNGramTokenFilter(TokenStream input) : base(input)\n {\n this.termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute));\n this.offsetAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute));\n }\n\n /**\n * Creates EdgeNGramTokenFilter that can generate n-grams in the sizes of the given range\n *\n * @param input {@link TokenStream} holding the input to be tokenized\n * @param side the {@link Side} from which to chop off an n-gram\n * @param minGram the smallest n-gram to generate\n * @param maxGram the largest n-gram to generate\n */\n public EdgeNGramTokenFilter(TokenStream input, Side side, int minGram, int maxGram)\n : base(input)\n {\n\n if (side == null)\n {\n throw new System.ArgumentException(\"sideLabel must be either front or back\");\n }\n\n if (minGram < 1)\n {\n throw new System.ArgumentException(\"minGram must be greater than zero\");\n }\n\n if (minGram > maxGram)\n {\n throw new System.ArgumentException(\"minGram must not be greater than maxGram\");\n }\n\n this.minGram = minGram;\n this.maxGram = maxGram;\n this.side = side;\n this.termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute));\n this.offsetAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute));\n }\n\n /**\n * Creates EdgeNGramTokenFilter that can generate n-grams in the sizes of the given range\n *\n * @param input {@link TokenStream} holding the input to be tokenized\n * @param sideLabel the name of the {@link Side} from which to chop off an n-gram\n * @param minGram the smallest n-gram to generate\n * @param maxGram the largest n-gram to generate\n */\n public EdgeNGramTokenFilter(TokenStream input, string sideLabel, int minGram, int maxGram)\n : this(input, Side.getSide(sideLabel), minGram, maxGram)\n {\n\n }\n\n public override bool IncrementToken()\n {\n while (true)\n {\n if (curTermBuffer == null)\n {\n if (!input.IncrementToken())\n {\n return false;\n }\n else\n {\n curTermBuffer = (char[])termAtt.TermBuffer().Clone();\n curTermLength = termAtt.TermLength();\n curGramSize = minGram;\n tokStart = offsetAtt.StartOffset();\n }\n }\n if (curGramSize <= maxGram)\n {\n if (!(curGramSize > curTermLength // if the remaining input is too short, we can't generate any n-grams\n || curGramSize > maxGram))\n { // if we have hit the end of our n-gram size range, quit\n // grab gramSize chars from front or back\n int start = side == Side.FRONT ? 0 : curTermLength - curGramSize;\n int end = start + curGramSize;\n ClearAttributes();\n offsetAtt.SetOffset(tokStart + start, tokStart + end);\n termAtt.SetTermBuffer(curTermBuffer, start, curGramSize);\n curGramSize++;\n return true;\n }\n }\n curTermBuffer = null;\n }\n }\n\n public override Token Next(Token reusableToken)\n {\n return base.Next(reusableToken);\n }\n public override Token Next()\n {\n return base.Next();\n }\n public override void Reset()\n {\n base.Reset();\n curTermBuffer = null;\n }\n}\n}\n" }, { "answer_id": 20209880, "author": "user2098849", "author_id": 2098849, "author_profile": "https://Stackoverflow.com/users/2098849", "pm_score": 3, "selected": false, "text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;\nimport org.apache.lucene.index.DirectoryReader;\nimport org.apache.lucene.index.IndexWriterConfig;\nimport org.apache.lucene.index.IndexWriterConfig.OpenMode;\nimport org.apache.lucene.search.spell.Dictionary;\nimport org.apache.lucene.search.spell.LuceneDictionary;\nimport org.apache.lucene.search.spell.PlainTextDictionary;\nimport org.apache.lucene.search.spell.SpellChecker;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.store.IOContext;\nimport org.apache.lucene.store.RAMDirectory;\nimport org.apache.lucene.util.Version;\nimport org.wltea4pinyin.analyzer.lucene.IKAnalyzer4PinYin;\n\n\n/**\n * \n * \n * @author <a href=\"mailto:liu.gang@renren-inc.com\"></a>\n * @version 2013-11-25上午11:13:59\n */\npublic class LuceneSpellCheckerDemoService {\n\nprivate static final String INDEX_FILE = \"/Users/r/Documents/jar/luke/youtui/index\";\nprivate static final String INDEX_FILE_SPELL = \"/Users/r/Documents/jar/luke/spell\";\n\nprivate static final String INDEX_FIELD = \"app_name_quanpin\";\n\npublic static void main(String args[]) {\n\n try {\n //\n PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new IKAnalyzer4PinYin(\n true));\n\n // read index conf\n IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_42, wrapper);\n conf.setOpenMode(OpenMode.CREATE_OR_APPEND);\n\n // read dictionary\n Directory directory = FSDirectory.open(new File(INDEX_FILE));\n RAMDirectory ramDir = new RAMDirectory(directory, IOContext.READ);\n DirectoryReader indexReader = DirectoryReader.open(ramDir);\n\n Dictionary dic = new LuceneDictionary(indexReader, INDEX_FIELD);\n\n\n SpellChecker sc = new SpellChecker(FSDirectory.open(new File(INDEX_FILE_SPELL)));\n //sc.indexDictionary(new PlainTextDictionary(new File(\"myfile.txt\")), conf, false);\n sc.indexDictionary(dic, conf, true);\n String[] strs = sc.suggestSimilar(\"zhsiwusdazhanjiangshi\", 10);\n for (int i = 0; i < strs.length; i++) {\n System.out.println(strs[i]);\n }\n sc.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n}\n\n\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6282/" ]
120,189
<p>As a temporary quick fix to mitigate the major risk while working on the permanent fix for XSS Vulnerability in a very large code base, I'm looking for a pre-existing XSS prevention blacklist that does a reasonable job of protecting against XSS.</p> <p>Preferably a set of Regular Expressions. I'm aware of plenty of cheat sheets for testing and smoke tests etc, what I'm looking for is pre-tuned regexps for blocking the attacks.</p> <p>I am fully aware that the best way is <a href="https://stackoverflow.com/questions/71328/what-are-the-best-practices-for-avoid-xss-attacks-in-a-php-site#71444">output escaping</a> or if you need some markup from users to use whitelisting. But, with the size of the code base, we need something in quick to reduce the immediate footprint of the vulnerability and raise the bar whilst working on the real solution.</p> <p>Is anyone aware of a good set?</p>
[ { "answer_id": 121262, "author": "tduehr", "author_id": 20486, "author_profile": "https://Stackoverflow.com/users/20486", "pm_score": 1, "selected": false, "text": "&lt;" }, { "answer_id": 122066, "author": "Chris Kite", "author_id": 9573, "author_profile": "https://Stackoverflow.com/users/9573", "pm_score": 2, "selected": false, "text": "purify()" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7106/" ]
120,191
<p>So you've created a ruby library.</p> <p>How do you create and publish your rubygem? And what common pitfalls and gotchas are there pertaining to creating and publishing rubygems?</p>
[ { "answer_id": 122913, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 4, "selected": true, "text": "bones <my_project_name>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
120,201
<p>I want to upload and then process a file in a Ruby on Rails app. The file upload is usually quite short, but the server-side processing can take some time (more than 20 seconds) so I want to give the user some indicator - something better than a meaningless 'processing...' screen.</p> <p>I'm trying to use the following code in the view</p> <pre><code>&lt;%= periodically_call_remote(:url =&gt; {:action =&gt; 'progress_monitor', :controller =&gt; 'files'}, :frequency =&gt; '5', :update =&gt; "setProgress('progressBar','5')" ) %&gt; </code></pre> <p>The content of the :update parameter is the javascript I want to run every 5 seconds</p> <p>and the following code is in the files controller</p> <pre><code>def progress_monitor render :text =&gt; 'whatever' end </code></pre> <p>Eventually the progress_monitor method will return the current progress as an integer (% complete) and that will be passed into the 'setProgress' JavaScript code (that will update an on screen element)</p> <p>However, I'm struggling to get a correct response from from the server that can then be passed into JavaScript.</p> <p>Can anyone help, or am I approaching this the wrong way?</p> <p>There is a follow up question to this, I originally updated this question but the update was sufficiently different to warrant a new question, <a href="https://stackoverflow.com/questions/126011/monitoring-a-server-side-process-on-rails-application-using-ajax-xmlhttprequest">here</a>.</p>
[ { "answer_id": 120317, "author": "liangzan", "author_id": 11927, "author_profile": "https://Stackoverflow.com/users/11927", "pm_score": 3, "selected": true, "text": "periodically_call_remote()" }, { "answer_id": 121201, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 0, "selected": false, "text": ":update" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6106/" ]
120,206
<p>The problem is not about randomness itself (we have rand), but in cryptographically secure PRNG. What can be used on Linux, or ideally POSIX? Does NSS have something useful?</p> <p><strong>Clarification</strong>: I know about /dev/random, but it may run out of entropy pool. And I'm not sure whether /dev/urandom is guaranteed to be cryptographically secure.</p>
[ { "answer_id": 120209, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "/dev/random" }, { "answer_id": 120223, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": true, "text": "/dev/random" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
120,212
<p>I am using VMware Server 1.0.7 on Windows XP SP3 at the moment to test software in virtual machines.</p> <p>I have also tried Microsoft Virtual PC (do not remeber the version, could be 2004 or 2007) and VMware was way faster at the time.</p> <p>I have heard of Parallels and VirtualBox but I did not have the time to try them out. Anybody has some benchmarks how fast is each of them (or some other)?</p> <p>I searched for benchmarks on the web, but found nothing useful.</p> <p>I am looking primarily for free software, but if it is really better than free ones I would pay for it.</p> <p>Also, if you are using (or know of) a good virtualization software but have no benchmarks for it, please let me know.</p>
[ { "answer_id": 120209, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "/dev/random" }, { "answer_id": 120223, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": true, "text": "/dev/random" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17469/" ]
120,226
<p>I have just installed Windows Server 2003 Standard Edition and therefore IIS6 (comes as standard). I have also install the windows component that enable the administration of IIS from the browser (<a href="https://server:8098/" rel="nofollow noreferrer">https://server:8098/</a>). The problem I have is that I have to log-in to this tool but the Server Administrator u/name and p/word does not let me in.</p> <p>The Windows documentation on this tool (<a href="http://support.microsoft.com/kb/324282" rel="nofollow noreferrer">http://support.microsoft.com/kb/324282</a>) says "You are prompted for a user name and password that exist on the Web Server" but none of the standard user acounts on the server let me in.</p> <p>Thanks,</p>
[ { "answer_id": 648790, "author": "Shalom Craimer", "author_id": 54491, "author_profile": "https://Stackoverflow.com/users/54491", "pm_score": 0, "selected": false, "text": "gpedit.msc" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
120,228
<p>I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend?</p> <p>What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not.</p> <p>This is just a quick example of what I was thinking about:</p> <pre><code>if ($alreadyDone == 0 &amp;&amp; time() &gt; $timeToRunMaintainance) { runTask(); $timeToRunMaintainance = time() + $interval; } </code></pre> <p>Anything else I should take into consideration or is there a better method than this?</p>
[ { "answer_id": 120236, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": false, "text": "man crontab" }, { "answer_id": 120258, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 3, "selected": false, "text": "#!/usr/bin/php\n<?php\n\n$h = @file_get_contents($_SERVER['argv'][1]);\n\nif ($h === false)\n{\n $h = \"<b>Failed to open file</b>: \" . $_SERVER['argv'][1];\n}\n\nif ($h != '')\n{\n @mail(\"cron@mydomain.com\", $_SERVER['argv']['1'], $h, \"From: cron@mydomain.com\\nMIME-Version: 1.0\\nContent-type: text/html; charset=iso-8859-1\");\n}\n\n?>\n" }, { "answer_id": 122168, "author": "David McLaughlin", "author_id": 3404, "author_profile": "https://Stackoverflow.com/users/3404", "pm_score": 4, "selected": false, "text": "/usr/bin/php /path/to/your/php/script.php\n" }, { "answer_id": 371486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "wget" }, { "answer_id": 15157355, "author": "Tim Visée", "author_id": 1000145, "author_profile": "https://Stackoverflow.com/users/1000145", "pm_score": 1, "selected": false, "text": "if(rand (1, 100) <= 1) { // 1, 100 is used to generate a number between 1 and 100. 1 is for one percent.\n // Run the tasks system\n}\n" }, { "answer_id": 30456312, "author": "mokiSRB", "author_id": 3676352, "author_profile": "https://Stackoverflow.com/users/3676352", "pm_score": 2, "selected": false, "text": "/usr/local/bin/php -q /home/yoursite/public_html/yourfile.php\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15214/" ]
120,240
<p>I am trying to optimize some stored procedures on a SQL Server 2000 database and when I try to use SQL Profiler I get an error message "In order to run a trace against SQL Server you have to be a member of sysadmin fixed server role.". It seems that only members of the sysadmin role can run traces on the server (something that was fixed in SQL Server 2005) and there is no way in hell that I will be granted that server role (company policies)</p> <p>What I'm doing now is inserting the current time minus the time the procedure started at various stages of the code but I find this very tedious </p> <p>I was also thinking of replicating the database to a local installation of SQL Server but the stored procedure is using data from many different databases that i will spend a lot of time copying data locally</p> <p>So I was wondering if there is some other way of profiling SQL code? (Third party tools, different practices, something else )</p>
[ { "answer_id": 120236, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": false, "text": "man crontab" }, { "answer_id": 120258, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 3, "selected": false, "text": "#!/usr/bin/php\n<?php\n\n$h = @file_get_contents($_SERVER['argv'][1]);\n\nif ($h === false)\n{\n $h = \"<b>Failed to open file</b>: \" . $_SERVER['argv'][1];\n}\n\nif ($h != '')\n{\n @mail(\"cron@mydomain.com\", $_SERVER['argv']['1'], $h, \"From: cron@mydomain.com\\nMIME-Version: 1.0\\nContent-type: text/html; charset=iso-8859-1\");\n}\n\n?>\n" }, { "answer_id": 122168, "author": "David McLaughlin", "author_id": 3404, "author_profile": "https://Stackoverflow.com/users/3404", "pm_score": 4, "selected": false, "text": "/usr/bin/php /path/to/your/php/script.php\n" }, { "answer_id": 371486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "wget" }, { "answer_id": 15157355, "author": "Tim Visée", "author_id": 1000145, "author_profile": "https://Stackoverflow.com/users/1000145", "pm_score": 1, "selected": false, "text": "if(rand (1, 100) <= 1) { // 1, 100 is used to generate a number between 1 and 100. 1 is for one percent.\n // Run the tasks system\n}\n" }, { "answer_id": 30456312, "author": "mokiSRB", "author_id": 3676352, "author_profile": "https://Stackoverflow.com/users/3676352", "pm_score": 2, "selected": false, "text": "/usr/local/bin/php -q /home/yoursite/public_html/yourfile.php\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11471/" ]
120,244
<p>I'm trying to put together a selector in SASS that will operate on the visted, hovered state of a link, but I can't quite seem to get the markup right, can someone enlighten me? I was writing it like this:</p> <pre><code> &amp;:visited:hover attribute: foo </code></pre>
[ { "answer_id": 120515, "author": "user6325", "author_id": 6325, "author_profile": "https://Stackoverflow.com/users/6325", "pm_score": 1, "selected": false, "text": "a\n &:visited:hover\n :attribute foo\n" }, { "answer_id": 6929064, "author": "crispy", "author_id": 231529, "author_profile": "https://Stackoverflow.com/users/231529", "pm_score": 4, "selected": true, "text": "a\n &:visited:hover\n attribute: foo\n" }, { "answer_id": 36032951, "author": "Sebastian", "author_id": 3923134, "author_profile": "https://Stackoverflow.com/users/3923134", "pm_score": 0, "selected": false, "text": "&:hover {\n color:#FFFFFF;\n\n &::before {\n color:#FFFFFF;\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2977/" ]
120,250
<p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p> <p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
[ { "answer_id": 120256, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": false, "text": "from array import array\na = array(\"h\") # h = signed short, H = unsigned short\n" }, { "answer_id": 120449, "author": "Arnav", "author_id": 21029, "author_profile": "https://Stackoverflow.com/users/21029", "pm_score": 3, "selected": false, "text": ">>> from struct import *\n>>> pack('hhl', 1, 2, 3)\n'\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03'\n>>> unpack('hhl', '\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03')\n(1, 2, 3)\n>>> calcsize('hhl')\n8\n" }, { "answer_id": 59604315, "author": "user12658139", "author_id": 12658139, "author_profile": "https://Stackoverflow.com/users/12658139", "pm_score": 1, "selected": false, "text": ">>> a = 2**1024\n>>> sys.getsizeof(a)\n164\n>>> 1024/164\n6.2439024390243905\n\n>>> a = 2**(2**20)\n>>> sys.getsizeof(a)\n139836\n>>> 2**20 / 139836\n7.49861266054521\n" }, { "answer_id": 59618360, "author": "user12658139", "author_id": 12658139, "author_profile": "https://Stackoverflow.com/users/12658139", "pm_score": 1, "selected": false, "text": ">>> import sys\n>>> a = bytearray(2**32)\n>>> sys.getsizeof(a)\n4294967353\n>>> 8 * 2**32 / 4294967353\n7.999999893829228\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21029/" ]
120,262
<p>Say for instance I was writing a function that was designed to accept multiple argument types:</p> <pre><code>var overloaded = function (arg) { if (is_dom_element(arg)) { // Code for DOM Element argument... } }; </code></pre> <p>What's the best way to implement <strong><code>is_dom_element</code></strong> so that it works in a cross-browser, fairly accurate way?</p>
[ { "answer_id": 120275, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "node instanceof HTMLElement\n" }, { "answer_id": 120280, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": true, "text": "var overloaded = function (arg) {\n if (arg.nodeType) {\n // Code for DOM Element argument...\n }\n};\n" }, { "answer_id": 120424, "author": "Wolfram Kriesing", "author_id": 21050, "author_profile": "https://Stackoverflow.com/users/21050", "pm_score": 0, "selected": false, "text": "obj instanceof HTMLElement\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
120,266
<p>In my database, I have a model which has a field which should be selected from one of a list of options. As an example, consider a model which needs to store a measurement, such as 5ft or 13cm or 12.24m3. The obvious way to achieve this is to have a decimal field and then some other field to store the unit of measurement. </p> <p>So what is the best way to store the unit of measurement? I've used a couple of approaches in the past:</p> <p>1) Storing the various options in another DB table (and associated model), and linking the two with a standard foreign key (and usually eager loading the associated model). This seems like overkill, as you are forcing the DB to perform a join on every query.</p> <p>2) Storing the options as a constant Hash, loaded in one of the initializers, where the key into the Hash is stored in the unit of measurement field. This way, you effectively do the join in Ruby (which may or may not be a performance increase), but you lose the ability to query from the "unit of measurement" side. This wouldn't be a problem provided it's unlikely you'd need to do queries like "find me all measurements with units of cm".</p> <p>Neither of these feel particularly elegant to me.. can anyone suggest something better?</p>
[ { "answer_id": 120318, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "name" }, { "answer_id": 120524, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 3, "selected": false, "text": "create_table :account_statuses do |t|\n t.string :name, :description\nend\n\nAccountStatus.create!(:name => 'Active', :description => 'Active user account')\nAccountStatus.create!(:name => 'Pending', :description => 'Pending user account')\nAccountStatus.create!(:name => 'Disabled', :description => 'Disabled user account')\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
120,283
<p>I am wanting to find the distance between two different points. This I know can be accomplished with the great circle distance. <a href="http://www.meridianworlddata.com/Distance-calculation.asp" rel="noreferrer">http://www.meridianworlddata.com/Distance-calculation.asp</a></p> <p>Once done, with a point and distance I would like to find the point that distance north, and that distance east in order to create a box around the point.</p>
[ { "answer_id": 123305, "author": "Sean", "author_id": 5446, "author_profile": "https://Stackoverflow.com/users/5446", "pm_score": 7, "selected": false, "text": "public static double distFrom(double lat1, double lng1, double lat2, double lng2) {\n double earthRadius = 3958.75; // miles (or 6371.0 kilometers)\n double dLat = Math.toRadians(lat2-lat1);\n double dLng = Math.toRadians(lng2-lng1);\n double sindLat = Math.sin(dLat / 2);\n double sindLng = Math.sin(dLng / 2);\n double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)\n * Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n double dist = earthRadius * c;\n\n return dist;\n }\n" }, { "answer_id": 8468985, "author": "Oscar Salguero", "author_id": 701472, "author_profile": "https://Stackoverflow.com/users/701472", "pm_score": 1, "selected": false, "text": "import org.gavaghan.geodesy.*;\n...\nGeodeticCalculator geoCalc = new GeodeticCalculator();\nEllipsoid reference = Ellipsoid.WGS84;\nGlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0);\nGlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0);\ndouble distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance();\n" }, { "answer_id": 9822531, "author": "Victor P.", "author_id": 939274, "author_profile": "https://Stackoverflow.com/users/939274", "pm_score": 4, "selected": false, "text": "/**\n * Calculates geodetic distance between two points specified by latitude/longitude using Vincenty inverse formula\n * for ellipsoids\n * \n * @param lat1\n * first point latitude in decimal degrees\n * @param lon1\n * first point longitude in decimal degrees\n * @param lat2\n * second point latitude in decimal degrees\n * @param lon2\n * second point longitude in decimal degrees\n * @returns distance in meters between points with 5.10<sup>-4</sup> precision\n * @see <a href=\"http://www.movable-type.co.uk/scripts/latlong-vincenty.html\">Originally posted here</a>\n */\npublic static double distVincenty(double lat1, double lon1, double lat2, double lon2) {\n double a = 6378137, b = 6356752.314245, f = 1 / 298.257223563; // WGS-84 ellipsoid params\n double L = Math.toRadians(lon2 - lon1);\n double U1 = Math.atan((1 - f) * Math.tan(Math.toRadians(lat1)));\n double U2 = Math.atan((1 - f) * Math.tan(Math.toRadians(lat2)));\n double sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);\n double sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);\n\n double sinLambda, cosLambda, sinSigma, cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM;\n double lambda = L, lambdaP, iterLimit = 100;\n do {\n sinLambda = Math.sin(lambda);\n cosLambda = Math.cos(lambda);\n sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda)\n + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));\n if (sinSigma == 0)\n return 0; // co-incident points\n cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;\n sigma = Math.atan2(sinSigma, cosSigma);\n sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;\n cosSqAlpha = 1 - sinAlpha * sinAlpha;\n cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;\n if (Double.isNaN(cos2SigmaM))\n cos2SigmaM = 0; // equatorial line: cosSqAlpha=0 (§6)\n double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));\n lambdaP = lambda;\n lambda = L + (1 - C) * f * sinAlpha\n * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));\n } while (Math.abs(lambda - lambdaP) > 1e-12 && --iterLimit > 0);\n\n if (iterLimit == 0)\n return Double.NaN; // formula failed to converge\n\n double uSq = cosSqAlpha * (a * a - b * b) / (b * b);\n double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));\n double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));\n double deltaSigma = B\n * sinSigma\n * (cos2SigmaM + B\n / 4\n * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM\n * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));\n double dist = b * A * (sigma - deltaSigma);\n\n return dist;\n}\n" }, { "answer_id": 12101310, "author": "Matthew Hager", "author_id": 1604395, "author_profile": "https://Stackoverflow.com/users/1604395", "pm_score": 3, "selected": false, "text": "public static double HaverSineDistance(double lat1, double lng1, double lat2, double lng2) \n{\n // mHager 08-12-2012\n // http://en.wikipedia.org/wiki/Haversine_formula\n // Implementation\n\n // convert to radians\n lat1 = Math.toRadians(lat1);\n lng1 = Math.toRadians(lng1);\n lat2 = Math.toRadians(lat2);\n lng2 = Math.toRadians(lng2);\n\n double dlon = lng2 - lng1;\n double dlat = lat2 - lat1;\n\n double a = Math.pow((Math.sin(dlat/2)),2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2),2);\n\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\n return EARTH_RADIUS * c;\n} \n" }, { "answer_id": 22913553, "author": "Rija Ramampiandra", "author_id": 1894680, "author_profile": "https://Stackoverflow.com/users/1894680", "pm_score": 2, "selected": false, "text": "public static Double distanceBetweenTwoLocationsInKm(Double latitudeOne, Double longitudeOne, Double latitudeTwo, Double longitudeTwo) {\n if (latitudeOne == null || latitudeTwo == null || longitudeOne == null || longitudeTwo == null) {\n return null;\n }\n\n Double earthRadius = 6371.0;\n Double diffBetweenLatitudeRadians = Math.toRadians(latitudeTwo - latitudeOne);\n Double diffBetweenLongitudeRadians = Math.toRadians(longitudeTwo - longitudeOne);\n Double latitudeOneInRadians = Math.toRadians(latitudeOne);\n Double latitudeTwoInRadians = Math.toRadians(latitudeTwo);\n Double a = Math.sin(diffBetweenLatitudeRadians / 2) * Math.sin(diffBetweenLatitudeRadians / 2) + Math.cos(latitudeOneInRadians) * Math.cos(latitudeTwoInRadians) * Math.sin(diffBetweenLongitudeRadians / 2)\n * Math.sin(diffBetweenLongitudeRadians / 2);\n Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n return (earthRadius * c);\n }\n" }, { "answer_id": 38552765, "author": "Ad Infinitum", "author_id": 6451425, "author_profile": "https://Stackoverflow.com/users/6451425", "pm_score": 1, "selected": false, "text": "private double getDist(double lat1, double lon1, double lat2, double lon2)\n{\n int R = 6373; // radius of the earth in kilometres\n double lat1rad = Math.toRadians(lat1);\n double lat2rad = Math.toRadians(lat2);\n double deltaLat = Math.toRadians(lat2-lat1);\n double deltaLon = Math.toRadians(lon2-lon1);\n\n double a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) +\n Math.cos(lat1rad) * Math.cos(lat2rad) *\n Math.sin(deltaLon/2) * Math.sin(deltaLon/2);\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\n double d = R * c;\n return d;\n}\n" }, { "answer_id": 53559309, "author": "makata", "author_id": 2408879, "author_profile": "https://Stackoverflow.com/users/2408879", "pm_score": 0, "selected": false, "text": " public static float getDistanceInMeter(LatLng start, LatLng end) { \n float[] results = new float[1];\n Location.distanceBetween(start.latitude, start.longitude, end.latitude, end.longitude, results);\n return results[0];\n\n}\n" }, { "answer_id": 57346001, "author": "Binakot", "author_id": 5788341, "author_profile": "https://Stackoverflow.com/users/5788341", "pm_score": 1, "selected": false, "text": "const val EARTH_RADIUS_IN_METERS = 6371007.177356707\n\nfun distance(lat1: Double, lng1: Double, lat2: Double, lng2: Double): Double {\n val latDiff = Math.toRadians(abs(lat2 - lat1))\n val lngDiff = Math.toRadians(abs(lng2 - lng1))\n val a = sin(latDiff / 2) * sin(latDiff / 2) +\n cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) *\n sin(lngDiff / 2) * sin(lngDiff / 2)\n val c = 2 * atan2(sqrt(a), sqrt(1 - a))\n return EARTH_RADIUS_IN_METERS * c\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633/" ]
120,295
<p>I'd like to find a good object oriented C++ (as opposed to C) wrapper for sqlite. What do people recommend? If you have several suggestions please put them in separate replies for voting purposes. Also, please indicate whether you have any experience of the wrapper you are suggesting and how you found it to use.</p>
[ { "answer_id": 387834, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "try\n{\n\n CppSQLite3DB db;\n\n db.open(asFileName.c_str());\n\n db.execDML(\"Update data set hrx = 0\");\n\n} // try\n\ncatch (...)\n{\n\n} // catch\n" }, { "answer_id": 3915108, "author": "edam", "author_id": 424221, "author_profile": "https://Stackoverflow.com/users/424221", "pm_score": 3, "selected": false, "text": "sqlite::connection db( filename );\n\nsqlite::command c( db, \"UPDATE foo SET bar = ? WHERE name = ?\" );\nc << 123 << name << sqlite::exec;\n\nsqlite::query q( db, \"SELECT foo FROM bar\" );\nfor( sqlite::query::iterator i = q.begin(); i != q.end(); i++ )\n std::cout << i->column< std::string >( 0 ) << \"\\n\";\n" }, { "answer_id": 6468760, "author": "markshiz", "author_id": 731285, "author_profile": "https://Stackoverflow.com/users/731285", "pm_score": 4, "selected": false, "text": "sqlite3pp::database db(\"test.db\");\nsqlite3pp::transaction xct(db);\n{\n sqlite3pp::command cmd(db, \"INSERT INTO contacts (name, phone) VALUES (:user, :phone)\");\n cmd.bind(\":user\", \"Mike\");\n cmd.bind(\":phone\", \"555-1234\");\n cmd.execute();\n}\nxct.rollback();\n" }, { "answer_id": 15904817, "author": "burner", "author_id": 2261889, "author_profile": "https://Stackoverflow.com/users/2261889", "pm_score": 3, "selected": false, "text": "class Person {\npublic:\n Person() {}\n static SqlTable<Person>& table() {\n static SqlTable<Person> tab = SqlTable<Person>::sqlTable(\"Person\",\n SqlColumn<Person>(\"Firstname\", makeAttr(&Person::firstname)),\n SqlColumn<Person>(\"Lastname\", makeAttr(&Person::lastname)),\n SqlColumn<Person>(\"Age\", makeAttr(&Person::age)),\n return tab;\n }\n std::string firstname;\n std::string lastname;\n int age;\n};\n\nSqliteDB db(\"testtable.db\");\nauto sel(db.select<Person>(\"Firstname=\\\"Danny\\\" and Lastname=\\\"Zeckzer\\\"\"));\nstd::for_each(sel.first, sel.second, [](const Person& p) {\n...\nPerson me;\ndb.insert<Person>(me);\n...\nstd::vector<Person> everybody;\ndb.insert<Person>(everybody.begin(), everybody.end());\n" }, { "answer_id": 18816490, "author": "Tomas Andrle", "author_id": 35440, "author_profile": "https://Stackoverflow.com/users/35440", "pm_score": 2, "selected": false, "text": "#include \"NLDatabase.h\"\n\n\nusing namespace std;\nusing namespace NL::DB;\n\n\nint main(int argc, const char * argv[]) {\n\n Database db( \"test.sqlite\" );\n\n auto results = db.query(\"SELECT * FROM test WHERE name <> ?\").select(\"TOM\");\n\n for ( auto const & row : results ) {\n cout << \"column[0]=\" << row.column_string( 0 ) << endl;\n }\n}\n" }, { "answer_id": 23663635, "author": "amin", "author_id": 1575632, "author_profile": "https://Stackoverflow.com/users/1575632", "pm_score": 4, "selected": false, "text": "database db(\"dbfile.db\");\n// executes the query and creates a 'user' table if not exists\ndb << \"create table if not exists user (\"\n \" age int,\"\n \" name text,\"\n \" weight real\"\n \");\";\n// inserts a new user and binds the values to '?' marks\ndb << \"insert into user (age,name,weight) values (?,?,?);\"\n << 20\n << \"bob\"\n << 83.0;\n// slects from table user on a condition ( age > 18 ) and executes \n// the lambda for every row returned .\ndb << \"select age,name,weight from user where age > ? ;\"\n << 18\n >> [&](int age, string name, double weight) {\n cout << age << ' ' << name << ' ' << weight << endl;\n };\n// selects the count(*) of table user\nint count = 0;\ndb << \"select count(*) from user\" >> count;\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17493/" ]
120,296
<p>This is obviously a stupid question. I am coding in Eclipse both on Mac and Linux, but I mixed up and used the Mac shortcut to window tabbing (<kbd>Ctrl</kbd>-<kbd>Cmd</kbd>-<kbd>F6</kbd>), but I was using the Linux on uni and screen went black. I've done this before, but this time I can't get back to my desktop. <kbd>Ctrl</kbd>-<kbd>Alt</kbd> <kbd>F1</kbd>-<kbd>F6</kbd> gives me different terminals, <kbd>F7</kbd> gives me a black screen and <kbd>F8</kbd> a blinking underscore in the top left corner. Shouldn't my session have been somewhere in <kbd>F1</kbd>-<kbd>F6</kbd> and is it lost? </p>
[ { "answer_id": 122827, "author": "duffbeer703", "author_id": 21292, "author_profile": "https://Stackoverflow.com/users/21292", "pm_score": 2, "selected": false, "text": "init 3\n" }, { "answer_id": 61402330, "author": "Alex_Gofman", "author_id": 7560180, "author_profile": "https://Stackoverflow.com/users/7560180", "pm_score": 3, "selected": false, "text": "alt + F1\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6371/" ]
120,315
<p>Once I've created a variable in the immediate window in C# (VS2008), is there any way to delete it so I can create a new variable with the same name but a different type? Apart from restarting the program that is.</p> <p>The reason would be to keep the immediate window's namespace clean, since it's difficult to keep track of variable declarations once they scroll off the visible part of the window.</p>
[ { "answer_id": 788476, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public void LolFunction() {\n {\n int main = 0;\n Console.Writeline(main);\n }\n {\n string main = \"Roflstring\";\n Console.Writeline(main);\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161040/" ]
120,334
<p>I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution. The following does not work on my windows development machine (although I'd think that this should be at least a possible solution):</p> <pre><code>$array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich'); $oldLocal=setlocale(LC_COLLATE, "0"); var_dump(setlocale(LC_COLLATE, 'German_Germany.65001')); usort($array, 'strcoll'); var_dump(setlocale(LC_COLLATE, $oldLocal)); var_dump($array); </code></pre> <p>The output is:</p> <pre><code>string(20) "German_Germany.65001" string(1) "C" array(6) { [0]=&gt; string(6) "Birnen" [1]=&gt; string(9) "Ungetiere" [2]=&gt; string(6) "Äpfel" [3]=&gt; string(5) "Apfel" [4]=&gt; string(9) "Ungetüme" [5]=&gt; string(11) "Österreich" } </code></pre> <p>This is complete nonsense. Using 1252 as the codepage for <code>setlocale()</code> gives another output but still a plainly wrong one:</p> <pre><code>string(19) "German_Germany.1252" string(1) "C" array(6) { [0]=&gt; string(11) "Österreich" [1]=&gt; string(6) "Äpfel" [2]=&gt; string(5) "Apfel" [3]=&gt; string(6) "Birnen" [4]=&gt; string(9) "Ungetüme" [5]=&gt; string(9) "Ungetiere" } </code></pre> <p>Is there a way to sort an array with UTF-8 strings locale aware?</p> <p><em>Just noted that this seems to be PHP on Windows problem, as the same snippet with <code>de_DE.utf8</code> used as locale works on a Linux machine. Nevertheless a solution for this Windows-specific problem would be nice...</em></p>
[ { "answer_id": 120388, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 0, "selected": false, "text": "$array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich');\n$oldLocal=setlocale(LC_COLLATE, \"0\");\nvar_dump(setlocale(LC_COLLATE, 'German_Germany.1252'));\nusort($array, 'strcoll');\nvar_dump(setlocale(LC_COLLATE, $oldLocal));\nvar_dump($array);\n" }, { "answer_id": 121445, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": -1, "selected": false, "text": "de_DE.utf8" }, { "answer_id": 125879, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 4, "selected": true, "text": "function traceStrColl($a, $b) {\n $outValue=strcoll($a, $b);\n echo \"$a $b $outValue\\r\\n\";\n return $outValue;\n}\n\n$locale=(defined('PHP_OS') && stristr(PHP_OS, 'win')) ? 'German_Germany.65001' : 'de_DE.utf8';\n\n$string=\"ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜabcdefghijklmnopqrstuvwxyzäöüß\";\n$array=array();\nfor ($i=0; $i<mb_strlen($string, 'UTF-8'); $i++) {\n $array[]=mb_substr($string, $i, 1, 'UTF-8');\n}\n$oldLocale=setlocale(LC_COLLATE, \"0\");\nvar_dump(setlocale(LC_COLLATE, $locale));\nusort($array, 'traceStrColl');\nsetlocale(LC_COLLATE, $oldLocale);\nvar_dump($array);\n" }, { "answer_id": 349036, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 3, "selected": false, "text": "strcoll()" }, { "answer_id": 9576230, "author": "Delian Krustev", "author_id": 1227975, "author_profile": "https://Stackoverflow.com/users/1227975", "pm_score": 5, "selected": false, "text": "$a = array( 'Кръстев', 'Делян1', 'делян1', 'Делян2', 'делян3', 'кръстев' );\n$col = new \\Collator('bg_BG');\n$col->asort( $a );\nvar_dump( $a );\n" }, { "answer_id": 32779390, "author": "leymannx", "author_id": 2199525, "author_profile": "https://Stackoverflow.com/users/2199525", "pm_score": 1, "selected": false, "text": "function _all_letters_to_ASCII($string) {\n return strtr(utf8_decode($string), \n utf8_decode('ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'),\n 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');\n}\n" }, { "answer_id": 39974761, "author": "Friedrich Siever", "author_id": 6997445, "author_profile": "https://Stackoverflow.com/users/6997445", "pm_score": 0, "selected": false, "text": "$laender =array(\"Österreich\", \"Schweiz\", \"England\", \"France\", \"Ägypten\"); \n$laender = array_map(\"utf8_decode\", $laender); \nsetlocale(LC_ALL,\"de_DE@euro\", \"de_DE\", \"deu_deu\"); \nsort($laender, SORT_LOCALE_STRING); \n$laender = array_map(\"utf8_encode\", $laender); \nprint_r($laender);\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11354/" ]
120,380
<p>Is there anyway in Java to delete data (e.g., a variable value, object) and be sure it can't be recovered from memory? Does assigning <code>null</code> to a variable in Java delete the value from memory? Any ideas? Answers applicable to other languages are also acceptable.</p>
[ { "answer_id": 121798, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "String" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15474/" ]
120,395
<p>I'm looking for non-web-based tools to view IIS logs. I've been using <a href="http://www.microsoft.com/technet/scriptcenter/tools/logparser/default.mspx" rel="nofollow noreferrer">LogParser</a> but I was hoping for something with an interface. It doesn't need to do any fancy reports or charts -- just a list with some search filters is plenty. I need something lightweight that I can run directly on the web server, preferably without a complex install process.</p>
[ { "answer_id": 120464, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 1, "selected": false, "text": "findstr \"404\" logfilename > out.txt\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4925/" ]
120,420
<p>I would like to have information about the icons which are displayed alongside the site URLs on a web browser. Is this some browser specific feature? Where do we specify the icon source, ie, is it in some tag on the web page itself ?</p>
[ { "answer_id": 120428, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "<head profile=\"http://www.w3.org/2005/10/profile\">\n<link rel=\"icon\" \n type=\"image/png\" \n href=\"/somewhere/myicon.png\" />\n[…]\n</head>\n" }, { "answer_id": 120445, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 4, "selected": false, "text": "<head>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11614/" ]
120,422
<p>How do I iterate over a set of records in RPG(LE) with embedded SQL?</p>
[ { "answer_id": 120993, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 5, "selected": true, "text": " //***********************************************************************\n // Main - Main Processing Routine\n begsr Main;\n\n exsr BldSqlStmt;\n\n if OpenSqlCursor() = SQL_SUCCESS;\n\n dow FetchNextRow() = SQL_SUCCESS;\n exsr ProcessRow;\n enddo;\n\n if sqlStt = SQL_NO_MORE_ROWS;\n CloseSqlCursor();\n endif;\n\n endif;\n\n CloseSqlCursor();\n\n endsr; // Main \n" }, { "answer_id": 1247484, "author": "James R. Perkins", "author_id": 152794, "author_profile": "https://Stackoverflow.com/users/152794", "pm_score": 3, "selected": false, "text": " EXEC SQL \n OPEN order_history; \n\n // Set the length \n len = %elem(results); \n\n // Loop through all the results \n dow (SqlState = Sql_Success); \n EXEC SQL \n FETCH FROM order_history FOR :len ROWS INTO :results; \n if (SQLER3 <> *zeros); \n for i = 1 to SQLER3 by 1; \n // Load the output \n eval-corr output = results(i); \n // Do something \n endfor; \n endif; \n enddo; \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
120,438
<p>What's the difference between "Layers" and "Tiers"?</p>
[ { "answer_id": 20674120, "author": "TryinHard", "author_id": 2776146, "author_profile": "https://Stackoverflow.com/users/2776146", "pm_score": 4, "selected": false, "text": "Tier" }, { "answer_id": 35970802, "author": "Yash", "author_id": 5081877, "author_profile": "https://Stackoverflow.com/users/5081877", "pm_score": 4, "selected": false, "text": "related-functional[code]" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ]
120,467
<p>I would like to confirm that the following analysis is correct:</p> <p>I am building a web app in RoR. I have a data structure for my postgres db designed (around 70 tables; this design may need changes and additions during development to reflect Rails ways of doing things. EG, I designed some user and role tables - but if it makes sense to use Restful Authentication, I will scrub them and replace with whatever RA requires. ).</p> <p>I have a shellscript which calls a series of .sql files to populate the empty database with tables and initial data (eg, Towns gets pre-filled with post towns) as well as test data (eg, Companies gets a few dummy companies so I have data to play with). </p> <p>for example:</p> <pre><code>CREATE TABLE towns ( id integer PRIMARY KEY DEFAULT nextval ('towns_seq'), county_id integer REFERENCES counties ON DELETE RESTRICT ON UPDATE CASCADE, country_id integer REFERENCES countries ON DELETE RESTRICT ON UPDATE CASCADE NOT NULL, name text NOT NULL UNIQUE ); </code></pre> <p>Proposition 0: Data lasts longer than apps, so I am convinced that I want referential integrity enforced at the DB level as well as validations in my RoR models, despite the lack of DRYNESS.</p> <p>Proposition 1: If I replace the script and sql files with Migrations, it is currently impossible to tell my Postgres database about the Foreign Key and other constraints I currently set in SQL DDL files within the migration code. </p> <p>Proposition 2: The touted benefit of migrations is that changes to the schema are versioned along with the RoR model code. But if I keep my scripts and .sql files in railsapp/db, I can version them just as easily.</p> <p>Proposition 3: Given that migrations lack functionality I want, and provide benefits I can replicate, there is little reason for me to consider using them. So I should --skipmigrations at script/generate model time. </p> <p>My question: If Proposition 0 is accepted, are Propositions 1,2,3 true or false, and why?</p> <p>Thanks!</p>
[ { "answer_id": 120494, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 4, "selected": true, "text": "def self.up\n create_table :users do |t|\n t.column :department_id, :integer, :references => :departments\n end\nend\n" }, { "answer_id": 599259, "author": "Mike Berrow", "author_id": 17251, "author_profile": "https://Stackoverflow.com/users/17251", "pm_score": 0, "selected": false, "text": "module ActiveRecord\n module ConnectionAdapters # :nodoc:\n module SchemaStatements\n # Example call:\n # add_fk_constraint 'orders','advertiser_id','advertisers','id'\n # \"If you want add/alter a 'orders' record, then its 'advertiser_id' had\n # better point to an existing 'advertisers' record with corresponsding 'id'\"\n def add_fk_constraint(table_name, referencing_col, referenced_table, referenced_col)\n fk_name = \"#{table_name}_#{referencing_col}\"\n sql = <<-ENDSQL\n ALTER TABLE #{table_name}\n ADD CONSTRAINT #{fk_name}\n FOREIGN KEY (#{referencing_col}) REFERENCES #{referenced_table} (#{referenced_col})\n ON UPDATE NO ACTION ON DELETE CASCADE; \n CREATE INDEX fki_#{fk_name} ON #{table_name}(#{referencing_col});\n ENDSQL\n execute sql\n end\n end\n end\nend\n\nclass AdvertisersOrders < ActiveRecord::Migration\n def self.up\n create_table :advertisers do |t|\n t.column :name, :string, :null => false\n t.column :net_id, :integer, :null => false\n t.column :source_service_id, :integer, :null => false, :default => 1\n t.column :source_id, :integer, :null => false \n end\n\n create_table :orders do |t|\n t.column :name, :string, :null => false\n t.column :advertiser_id, :integer, :null => false\n t.column :source_id, :integer, :null => false\n end\n add_fk_constraint 'orders','advertiser_id','advertisers','id'\n end\n\n def self.down\n drop_table :orders\n drop_table :advertisers\n end\nend\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6941/" ]
120,470
<p>I'm using nhibernate to store some user settings for an app in a SQL Server Compact Edition table.</p> <p>This is an excerpt the mapping file:</p> <pre><code>&lt;property name="Name" type="string" /&gt; &lt;property name="Value" type="string" /&gt; </code></pre> <p>Name is a regular string/nvarchar(50), and Value is set as ntext in the DB</p> <p>I'm trying to write a large amount of xml to the "Value" property. I get an exception every time:</p> <pre><code>@p1 : String truncation: max=4000, len=35287, value='&lt;lots of xml..../&gt;' </code></pre> <p>I've googled it quite a bit, and tried a number of different mapping configurations:</p> <pre><code>&lt;property name="Name" type="string" /&gt; &lt;property name="Value" type="string" &gt; &lt;column name="Value" sql-type="StringClob" /&gt; &lt;/property&gt; </code></pre> <p>That's one example. Other configurations include "ntext" instead of "StringClob". Those configurations that don't throw mapping exceptions still throw the string truncation exception.</p> <p>Is this a problem ("feature") with SQL CE? Is it possible to put more than 4000 characters into a SQL CE database with nhibernate? If so, can anyone tell me how?</p> <p>Many thanks!</p>
[ { "answer_id": 120560, "author": "Jimmeh", "author_id": 20749, "author_profile": "https://Stackoverflow.com/users/20749", "pm_score": 0, "selected": false, "text": "<property name=\"Value\" type=\"string\" />\n <column name=\"Value\" sql-type=\"StringClob\" />\n</property>\n" }, { "answer_id": 120745, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 0, "selected": false, "text": "<property name=\"Value\" type=\"string\" length=\"4001\" />" }, { "answer_id": 120899, "author": "Reiste", "author_id": 21033, "author_profile": "https://Stackoverflow.com/users/21033", "pm_score": 0, "selected": false, "text": "<property name=\"Value\" type=\"string\" length=\"4001\" />\n" }, { "answer_id": 132250, "author": "Reiste", "author_id": 21033, "author_profile": "https://Stackoverflow.com/users/21033", "pm_score": 4, "selected": true, "text": "using System.Data;\nusing System.Data.SqlServerCe;\nusing NHibernate.Driver;\nusing NHibernate.SqlTypes;\n\nnamespace MySqlServerCeDriverNamespace\n{\n /// <summary>\n /// Overridden Nhibernate SQL CE Driver,\n /// so that ntext fields are not truncated at 4000 characters\n /// </summary>\n public class MySqlServerCeDriver : SqlServerCeDriver\n {\n protected override void InitializeParameter(\n IDbDataParameter dbParam,\n string name,\n SqlType sqlType)\n {\n base.InitializeParameter(dbParam, name, sqlType);\n\n if (sqlType is StringClobSqlType)\n {\n var parameter = (SqlCeParameter)dbParam;\n parameter.SqlDbType = SqlDbType.NText;\n }\n\n }\n }\n}\n" }, { "answer_id": 214311, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 0, "selected": false, "text": "<property name='Value' type='StringClob' />\n" }, { "answer_id": 724703, "author": "Kim Johansson", "author_id": 88000, "author_profile": "https://Stackoverflow.com/users/88000", "pm_score": 0, "selected": false, "text": "<session-factory>\n ...\n <property name=\"connection.release_mode\">on_close</property>\n</session-factory>\n" }, { "answer_id": 7270955, "author": "wal", "author_id": 224410, "author_profile": "https://Stackoverflow.com/users/224410", "pm_score": 0, "selected": false, "text": "protected override void InitializeParameter(IDbDataParameter dbParam,string name,SqlType sqlType)\n {\n base.InitializeParameter(dbParam, name, sqlType);\n\n var stringType = sqlType as StringSqlType;\n if (stringType != null && stringType.LengthDefined && stringType.Length > 4000)\n {\n var parameter = (SqlCeParameter)dbParam;\n parameter.SqlDbType = SqlDbType.NText;\n }\n\n }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21033/" ]
120,497
<p>I've noticed that Internet Explorer adds a number in square brackets to files downloaded from the internet (usually [1]). This creates a big problem with downloading Excel spreadsheets as square brackets are not a valid filename character inside Excel worksheet name. That problem is IE specific, others browsers are keeping same file name.</p> <p>So, if you have a pivot table auto-refreshed on file opening for example, you'll get an error message saying the name "file[1].yourPivotTableName" is not valid.</p> <p>Is there any solution to that problem ?</p> <p>EDIT : It seems that whatever the <strong>filename suggested by HTTP directives</strong>, IE adds [1] in all cases, which cause the problem ! (So, answers about filenames aren't helpful in that case)</p> <p>EDIT : I've tried some VBA code to save file under another name when it'll open. However, it doesn't work (same error message than before). Do you think there's a way to fix that with VBA ?</p>
[ { "answer_id": 120569, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 0, "selected": false, "text": "Response.AppendHeader(\"content-disposition\", \"attachment;filename=file.xls\");\nResponse.ContentType = \"application/vnd.ms-excel\";\n" }, { "answer_id": 120581, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": -1, "selected": false, "text": " Response.AddHeader(\"Content-Disposition\", \"attachment; filename=excel.xls\");\n Response.AddHeader(\"Content-Type\", \"application/vnd.ms-excel\");\n Response.ContentType = \"application/vnd.ms-excel\";\n" }, { "answer_id": 304571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private string EncodeFileName(string fileName)\n {\n fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace(\"+\", \" \");\n if (HttpContext.Current.Request.UserAgent.ToLower().Contains(\"msie\"))\n {\n var res = new StringBuilder();\n var chArr = fileName.ToCharArray();\n for (var j = 0; j < chArr.Length; j++)\n {\n if (chArr[j] == '.' && j != fileName.LastIndexOf(\".\"))\n res.Append(\"%2E\");\n else\n res.Append(chArr[j]);\n }\n fileName = res.ToString();\n }\n return \"\\\"\" + fileName + \"\\\"\";\n }\n" }, { "answer_id": 2730168, "author": "Arvind Kumar", "author_id": 327936, "author_profile": "https://Stackoverflow.com/users/327936", "pm_score": 0, "selected": false, "text": "response.reset();\nresponse.setHeader(\"Expires\", \"0\");\nresponse.setHeader(\"Cache-Control\",\"must-revalidate,post-check=0, pre-check=0\");\nresponse.setHeader(\"Pragma\", \"public\");\n" }, { "answer_id": 26251490, "author": "AnirbanDebnath", "author_id": 4120181, "author_profile": "https://Stackoverflow.com/users/4120181", "pm_score": 1, "selected": false, "text": "public static String encoding(String fileName, String extension, HttpServletRequest request)\n{\n String user = request.getHeader( \"user-agent\" );\n boolean isInternetExplorer = ( user.indexOf( \"MSIE\" ) > -1 );\n String var = \"\";\n try\n { \n fileName = URLEncoder.encode( fileName, \"UTF-8\" );\n fileName = fileName.trim().replaceAll( \"\\\\+\", \" \" );\n extension = URLEncoder.encode( extension, \"UTF-8\" );\n extension = extension.trim().replaceAll( \"\\\\+\", \" \" );\n if ( isInternetExplorer )\n {\n disposition = \"attachment; filename=\\\"\" + fileName+\".\"+extension+\"\\\"\";\n }\n else\n {\n var = \"attachment; filename*=UTF-8''\" + fileName+\".\"+extension;\n } \n }\n catch ( UnsupportedEncodingException ence )\n {\n var = \"attachment; filename=\\\"\" + fileName+\".\"+extension;\n ence.printStackTrace();\n }\n\n return var;\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ]
120,503
<p>I'm trying to populate a TDBGrid with the results of the following TQuery against the file Journal.db:</p> <pre><code>select * from Journal where Journal.where = "RainPump" </code></pre> <p>I've tried both <code>Journal."Where"</code> and <code>Journal.[Where]</code> to no avail.</p> <p>I've also tried: <code>select Journal.[Where] as "Location"</code> with the same result.</p> <p>Journal.db is a file created by a third party and I am unable to change the field names.</p> <p>The problem is that the field I'm interested in is called 'where' and understandably causes the above error. How do I reference this field without causing the BDE (presumably) to explode?</p>
[ { "answer_id": 120518, "author": "Johan Bresler", "author_id": 3535708, "author_profile": "https://Stackoverflow.com/users/3535708", "pm_score": 0, "selected": false, "text": "select * from Journal where Journal.\"where\" = \"RainPump\"\n" }, { "answer_id": 120519, "author": "Branko", "author_id": 5362, "author_profile": "https://Stackoverflow.com/users/5362", "pm_score": 2, "selected": false, "text": "select * from Journal where Journal.[where] = \"RainPump\"\n" }, { "answer_id": 120756, "author": "Johan Bresler", "author_id": 3535708, "author_profile": "https://Stackoverflow.com/users/3535708", "pm_score": 3, "selected": true, "text": "Query1.sql.clear;\nquery1,sql.add('Insert into newtable values (select * from Journal);');\nquery1.sql.add('Select * from newtable where newcolumn = \"Rainpump\";');\nquery1.open;\n" }, { "answer_id": 398201, "author": "A. I. Breveleri", "author_id": 45506, "author_profile": "https://Stackoverflow.com/users/45506", "pm_score": 2, "selected": false, "text": "select * from Journal where Journal.\"Where\" = \"RainPump\"\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11781/" ]
120,504
<p>I'm trying to run the following SQL statement in Oracle, and it takes ages to run:</p> <pre><code>SELECT orderID FROM tasks WHERE orderID NOT IN (SELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL AND engineer2 IS NOT NULL) </code></pre> <p>If I run just the sub-part that is in the IN clause, that runs very quickly in Oracle, i.e.</p> <pre><code>SELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL AND engineer2 IS NOT NULL </code></pre> <p>Why does the whole statement take such a long time in Oracle? In SQL Server the whole statement runs quickly.</p> <p>Alternatively is there a simpler/different/better SQL statement I should use?</p> <p>Some more details about the problem:</p> <ul> <li>Each order is made of many tasks</li> <li>Each order will be allocated (one or more of its task will have engineer1 and engineer2 set) or the order can be unallocated (all its task have null values for the engineer fields)</li> <li>I am trying to find all the orderIDs that are unallocated.</li> </ul> <p>Just in case it makes any difference, there are ~120k rows in the table, and 3 tasks per order, so ~40k different orders.</p> <p>Responses to answers:</p> <ul> <li>I would prefer a SQL statement that works in both SQL Server and Oracle.</li> <li>The tasks only has an index on the orderID and taskID.</li> <li>I tried the NOT EXISTS version of the statement but it ran for over 3 minutes before I cancelled it. Perhaps need a JOIN version of the statement?</li> <li>There is an "orders" table as well with the orderID column. But I was trying to simplify the question by not including it in the original SQL statement.</li> </ul> <p>I guess that in the original SQL statement the sub-query is run every time for each row in the first part of the SQL statement - even though it is static and should only need to be run once?</p> <p>Executing</p> <pre><code>ANALYZE TABLE tasks COMPUTE STATISTICS; </code></pre> <p>made my original SQL statement execute much faster. </p> <p>Although I'm still curious why I have to do this, and if/when I would need to run it again?</p> <blockquote> <p>The statistics give Oracle's cost-based optimzer information that it needs to determine the efficiency of different execution plans: for example, the number of rowsin a table, the average width of rows, highest and lowest values per column, number of distinct values per column, clustering factor of indexes etc.</p> <p>In a small database you can just setup a job to gather statistics every night and leave it alone. In fact, this is the default under 10g. For larger implementations you usually have to weigh the stability of the execution plans against the way that the data changes, which is a tricky balance.</p> <p>Oracle also has a feature called "dynamic sampling" that is used to sample tables to determine relevant statistics at execution time. It's much more often used with data warehouses where the overhead of the sampling it outweighed by the potential performance increase for a long-running query.</p> </blockquote>
[ { "answer_id": 120516, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "SELECT orderID FROM tasks WHERE orderID NOT EXISTS \n (SELECT DISTINCT orderID FROM tasks WHERE\n engineer1 IS NOT NULL AND engineer2 IS NOT NULL)`print(\"code sample\");`\n" }, { "answer_id": 120531, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "SELECT orderID FROM tasks\nWHERE engineer1 IS NOT NULL OR engineer2 IS NOT NULL\n" }, { "answer_id": 120545, "author": "Mac", "author_id": 8696, "author_profile": "https://Stackoverflow.com/users/8696", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT orderID FROM tasks t1 WHERE NOT EXISTS (SELECT * FROM tasks t2 WHERE t2.orderID=t1.orderID AND (engineer1 IS NOT NULL OR engineer2 IS NOT NULL));\n" }, { "answer_id": 120558, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "SELECT orderID FROM tasks\nMINUS\nSELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL \nAND engineer2 IS NOT NULL\n" }, { "answer_id": 120597, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": -1, "selected": false, "text": "SELECT orderID\n FROM tasks\n GROUP BY orderID\n HAVING COUNT(engineer1) = 0 OR COUNT(engineer2) = 0\n" }, { "answer_id": 120602, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "select orderid from tasks\nminus\nselect orderid from tasks\nwhere engineer1 IS NOT NULL AND engineer2 IS NOT NULL\n" }, { "answer_id": 120780, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 2, "selected": false, "text": "SELECT \n t.orderID \nFROM \n tasks t\n LEFT JOIN tasks t1\n ON t.orderID = t1.orderID\n AND t1.engineer1 IS NOT NULL \n AND t1.engineer2 IS NOT NULL\nWHERE\n t1.orderID IS NULL \n" }, { "answer_id": 120790, "author": "Jim Birchall", "author_id": 989, "author_profile": "https://Stackoverflow.com/users/989", "pm_score": -1, "selected": false, "text": "SELECT DISTINCT orderID \nFROM tasks \nWHERE (engineer1 IS NULL OR engineer2 IS NULL)\n" }, { "answer_id": 120998, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": false, "text": "SELECT t1.orderID \nFROM tasks t1\nWHERE NOT EXISTS\n (SELECT 1 \n FROM tasks t2 \n WHERE t2.orderID = t1.orderID\n AND t2.engineer1 IS NOT NULL \n AND t2.engineer2 IS NOT NULL)\n" }, { "answer_id": 121161, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 4, "selected": true, "text": "ANALYZE TABLE tasks COMPUTE STATISTICS;\n" }, { "answer_id": 121183, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "select distinct orderid\nfrom\n(\nselect orderid,\n max(case when engineer1 is null and engineer2 is null then 0 else 1)\n over (partition by orderid)\n as max_null_finder\nfrom tasks\n)\nwhere max_null_finder = 0\n" }, { "answer_id": 121214, "author": "JoshL", "author_id": 20625, "author_profile": "https://Stackoverflow.com/users/20625", "pm_score": 0, "selected": false, "text": "SELECT orderID FROM tasks\nMINUS\nSELECT DISTINCT orderID FROM tasks WHERE\n engineer1 IS NOT NULL AND engineer2 IS NOT NULL\n" }, { "answer_id": 121538, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "SELECT orderID\nFROM tasks\nGROUP BY orderID\nHAVING COUNT(engineer1) = 0 AND COUNT(engineer2) = 0\n" }, { "answer_id": 195779, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT orderID FROM Tasks \nWHERE Engineer1 IS NULL OR Engineer2 IS NULL;\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261/" ]
120,561
<p>We have a vxWorks design which requires one task to process both high and low priority messages sent over two message queues.<br> The messages for a given priority have to be processed in FIFO order. </p> <p>For example, process all the high priority messages in the order they were received, then process the low priority messages. If there is no high priority message, then process the low priority message immediately.</p> <p>Is there a way to do this?</p>
[ { "answer_id": 120788, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 1, "selected": false, "text": "\nMSG_Q_ID lowQ, hiQ;\n\nvoid Init() {\n// Task Initialization Code. This should be called from the task that will\n// be receiving the messages\n...\nhiQ = msgQCreate(...);\nlowQ = msgQCreate(...);\nmsgQEvStart(hiQ, VX_EV01); // Event 1 sent when hiQ receives message\nmsgQEvStart(loQ, VX_EV02); // Event 2 sent when loQ receives message\n...\n}\nvoid RxMessages() {\n...\n UINT32 ev; // Event received\n\n // Blocks until we receive Event 1 or 2\n eventReceive(VX_EV01 | VX_EV02, EVENT_WAIT_ANY, WAIT_FOREVER, &ev);\n if(ev & VX_EV01) {\n msgQReceive(hiQ, ...);\n }\n if(ev & VX_EV02) {\n msgQReceive(loQ, ...);\n }\n}\n" }, { "answer_id": 142002, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 3, "selected": true, "text": " // Initialization: Create high and low priority named pipes\n pipeDrv(); //initialize pipe driver\n int fdHi = pipeDevCreate(\"/pipe/high\",numMsgs,msgSize);\n int fdLo = pipeDevCreate(\"/pipe/low\",numMsgs,msgSize);\n\n ...\n\n // Message sending thread: Add messages to pipe\n write(fdHi, buf, sizeof(buf));\n\n ...\n\n // Message processing Thread: select loop\n fd_set rdFdSet;\n\n while(1)\n {\n FD_ZERO(&rdFdSet);\n FD_SET(fdHi, &rdFdSet);\n FD_SET(fdLo, &rdFdSet;\n\n if (select(FD_SETSIZE, &rdFdSet, NULL, NULL, NULL) != ERROR)\n {\n if (FD_ISSET(fdHi, &rdFdSet))\n {\n // process all high-priority messages\n while(read(fdHi,buf,size) > 0)\n {\n //process high-priority\n }\n }\n\n if (FD_ISSET(fdLo, &rdFdSet))\n {\n // process a single low priority message\n if (read(fdLo,buf,size) > 0)\n {\n // process low priority\n }\n }\n }\n }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
120,578
<p>Take any social website like <a href="http://en.wikipedia.org/wiki/Digg" rel="nofollow noreferrer">Digg</a> or Stack&nbsp;Overflow that somehow lets users reward points for stories, questions, etc..</p> <p>What happens is quite similar to the process that lead to the rise of tabloid newspapers that feed only headlines and no content to its readers.</p> <p>Users are usually smart enough to figure out strategies to maximize their point rewards regardless of whether that strategy harmonized with the goal of the website or not.</p> <p>I identify the following problems</p> <ul> <li>People will swamp more general and more entertaining questions with answers. Answering more specific questions requires actual domain knowledge.</li> <li>Getting most points is often tied to involving most users. Given a random web crowd this unfortunately means mostly generic, subjective, argumentative and unspecific entries.</li> </ul> <p>As the creator of a social website you have the unique chance to influence social behavior towards a favorable direction. I think that the influence the system has on the behavior of the people far outweighs the initial seed of users.</p> <p>I'm interested in patterns/solutions that aim to solve this problem in terms of:</p> <ul> <li>ranking algorithms</li> <li>expert systems</li> <li>limiting/creating ways of social interaction</li> <li>information that is provided/hidden</li> </ul> <p>In particular, given the perspective of Stack&nbsp;Overflow, how could one solve entries like "<a href="https://stackoverflow.com/questions/84556/whats-your-favorite-programmer-cartoon">What's your favorite programmer cartoon</a>" become the most popular entries (I pick this one because it is a good example for the undesired phenomenon).</p>
[ { "answer_id": 158898, "author": "eaolson", "author_id": 23669, "author_profile": "https://Stackoverflow.com/users/23669", "pm_score": -1, "selected": false, "text": "OBSCURE_TASK" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19435/" ]
120,579
<p>What would be the best way to expose certain functionality in a Dotnet VSTO Excel add-in to VBA, without requiring the user to be a local administrator (i.e. no COM registration, <a href="http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic49734.aspx" rel="nofollow noreferrer">no HttpListener</a>)? Would it be possible to use Microsoft Message Queues from VBA?</p>
[ { "answer_id": 120925, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "Private m_objMyFactory As Object\n\nPublic Sub RegisterFactory(MyFactory As Object)\n\n On Error GoTo ErrHandler\n Set m_objMyFactory = MyFactory\n Exit Sub\nErrHandler:\n MsgBox \"An unexpected error occurred when registering the Factory component: \" & Err.Description\n Exit Sub\nEnd Sub\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6022/" ]
120,584
<p>In a <a href="http://www.pygame.org/" rel="nofollow noreferrer">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p> <p>How can I achieve this?</p> <p>(I like the <a href="http://ocemp.sourceforge.net/gui.html" rel="nofollow noreferrer">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
[ { "answer_id": 121653, "author": "Pierre-Jean Coudert", "author_id": 8450, "author_profile": "https://Stackoverflow.com/users/8450", "pm_score": 2, "selected": false, "text": "import cairo\nimport rsvg\n\nWIDTH, HEIGHT = 256, 256\nsurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)\n\nctx = cairo.Context (surface)\n\nsvg = rsvg.Handle(file=\"test.svg\")\nsvg.render_cairo(ctx)\n\nsurface.write_to_png(\"test.png\")\n" }, { "answer_id": 341742, "author": "Johan Dahlin", "author_id": 14337, "author_profile": "https://Stackoverflow.com/users/14337", "pm_score": 5, "selected": true, "text": "#!/usr/bin/python\n\nimport array\nimport math\n\nimport cairo\nimport pygame\nimport rsvg\n\nWIDTH = 512\nHEIGHT = 512\n\ndata = array.array('c', chr(0) * WIDTH * HEIGHT * 4)\nsurface = cairo.ImageSurface.create_for_data(\n data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)\n\npygame.init()\nwindow = pygame.display.set_mode((WIDTH, HEIGHT))\nsvg = rsvg.Handle(file=\"test.svg\")\nctx = cairo.Context(surface)\nsvg.render_cairo(ctx)\n\nscreen = pygame.display.get_surface()\nimage = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),\"ARGB\")\nscreen.blit(image, (0, 0)) \npygame.display.flip() \n\nclock = pygame.time.Clock()\nwhile True:\n clock.tick(15)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n raise SystemExit\n" }, { "answer_id": 4950448, "author": "Dave", "author_id": 610409, "author_profile": "https://Stackoverflow.com/users/610409", "pm_score": 1, "selected": false, "text": "import array,cairo, pygame,rsvg\n\ndef loadsvg(filename,surface,position):\n WIDTH = surface.get_width()\n HEIGHT = surface.get_height()\n data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)\n cairosurface = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)\n svg = rsvg.Handle(filename)\n svg.render_cairo(cairo.Context(cairosurface))\n image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),\"ARGB\")\n surface.blit(image, position) \n\nWIDTH = 800\nHEIGHT = 600\npygame.init()\nwindow = pygame.display.set_mode((WIDTH, HEIGHT))\nscreen = pygame.display.get_surface()\n\nloadsvg(\"test.svg\",screen,(0,0))\n\npygame.display.flip() \n\nclock = pygame.time.Clock()\nwhile True:\n clock.tick(15)\n event = pygame.event.get()\n for e in event:\n if e.type == 12:\n raise SystemExit\n" }, { "answer_id": 26188526, "author": "loopbackbee", "author_id": 1595865, "author_profile": "https://Stackoverflow.com/users/1595865", "pm_score": 0, "selected": false, "text": "def pygame_svg( svg_file, scale=1 ):\n svg = rsvg.Handle(file=svg_file)\n width, height= map(svg.get_property, (\"width\", \"height\"))\n width*=scale; height*=scale\n data = array.array('c', chr(0) * width * height * 4)\n surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, width, height, width*4)\n ctx = cairo.Context(surface)\n ctx.scale(scale, scale)\n svg.render_cairo(ctx)\n\n #seemingly, cairo and pygame expect channels in a different order...\n #if colors/alpha are funny, mess with the next lines\n import numpy\n data= numpy.fromstring(data, dtype='uint8')\n data.shape= (height, width, 4)\n c= data.copy()\n data[::,::,0]=c[::,::,1]\n data[::,::,1]=c[::,::,0]\n data[::,::,2]=c[::,::,3]\n data[::,::,3]=c[::,::,2]\n\n image = pygame.image.frombuffer(data.tostring(), (width, height),\"ARGB\")\n return image\n" }, { "answer_id": 51058233, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 4, "selected": false, "text": "librsvg" }, { "answer_id": 64598021, "author": "Rabbid76", "author_id": 5577765, "author_profile": "https://Stackoverflow.com/users/5577765", "pm_score": 4, "selected": false, "text": "pygame.Surface" }, { "answer_id": 74401182, "author": "MestreLion", "author_id": 624066, "author_profile": "https://Stackoverflow.com/users/624066", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python3\nimport sys\n\nimport cairo\nimport gi\nimport PIL.Image\nimport pygame\ngi.require_version('Rsvg', '2.0')\nfrom gi.repository import Rsvg\n\nWIDTH = 512\nHEIGHT = 512\nPATH = sys.argv[1] if len(sys.argv) > 1 else \"test.svg\"\n\n\ndef load_svg(path: str, size: tuple) -> pygame.Surface:\n \"\"\"Render an SVG file to a new pygame surface and return that surface.\"\"\"\n svg = Rsvg.Handle.new_from_file(path)\n\n # Create a Cairo surface.\n # Nominally ARGB, but in little-endian architectures it is effectively BGRA\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size)\n\n # Create a Cairo context and scale it\n context = cairo.Context(surface)\n context.scale(size[0]/svg.props.width, size[1]/svg.props.height)\n\n # Render the SVG\n svg.render_cairo(context)\n\n # Get image data buffer\n data = surface.get_data()\n if sys.byteorder == 'little':\n # Convert from effective BGRA to actual RGBA.\n # PIL is surprisingly faster than NumPy, but can be done without neither\n data = PIL.Image.frombuffer('RGBA', size, data.tobytes(),\n 'raw', 'BGRA', 0, 1).tobytes()\n\n return pygame.image.frombuffer(data, size, \"RGBA\").convert_alpha()\n\n\npygame.init()\nwindow = pygame.display.set_mode((WIDTH, HEIGHT))\nimage = load_svg(PATH, (WIDTH, HEIGHT))\nwindow.blit(image, (0, 0))\npygame.display.update()\n\nclock = pygame.time.Clock()\nwhile True:\n if pygame.event.get([pygame.QUIT]):\n break\n clock.tick(30)\npygame.quit()\n\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8450/" ]
120,587
<p>I would like to trash the mail received by a single qmail alias. I don't want any mail delivery errors, and I want qmail to be happy about having delivered the mail.</p> <p>How can I do this, preferably without adding another local email account?</p>
[ { "answer_id": 120771, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": 2, "selected": false, "text": "|cat >/dev/null\n" }, { "answer_id": 655324, "author": "drench", "author_id": 73779, "author_profile": "https://Stackoverflow.com/users/73779", "pm_score": 2, "selected": true, "text": "echo \"# drop all messages on the floor\" > ~alias/.qmail-devnull\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15992/" ]
120,588
<p>I'm using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objects from the database according to user-provided strings. For example, when searching for people, if the user is looking for people who live in 'fran', I want to be able to give her people in San Francisco.</p> <p>SQL is not my strong suit, and I prefer Hibernate's <code>Criteria</code> building code to hard-coded strings as it is. Can anyone point me in the right direction about how to do this in code, and if impossible, how the hard-coded SQL should look like?</p> <p>Thanks,</p> <p>Yuval =8-)</p>
[ { "answer_id": 120622, "author": "Richard", "author_id": 20038, "author_profile": "https://Stackoverflow.com/users/20038", "pm_score": 2, "selected": false, "text": "select f.name from f where TO_UPPER(f.name) like '%FRAN%'\n" }, { "answer_id": 120641, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 7, "selected": true, "text": "Criteria crit = session.createCriteria(Person.class);\ncrit.add(Restrictions.ilike('town', '%fran%');\nList results = crit.list();\n" }, { "answer_id": 121413, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": 2, "selected": false, "text": "START" }, { "answer_id": 227212, "author": "SamS", "author_id": 14068, "author_profile": "https://Stackoverflow.com/users/14068", "pm_score": 3, "selected": false, "text": "getHibernateTemplate().find(\"from User where upper(email)=?\", emailAddr.toUpperCase());\n" }, { "answer_id": 290156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "Criteria crit = session.createCriteria(Person.class);\ncrit.add(Restrictions.ilike('town', 'fran', MatchMode.ANYWHERE);\nList results = crit.list();\n" }, { "answer_id": 4089895, "author": "Casey", "author_id": 147373, "author_profile": "https://Stackoverflow.com/users/147373", "pm_score": 1, "selected": false, "text": "public List findLike(Object entity, MatchMode matchMode) {\n Example example = Example.create(entity);\n example.enableLike(matchMode);\n example.ignoreCase();\n return getSession().createCriteria(entity.getClass()).add(\n example).list();\n}\n" }, { "answer_id": 58017459, "author": "gawi", "author_id": 1127920, "author_profile": "https://Stackoverflow.com/users/1127920", "pm_score": 1, "selected": false, "text": "session.createCriteria" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2819/" ]
120,607
<p>I am trying to separate some asp logic out into a separate page. For now, I am trying to call a simple function. </p> <p>Here is the simple index page that I am using</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Calling a webservice from classic ASP&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;% If Request.ServerVariables("REQUEST_METHOD") = "POST" Then %&gt; &lt;!--#include file="aspFunctions.asp"--&gt; &lt;% doStuff() End If %&gt; &lt;FORM method=POST name="form1" ID="Form1"&gt; ID: &lt;INPUT type="text" name="corpId" ID="id" value="050893"&gt; &lt;BR&gt;&lt;BR&gt; &lt;INPUT type="submit" value="GO" name="submit1" ID="Submit1" &gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is aspfunctions.asp</p> <pre><code>sub doStuff() Response.Write("In Do Stuff") end sub </code></pre> <p>When i hit the submit button on my form i get the below sub doStuff() Response.Write("In Do Stuff") end sub</p> <p>Microsoft VBScript runtime error '800a000d'</p> <p>Does anyone have any idea what i could be doing wrong?</p> <p>Any help is greatly appreciated</p> <p>Thanks Damien Type mismatch: 'doStuff'</p> <p>/uat/damien/index.asp, line 15 </p>
[ { "answer_id": 120619, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 1, "selected": false, "text": "doStuff\n" }, { "answer_id": 120632, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": true, "text": "aspfunctions.asp" }, { "answer_id": 120855, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 3, "selected": false, "text": "<%\nIf 1=0 Then\n'We never get here\n%>\n <!--#include file=\"aspFunctions.asp\"-->\n<%\n dostuff()\nEnd If\ndostuff()\n%>\n" }, { "answer_id": 12139094, "author": "polin", "author_id": 1624049, "author_profile": "https://Stackoverflow.com/users/1624049", "pm_score": -1, "selected": false, "text": "sub doStuff()" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11612/" ]
120,618
<p>What logging solutions exist for j2me? </p> <p>I'm specifically interested in easily excluding logging for "release" version, to have a smaller package &amp; memory footprint. </p>
[ { "answer_id": 121077, "author": "JaanusSiim", "author_id": 706, "author_profile": "https://Stackoverflow.com/users/706", "pm_score": 5, "selected": true, "text": "public class Log {\n public static void debug(final String message) {\n //#if !release.build\n System.out.println(message);\n //#endif\n }\n}\n" }, { "answer_id": 166156, "author": "edsumner", "author_id": 24072, "author_profile": "https://Stackoverflow.com/users/24072", "pm_score": 3, "selected": false, "text": "-assumenosideeffects public class logger.Logger {*;}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6827/" ]
120,621
<p>Is Eclipse at all theme-able? I would like to install a dark color scheme for it, since I much prefer white text on dark background than the other way around.</p>
[ { "answer_id": 3587514, "author": "TEHEK", "author_id": 295253, "author_profile": "https://Stackoverflow.com/users/295253", "pm_score": 0, "selected": false, "text": "!!ARBfp1.0\nTEMP temp, neg;\n\n# Dunno what's this... but every other filter starts with this :) ;\nTEX temp, fragment.texcoord[0], texture[0], RECT;\n\n# Applying negative filter ;\nRCP neg.a, temp.a;\nMAD temp.rgb, -neg.a, temp, 1.0;\nMUL temp.rgb, temp.a, temp;\nMUL temp, fragment.color, temp;\n\n# Lowering contrast and shifting brightness ;\nMUL temp.rgb, temp, 0.8;\nADD temp.rgb, temp, 0.25;\n\nMOV result.color, temp;\nEND\n" }, { "answer_id": 4731432, "author": "user580853", "author_id": 580853, "author_profile": "https://Stackoverflow.com/users/580853", "pm_score": 3, "selected": false, "text": "Dark" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985/" ]
120,625
<p>I got this error when I checked out my database from source control. It might sounds weird to check in the sql server database, but this was what I have done because this is just a personal project.</p> <p>Anyone knows how to fix this?</p>
[ { "answer_id": 120643, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "ATTACH_REBUILD_LOG" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
120,627
<p>I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error:</p> <pre><code>MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj) </code></pre> <p>This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it?</p> <p>I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library.</p>
[ { "answer_id": 4216966, "author": "Alex", "author_id": 512381, "author_profile": "https://Stackoverflow.com/users/512381", "pm_score": 1, "selected": false, "text": "my_memory.c\n#undef malloc\n#undef calloc\n...\nvoid *_custom_malloc(int size) { return jmalloc(size); }\nvoid *_custom_calloc(int size) { return jcalloc(size); }\n...\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14443/" ]
120,628
<p>This is a real issue that applies on tagging items in general (and yes, this applies to StackOverflow too, and no, it is not a question about StackOverflow).</p> <p>The whole tagging issue helps cluster similar items, whatever items they may be (jokes, blog posts, so questions etc). However, there (usually but not strictly) is a hierarchy of tags, meaning that some tags <em>imply</em> other tags too. To use a familiar example, the "c#" so tag implies also ".net"; another example, in a jokes database, a "blondes" tag implies the "derisive" tag, similarly to "irish" or "belge" or "canadian" etc depending on the joke's country origin.</p> <p>How have you handled this, if you have, in your projects? I will supply an answer describing two different methods I have used in two separate cases (actually, the same mechanism but implemented in two different environments), but I am also interested not only on similar mechanisms, but also on your opinion on the hierarchy issue.</p>
[ { "answer_id": 120694, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "[Tags]\ntagID integer primary key\ntagName text\n\n[TagRelations]\ntagID integer # first part of two-field key\ntagID_parent integer # second part of key\ntrlValue float\n" }, { "answer_id": 120795, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "[TagRelations]\ntagId integer\ncloseTagId integer\nproximity integer\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6899/" ]
120,646
<p>If you call javascript window.open and pass a url to a .xls file it open on some machines in the browser window. How can you force it into Excel?</p>
[ { "answer_id": 120709, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 2, "selected": false, "text": "<a href=\"foo.xls\">" }, { "answer_id": 120761, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 1, "selected": false, "text": "application/vnd.ms-excel xls\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19494/" ]
120,648
<p>I use Assert.Fail a lot when doing TDD. I'm usually working on one test at a time but when I get ideas for things I want to implement later I quickly write an empty test where the name of the test method indicates what I want to implement as sort of a todo-list. To make sure I don't forget I put an Assert.Fail() in the body.</p> <p>When trying out xUnit.Net I found they hadn't implemented Assert.Fail. Of course you can always Assert.IsTrue(false) but this doesn't communicate my intention as well. I got the impression Assert.Fail wasn't implemented on purpose. Is this considered bad practice? If so why?</p> <hr> <p>@Martin Meredith That's not exactly what I do. I do write a test first and then implement code to make it work. Usually I think of several tests at once. Or I think about a test to write when I'm working on something else. That's when I write an empty failing test to remember. By the time I get to writing the test I neatly work test-first.</p> <p>@Jimmeh That looks like a good idea. Ignored tests don't fail but they still show up in a separate list. Have to try that out.</p> <p>@Matt Howells Great Idea. NotImplementedException communicates intention better than assert.Fail() in this case</p> <p>@Mitch Wheat That's what I was looking for. It seems it was left out to prevent it being abused in another way I abuse it.</p>
[ { "answer_id": 120670, "author": "Jimmeh", "author_id": 20749, "author_profile": "https://Stackoverflow.com/users/20749", "pm_score": 3, "selected": false, "text": "[Test]\n[Ignore]\npublic void YourTest()\n{ } \n" }, { "answer_id": 120679, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 7, "selected": true, "text": "[Test]\npublic void MyClassDoesSomething()\n{\n throw new NotImplementedException();\n}\n" }, { "answer_id": 120742, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 4, "selected": false, "text": "try \n{\n // Some code that should throw ExceptionX\n Assert.Fail(\"ExceptionX should be thrown\")\n} \ncatch ( ExceptionX ex ) \n{\n // test passed\n}\n" }, { "answer_id": 121173, "author": "Daniel Fanjul", "author_id": 16135, "author_profile": "https://Stackoverflow.com/users/16135", "pm_score": 2, "selected": false, "text": "void goodCode() {\n // TODO void goodCode()\n throw new NotSupportedOperationException(\"void goodCode()\");\n}\n" }, { "answer_id": 235812, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Assert.Fail" }, { "answer_id": 1048617, "author": "lexx", "author_id": 67014, "author_profile": "https://Stackoverflow.com/users/67014", "pm_score": 2, "selected": false, "text": "[TestMethod]\npublic void TestForException()\n{\n Exception _Exception = null;\n\n try\n {\n //Code that I expect to throw the exception.\n MyClass _MyClass = null;\n _MyClass.SomeMethod();\n //Code that I expect to throw the exception.\n }\n catch(Exception _ThrownException)\n { \n _Exception = _ThrownException\n }\n finally\n {\n Assert.IsNotNull(_Exception);\n //Replace NullReferenceException with expected exception.\n Assert.IsInstanceOfType(_Exception, typeof(NullReferenceException));\n }\n}\n" }, { "answer_id": 25546983, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 1, "selected": false, "text": "Assert.Fail" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3320/" ]
120,656
<p>How do I get a list of all files (and directories) in a given directory in Python?</p>
[ { "answer_id": 120676, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 9, "selected": false, "text": "os.listdir(path)\n" }, { "answer_id": 120692, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 6, "selected": false, "text": "import os\n\nfor filename in os.listdir(\"C:\\\\temp\"):\n print filename\n" }, { "answer_id": 120695, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "import os\nfor top, dirs, files in os.walk('./'):\n for nm in files: \n print os.path.join(top, nm)\n" }, { "answer_id": 120701, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 10, "selected": true, "text": "import os\n\nfor dirname, dirnames, filenames in os.walk('.'):\n # print path to all subdirectories first.\n for subdirname in dirnames:\n print(os.path.join(dirname, subdirname))\n\n # print path to all filenames.\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n # Advanced usage:\n # editing the 'dirnames' list will stop os.walk() from recursing into there.\n if '.git' in dirnames:\n # don't go into any .git directories.\n dirnames.remove('.git')\n" }, { "answer_id": 120948, "author": "giltay", "author_id": 21106, "author_profile": "https://Stackoverflow.com/users/21106", "pm_score": 7, "selected": false, "text": "import os\n\ndef listdir_fullpath(d):\n return [os.path.join(d, f) for f in os.listdir(d)]\n" }, { "answer_id": 11753937, "author": "Sam Watkins", "author_id": 218294, "author_profile": "https://Stackoverflow.com/users/218294", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python\n\nimport os\nimport sys\n\ndef ls(dir, hidden=False, relative=True):\n nodes = []\n for nm in os.listdir(dir):\n if not hidden and nm.startswith('.'):\n continue\n if not relative:\n nm = os.path.join(dir, nm)\n nodes.append(nm)\n nodes.sort()\n return nodes\n\ndef find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):\n root = os.path.join(root, '') # add slash if not there\n for parent, ldirs, lfiles in os.walk(root, topdown=topdown):\n if relative:\n parent = parent[len(root):]\n if dirs and parent:\n yield os.path.join(parent, '')\n if not hidden:\n lfiles = [nm for nm in lfiles if not nm.startswith('.')]\n ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place\n if files:\n lfiles.sort()\n for nm in lfiles:\n nm = os.path.join(parent, nm)\n yield nm\n\ndef test(root):\n print \"* directory listing, with hidden files:\"\n print ls(root, hidden=True)\n print\n print \"* recursive listing, with dirs, but no hidden files:\"\n for f in find(root, dirs=True):\n print f\n print\n\nif __name__ == \"__main__\":\n test(*sys.argv[1:])\n" }, { "answer_id": 12572822, "author": "kenny", "author_id": 667847, "author_profile": "https://Stackoverflow.com/users/667847", "pm_score": 4, "selected": false, "text": "import glob\nglob.glob('./[0-9].*')\n" }, { "answer_id": 13528334, "author": "Alok", "author_id": 1847405, "author_profile": "https://Stackoverflow.com/users/1847405", "pm_score": 0, "selected": false, "text": "#import modules\nimport os\n\n_CURRENT_DIR = '.'\n\n\ndef rec_tree_traverse(curr_dir, indent):\n \"recurcive function to traverse the directory\"\n #print \"[traverse_tree]\"\n\n try :\n dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)]\n except:\n print \"wrong path name/directory name\"\n return\n\n for file_or_dir in dfList:\n\n if os.path.isdir(file_or_dir):\n #print \"dir : \",\n print indent, file_or_dir,\"\\\\\"\n rec_tree_traverse(file_or_dir, indent*2)\n\n if os.path.isfile(file_or_dir):\n #print \"file : \",\n print indent, file_or_dir\n\n #end if for loop\n#end of traverse_tree()\n\ndef main():\n\n base_dir = _CURRENT_DIR\n\n rec_tree_traverse(base_dir,\" \")\n\n raw_input(\"enter any key to exit....\")\n#end of main()\n\n\nif __name__ == '__main__':\n main()\n" }, { "answer_id": 25390299, "author": "moylop260", "author_id": 3753497, "author_profile": "https://Stackoverflow.com/users/3753497", "pm_score": 0, "selected": false, "text": "path = '.'\nfor dirname, dirnames, filenames in os.walk(path):\n # print path to all filenames with extension py.\n for filename in filenames:\n fname_path = os.path.join(dirname, filename)\n fext = os.path.splitext(fname_path)[1]\n if fext == '.py':\n print fname_path\n else:\n continue\n" }, { "answer_id": 27713560, "author": "fivetentaylor", "author_id": 2998052, "author_profile": "https://Stackoverflow.com/users/2998052", "pm_score": 1, "selected": false, "text": "import os\n\n[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]\n" }, { "answer_id": 30471791, "author": "Arnaldo P. Figueira Figueira", "author_id": 1579731, "author_profile": "https://Stackoverflow.com/users/1579731", "pm_score": 3, "selected": false, "text": "import os\n\ndef scan_dir(dir):\n for name in os.listdir(dir):\n path = os.path.join(dir, name)\n if os.path.isfile(path):\n print path\n else:\n scan_dir(path)\n" }, { "answer_id": 35628738, "author": "bng44270", "author_id": 198259, "author_profile": "https://Stackoverflow.com/users/198259", "pm_score": 0, "selected": false, "text": "import re\nimport os\n\n[a for a in os.listdir(\".\") if re.search(\"^.*\\.py$\",a)]\n" }, { "answer_id": 38609425, "author": "Dave Engineer", "author_id": 1959038, "author_profile": "https://Stackoverflow.com/users/1959038", "pm_score": 4, "selected": false, "text": "import os\nos.listdir('.')\n" }, { "answer_id": 38941184, "author": "Alejandro Blasco", "author_id": 3589567, "author_profile": "https://Stackoverflow.com/users/3589567", "pm_score": 1, "selected": false, "text": "#!/bin/python2\n\nimport os\n\ndef scan_dir(path):\n print map(os.path.abspath, os.listdir(pwd))\n" }, { "answer_id": 45229467, "author": "Heenashree Khandelwal", "author_id": 8017535, "author_profile": "https://Stackoverflow.com/users/8017535", "pm_score": 0, "selected": false, "text": "def print_directory_contents(sPath):\n import os \n for sChild in os.listdir(sPath): \n sChildPath = os.path.join(sPath,sChild)\n if os.path.isdir(sChildPath):\n print_directory_contents(sChildPath)\n else:\n print(sChildPath)\n" }, { "answer_id": 45242048, "author": "salehinejad", "author_id": 4538031, "author_profile": "https://Stackoverflow.com/users/4538031", "pm_score": 0, "selected": false, "text": "import os\ndir = 'given_directory_name'\nfilenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]\n" }, { "answer_id": 47211494, "author": "apeter", "author_id": 7065873, "author_profile": "https://Stackoverflow.com/users/7065873", "pm_score": 0, "selected": false, "text": "import subprocess\nprint(subprocess.check_output([\"ls\", \"/\"]).decode(\"utf8\"))\n" }, { "answer_id": 49350260, "author": "HassanSh__3571619", "author_id": 3571619, "author_profile": "https://Stackoverflow.com/users/3571619", "pm_score": 2, "selected": false, "text": "dir = 'given_directory_name'\nfilenames = [os.path.abspath(os.path.join(dir,i)) for i in os.listdir(dir)]\n" }, { "answer_id": 52180310, "author": "Khaino", "author_id": 4053000, "author_profile": "https://Stackoverflow.com/users/4053000", "pm_score": 2, "selected": false, "text": "os.scandir(path='.')\n" }, { "answer_id": 53643569, "author": "Steve Tarver", "author_id": 1089228, "author_profile": "https://Stackoverflow.com/users/1089228", "pm_score": 3, "selected": false, "text": "os.listdir()" }, { "answer_id": 71669709, "author": "Manav Patadia", "author_id": 3380823, "author_profile": "https://Stackoverflow.com/users/3380823", "pm_score": 0, "selected": false, "text": "list_output_files = [os.getcwd()+\"\\\\\"+f for f in os.listdir(os.getcwd())]\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
120,657
<p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p> <p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p> <p>To clarify from current responses:</p> <ol> <li>I am using the subprocess module</li> <li>I am passing the command line + arguments in as a list</li> <li>The issue is with the path to the command itself, not any of the arguments</li> <li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li> <li>I'm using no shell argument (so <code>shell=false</code>) </li> <li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li> <li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li> <li>The command that is failing is: </li> </ol> <blockquote> <p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p> </blockquote> <p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
[ { "answer_id": 120706, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": true, "text": "subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)\n" }, { "answer_id": 120708, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 0, "selected": false, "text": "wget \"http://foo.com/?bar=baz&amp;baz=bar\"\n" }, { "answer_id": 120992, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "^" }, { "answer_id": 20922266, "author": "rickyteng", "author_id": 3160495, "author_profile": "https://Stackoverflow.com/users/3160495", "pm_score": 0, "selected": false, "text": "exe = 'C:/Program Files (x86)/VideoLAN/VLC/VLC.exe'\nurl = 'http://translate.google.com/translate_tts?tl=en&q=hello+world'\nsubprocess.Popen([exe, url.replace(\"&\",\"^&\")],shell=True)\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16035/" ]
120,662
<p>I'm trying to run SQuirreL SQL.<br> I've downloaded it and installed it, but when I try to run it I get this error message: </p> <blockquote> <p>Java Virtual Machine Launcher.<br> Could not find the main class.<br> Program will exit. </p> </blockquote> <p>I get the gist of this, but I have not idea how to fix it. Any help? </p> <h3>more info:</h3> <ul> <li>I'm on Windows XP pro. </li> <li>I have java 1.6 installed, and other apps are running OK. </li> <li>The install ran OK. </li> <li>I believe I've followed the installation instructions correctly. </li> <li>To run it, I'm invoking the <strong>squirrel-sql.bat</strong> file. </li> </ul> <h3>Update</h3> <p>This question: <a href="https://stackoverflow.com/questions/1417328/could-not-find-the-main-class">&quot;Could not find the main class: XX. Program will exit.&quot;</a> gives some background on this error from the point of view of a java developer. </p>
[ { "answer_id": 120729, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 5, "selected": true, "text": "squirrel-sql.jar" }, { "answer_id": 121552, "author": "18Rabbit", "author_id": 12662, "author_profile": "https://Stackoverflow.com/users/12662", "pm_score": 3, "selected": false, "text": "java -classpath \"c:\\directory\\lib\\squirrel-sql.jar\" com.some.squirrel.package.file\n" }, { "answer_id": 1312970, "author": "Nathan Feger", "author_id": 8563, "author_profile": "https://Stackoverflow.com/users/8563", "pm_score": 2, "selected": false, "text": "start javaw -jar squirrel-sql.jar\n" }, { "answer_id": 2920018, "author": "huug", "author_id": 205785, "author_profile": "https://Stackoverflow.com/users/205785", "pm_score": 1, "selected": false, "text": "squirrel-sql.jar\n" }, { "answer_id": 23370426, "author": "Steve Gelman", "author_id": 967671, "author_profile": "https://Stackoverflow.com/users/967671", "pm_score": 1, "selected": false, "text": "JRE32=C:\\Program Files\\Java\\jre7\n" }, { "answer_id": 58540339, "author": "eby", "author_id": 5835746, "author_profile": "https://Stackoverflow.com/users/5835746", "pm_score": 0, "selected": false, "text": "Java Virtual Machine Launcher - could not find the main class\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ]
120,693
<p>I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens.</p> <p>If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that.</p> <p>Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Regex&lt;/title&gt; &lt;script type="text/javascript" charset="utf-8"&gt; var grep = new RegExp('gr['); try { var results = grep.exec('bob went to town'); } catch (e) { //Do nothing? } alert('If you can see this then the script kept going'); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 120716, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 3, "selected": false, "text": "var grep = new RegExp('gr[');\n" }, { "answer_id": 120743, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 5, "selected": true, "text": " <script type=\"text/javascript\" charset=\"utf-8\">\n var grep;\n\n try {\n grep = new RegExp(\"gr[\");\n }\n catch(e) {\n alert(e);\n\n }\n try\n {\n var results = grep.exec('bob went to town');\n }\n catch (e)\n {\n //Do nothing?\n }\n\n alert('If you can see this then the script kept going');\n </script>\n" }, { "answer_id": 120809, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "var grep, results;\n\ntry {\n grep = new RegExp(\"gr[\");\n results = grep.exec('bob went to town');\n}\ncatch(e) {\n alert(e);\n}\nalert('If you can see this then the script kept going');\n" }, { "answer_id": 121802, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 2, "selected": false, "text": "\nvar grep, results;\n\ntry\n{\n grep = new RegExp(\"gr[\"); // your user input here\n}\ncatch(e)\n{\n alert(\"The RegExpr is invalid\");\n}\n\n// do your stuff with grep and results\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
120,702
<p>Using Scala's command line REPL:</p> <pre><code>def foo(x: Int): Unit = {} def foo(x: String): Unit = {println(foo(2))} </code></pre> <p>gives</p> <pre><code>error: type mismatch; found: Int(2) required: String </code></pre> <p>It seems that you can't define overloaded recursive methods in the REPL. I thought this was a bug in the Scala REPL and filed it, but it was almost instantly closed with "wontfix: I don't see any way this could be supported given the semantics of the interpreter, because these two methods must to be compiled together." He recommended putting the methods in an enclosing object.</p> <p>Is there a JVM language implementation or Scala expert who could explain why? I can see it would be a problem if the methods called each other for instance, but in this case?</p> <p>Or if this is too large a question and you think I need more prerequisite knowledge, does someone have any good links to books or sites about language implementations, especially on the JVM? (I know about John Rose's blog, and the book Programming Language Pragmatics... but that's about it. :)</p>
[ { "answer_id": 122338, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 5, "selected": true, "text": "test" }, { "answer_id": 3664567, "author": "psp", "author_id": 89872, "author_profile": "https://Stackoverflow.com/users/89872", "pm_score": 3, "selected": false, "text": "% scala28\nWelcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_20).\nType in expressions to have them evaluated.\nType :help for more information.\n\nscala> def foo(x: Int): Unit = () ; def foo(x: String): Unit = { println(foo(2)) } \nfoo: (x: String)Unit <and> (x: Int)Unit\nfoo: (x: String)Unit <and> (x: Int)Unit\n\nscala> foo(5)\n\nscala> foo(\"abc\")\n()\n" }, { "answer_id": 11276947, "author": "Daniel C. Sobral", "author_id": 53013, "author_profile": "https://Stackoverflow.com/users/53013", "pm_score": 1, "selected": false, "text": "def foo(x: Int): Unit = {}\ndef foo(x: String): Unit = {println(foo(2))}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15627/" ]
120,731
<p>Let's assume you have one massive table with three columns as shown below:</p> <pre><code>[id] INT NOT NULL, [date] SMALLDATETIME NOT NULL, [sales] FLOAT NULL </code></pre> <p>Also assume you are limited to one physical disk and one filegroup (PRIMARY). You expect this table to hold sales for 10,000,000+ ids, across 100's of dates (easily 1B+ records).</p> <p>As with many data warehousing scenarios, the data will typically grow sequentially by date (i.e., each time you perform a data load, you will be inserting new dates, and maybe updating some of the more recent dates of data). For analytic purposes, the data will often be queried and aggregated for a random set of ~10,000 ids which will be specified via a join with another table. Often, these queries don't specify date ranges, or specify very wide date ranges, which leads me to my question: What is the best way to index / partition this table?</p> <p>I have thought about this for a while, but am stuck with conflicting solutions:</p> <p><strong>Option #1:</strong> As data will be loaded sequentially by date, define the clustered index (and primary key) as [date], [id]. Also create a "sliding window" partitioning function / scheme on date allowing rapid movement of new data in / out of the table. Potentially create a non-clustered index on id to help with querying.</p> <p><strong>Expected Outcome #1:</strong> This setup will be very fast for data loading purposes, but sub-optimal when it comes to analytic reads as, in a worst case scenario (no limiting by dates, unlucky with set of id's queried), 100% of the data pages may be read.</p> <p><strong>Option #2:</strong> As the data will be queried for only a small subset of ids at a time, define the clustered index (and primary key) as [id], [date]. Do not bother to create a partitioned table.</p> <p><strong>Expected Outcome #2:</strong> Expected huge performance hit when it comes to loading data as we can no longer quickly limit by date. Expected huge performance benefit when it comes to my analytic queries as it will minimize the number of data pages read.</p> <p><strong>Option #3:</strong> Clustered (and primary key) as follows: [id], [date]; "sliding window" partition function / scheme on date.</p> <p><strong>Expected Outcome #3:</strong> Not sure what to expect. Given that the first column in the clustered index is [id] and thus (it is my understanding) the data is arranged by ID, I would expect good performance from my analytic queries. However, the data is partitioned by date, which is contrary to the definition of the clustered index (but still aligned as date is part of the index). I haven't found much documentation that speaks to this scenario and what, if any, performance benefits I may get from this, which brings me to my final, bonus question:</p> <p>If I am creating a table on one filegroup on one disk, with a clustered index on one column, is there any benefit (besides partition switching when loading the data) that comes from defining a partition on the same column?</p>
[ { "answer_id": 120882, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "CREATE TABLE Narrow\n(\n [id] INT NOT NULL,\n [date] SMALLDATETIME NOT NULL,\n [sales] FLOAT NULL,\n PRIMARY KEY(id, date) --EDIT, just noticed your id is not unique.\n)\n\nCREATE INDEX CoveringNarrow ON Narrow(date, id, sales)\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4391/" ]
120,751
<p>I have been trying to use routes.rb for creating a URL /similar-to-:product (where product is dynamic) for my website. The issue is that routes.rb readily supports URLs like /:product-similar but doesn't support the former because it requires :product to be preceded with a separator ('/' is a separator but '-' isn't). The list of separators is in ActionController::Routing::SEPARATORS.</p> <p>I can't add '-' as a separator because :product can also contain a hyphen. What is the best way of supporting a URL like this?</p> <p>One way that I have successfully tried is to not use routes.rb and put the URL parsing logic in the controller itself, but that isn't the cleanest way.</p>
[ { "answer_id": 1385217, "author": "Leonid Shevtsov", "author_id": 6678, "author_profile": "https://Stackoverflow.com/users/6678", "pm_score": 2, "selected": true, "text": "-" }, { "answer_id": 1476296, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "/similar-to-:product" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17494/" ]
120,755
<p>Is the Entity Framework aware of identity columns? </p> <p>I am using SQL Server 2005 Express Edition and have several tables where the primary key is an identity column. when I use these tables to create an entity model and use the model in conjunction with an entity datasource bond to a formview in order to create a new entity I am asked to enter a value for the identity column. Is there a way to make the framework not ask for values for identity columns?</p>
[ { "answer_id": 388515, "author": "biozinc", "author_id": 30698, "author_profile": "https://Stackoverflow.com/users/30698", "pm_score": 6, "selected": false, "text": "CreateYourEntityHere" }, { "answer_id": 6282096, "author": "John West", "author_id": 761580, "author_profile": "https://Stackoverflow.com/users/761580", "pm_score": 2, "selected": false, "text": "StoreGeneratedPattern=\"Identity\"" }, { "answer_id": 9958294, "author": "Fun Chiat Chan", "author_id": 1274015, "author_profile": "https://Stackoverflow.com/users/1274015", "pm_score": 0, "selected": false, "text": " Dim ItemCollection = From d In action.Parameter\n Select New STOCK_TYPE With {\n .Code = d.ParamValue.<Code>.Value,\n .GeneralUseID = d.ParamValue.<GeneralUse>.Value,\n }\n\n\n GtexCtx.STOCK_TYPE.AddObject( ItemCollection.FirstOrDefault)\n GtexCtx.SaveChanges()\n" }, { "answer_id": 15503958, "author": "aladd04", "author_id": 1945983, "author_profile": "https://Stackoverflow.com/users/1945983", "pm_score": 2, "selected": false, "text": "FooConfiguration.cs : EntityTypeConfiguration<Foo>" }, { "answer_id": 17737443, "author": "Siva", "author_id": 408204, "author_profile": "https://Stackoverflow.com/users/408204", "pm_score": 3, "selected": false, "text": "[DatabaseGenerated(DatabaseGeneratedOption.Identity)]\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
120,763
<p>I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command?</p> <p>Instead of this:</p> <pre><code>string filePath = @"C:\somepath\file.txt"; </code></pre> <p>I want to do this:</p> <pre><code>string filePath = @helper.getFilePath(); //getFilePath returns a string </code></pre> <p>This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something?</p>
[ { "answer_id": 120785, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 2, "selected": false, "text": "helper.getFilePath()" }, { "answer_id": 120796, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 2, "selected": false, "text": "print(@\"c:\\mydir\\dont\\have\\to\\escape\\backslashes\\etc\");\n" }, { "answer_id": 120805, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 1, "selected": false, "text": "string filePath = helper.getFilePath();\n" }, { "answer_id": 120837, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 2, "selected": false, "text": "@\"good morning\" // a string literal" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
120,766
<p>I have several &lt;li> elements with different id's on ASP.NET page:</p> <pre><code>&lt;li id="li1" class="class1"&gt; &lt;li id="li2" class="class1"&gt; &lt;li id="li3" class="class1"&gt; </code></pre> <p>and can change their class using JavaScript like this:</p> <pre><code>li1.className="class2" </code></pre> <p>But is there a way to change &lt;li> element class using ASP.NET? It could be something like:</p> <pre><code>WebControl control = (WebControl)FindControl("li1"); control.CssClass="class2"; </code></pre> <p>But FindControl() doesn't work as I expected. Any suggestions?</p> <p>Thanks in advance!</p>
[ { "answer_id": 120774, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 2, "selected": false, "text": "<li id=\"li1\" runat=\"server\">stuff</li>\n" }, { "answer_id": 120777, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 4, "selected": false, "text": "<li id=\"li1\" runat=\"server\">stuff</li>\n" }, { "answer_id": 120894, "author": "Richard Yorkshire", "author_id": 21001, "author_profile": "https://Stackoverflow.com/users/21001", "pm_score": 4, "selected": true, "text": "<li runat=\"server ... ></li>\n" }, { "answer_id": 397821, "author": "user49845", "author_id": 49845, "author_profile": "https://Stackoverflow.com/users/49845", "pm_score": 5, "selected": false, "text": "runat=\"server\"" }, { "answer_id": 2099341, "author": "cweston", "author_id": 37966, "author_profile": "https://Stackoverflow.com/users/37966", "pm_score": 3, "selected": false, "text": "using System.Web.UI.HtmlControls;\n\nHtmlGenericControl liItem = (HtmlGenericControl) ctl.FindControl(\"liItemID\");\nliItem.Attributes.Add(\"class\", \"someCssClass\");\n" }, { "answer_id": 10911810, "author": "ebram khalil", "author_id": 1295905, "author_profile": "https://Stackoverflow.com/users/1295905", "pm_score": 0, "selected": false, "text": "li1.Style.add(\"color\",\"Blue\");\nli2.Style.add(\"text-decoration\",\"line-through\");\n" }, { "answer_id": 11357836, "author": "Amareswar sai Mulumudi", "author_id": 1506068, "author_profile": "https://Stackoverflow.com/users/1506068", "pm_score": 1, "selected": false, "text": "using System.Web.UI.HtmlControls;\n\nHtmlGenericControl liItem = (HtmlGenericControl) ctl.FindControl(\"liItemID\");\nliItem.Attributes.Add(\"class\", \"someCssClass\");\n" }, { "answer_id": 11879780, "author": "Vimal Patel", "author_id": 1488039, "author_profile": "https://Stackoverflow.com/users/1488039", "pm_score": 2, "selected": false, "text": "li1.Style.Add(\"background-color\", \"black\");\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
120,783
<p>Currently I have this (edited after reading advice):</p> <pre><code>struct Pair&lt;T, K&gt; : IEqualityComparer&lt;Pair&lt;T, K&gt;&gt; { readonly private T _first; readonly private K _second; public Pair(T first, K second) { _first = first; _second = second; } public T First { get { return _first; } } public K Second { get { return _second; } } #region IEqualityComparer&lt;Pair&lt;T,K&gt;&gt; Members public bool Equals(Pair&lt;T, K&gt; x, Pair&lt;T, K&gt; y) { return x.GetHashCode(x) == y.GetHashCode(y); } public int GetHashCode(Pair&lt;T, K&gt; obj) { int hashCode = obj.First == null ? 0 : obj._first.GetHashCode(); hashCode ^= obj.Second == null ? 0 : obj._second.GetHashCode(); return hashCode; } #endregion public override int GetHashCode() { return this.GetHashCode(this); } public override bool Equals(object obj) { return (obj != null) &amp;&amp; (obj is Pair&lt;T, K&gt;) &amp;&amp; this.Equals(this, (Pair&lt;T, K&gt;) obj); } } </code></pre> <p>The problem is that First and Second may not be reference types (VS actually warns me about this), but the code still compiles. Should I cast them (First and Second) to objects before I compare them, or is there a better way to do this?</p> <p>Edit: Note that I <em>want</em> this struct to support value and reference types (in other words, constraining by class is not a valid solution)</p> <p>Edit 2: As to what I'm trying to achieve, I want this to work in a Dictionary. Secondly, SRP isn't important to me right now because that isn't really the essence of this problem - it can always be refactored later. Thirdly, comparing to default(T) will not work in lieu of comparing to null - try it.</p>
[ { "answer_id": 120843, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "bool result = ( x._hashCode == y._hashCode );\nif ( result ) { result = ( x._first == y._first && x._second == y._second ); }\n// OR?: if ( result ) { result = object.Equals( x._first, y._first ) && object.Equals( x._second, y._second ); }\n// OR?: if ( result ) { result = object.ReferenceEquals( x._first, y._first ) && object.Equals( x._second, y._second ); }\nreturn result;\n" }, { "answer_id": 121642, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 3, "selected": true, "text": "internal struct Pair<T, K> : IEquatable<Pair<T, K>>\n{\n private readonly T _first;\n private readonly K _second;\n\n public Pair(T first, K second)\n {\n _first = first;\n _second = second;\n }\n\n public T First\n {\n get { return _first; }\n }\n\n public K Second\n {\n get { return _second; }\n }\n\n public bool Equals(Pair<T, K> obj)\n {\n return Equals(obj._first, _first) && Equals(obj._second, _second);\n }\n\n public override bool Equals(object obj)\n {\n return obj is Pair<T, K> && Equals((Pair<T, K>) obj);\n }\n\n public override int GetHashCode()\n {\n unchecked\n {\n return (_first != null ? _first.GetHashCode() * 397 : 0) ^ (_second != null ? _second.GetHashCode() : 0);\n }\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
120,797
<p>Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.</p> <p>I am behind a proxy server. How can I set my JVM to use the proxy ?</p>
[ { "answer_id": 120802, "author": "Leonel", "author_id": 15649, "author_profile": "https://Stackoverflow.com/users/15649", "pm_score": 10, "selected": true, "text": "http.proxyHost" }, { "answer_id": 120818, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 6, "selected": false, "text": "if (needsProxy()) {\n System.setProperty(\"http.proxyHost\",getProxyHost());\n System.setProperty(\"http.proxyPort\",getProxyPort());\n} else {\n System.setProperty(\"http.proxyHost\",\"\");\n System.setProperty(\"http.proxyPort\",\"\");\n}\n" }, { "answer_id": 122579, "author": "Alex. S.", "author_id": 18300, "author_profile": "https://Stackoverflow.com/users/18300", "pm_score": 4, "selected": false, "text": "import java.net.*;\nimport java.io.*;\n\npublic class ProxyAuthenticator extends Authenticator {\n\n private String userName, password;\n\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(userName, password.toCharArray());\n }\n\n public ProxyAuthenticator(String userName, String password) {\n this.userName = userName;\n this.password = password;\n }\n}\n" }, { "answer_id": 137174, "author": "Chris Carruthers", "author_id": 1119, "author_profile": "https://Stackoverflow.com/users/1119", "pm_score": 6, "selected": false, "text": "...\n\npublic void setProxy() {\n if (isUseHTTPProxy()) {\n // HTTP/HTTPS Proxy\n System.setProperty(\"http.proxyHost\", getHTTPHost());\n System.setProperty(\"http.proxyPort\", getHTTPPort());\n System.setProperty(\"https.proxyHost\", getHTTPHost());\n System.setProperty(\"https.proxyPort\", getHTTPPort());\n if (isUseHTTPAuth()) {\n String encoded = new String(Base64.encodeBase64((getHTTPUsername() + \":\" + getHTTPPassword()).getBytes()));\n con.setRequestProperty(\"Proxy-Authorization\", \"Basic \" + encoded);\n Authenticator.setDefault(new ProxyAuth(getHTTPUsername(), getHTTPPassword()));\n }\n }\n if (isUseSOCKSProxy()) {\n // SOCKS Proxy\n System.setProperty(\"socksProxyHost\", getSOCKSHost());\n System.setProperty(\"socksProxyPort\", getSOCKSPort());\n if (isUseSOCKSAuth()) {\n System.setProperty(\"java.net.socks.username\", getSOCKSUsername());\n System.setProperty(\"java.net.socks.password\", getSOCKSPassword());\n Authenticator.setDefault(new ProxyAuth(getSOCKSUsername(), getSOCKSPassword()));\n }\n }\n}\n\n...\n\npublic class ProxyAuth extends Authenticator {\n private PasswordAuthentication auth;\n\n private ProxyAuth(String user, String password) {\n auth = new PasswordAuthentication(user, password == null ? new char[]{} : password.toCharArray());\n }\n\n protected PasswordAuthentication getPasswordAuthentication() {\n return auth;\n }\n}\n\n...\n" }, { "answer_id": 2409610, "author": "dma_k", "author_id": 267197, "author_profile": "https://Stackoverflow.com/users/267197", "pm_score": 2, "selected": false, "text": "${java.home}/lib/deploy.jar" }, { "answer_id": 11527488, "author": "gr5", "author_id": 957476, "author_profile": "https://Stackoverflow.com/users/957476", "pm_score": 7, "selected": false, "text": "java -Djava.net.useSystemProxies=true ...\n" }, { "answer_id": 12295125, "author": "Pallavi", "author_id": 978180, "author_profile": "https://Stackoverflow.com/users/978180", "pm_score": 3, "selected": false, "text": "System.setProperty(\"http.proxyHost\", \"proxy host addr\");\nSystem.setProperty(\"http.proxyPort\", \"808\");\nAuthenticator.setDefault(new Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n\n return new PasswordAuthentication(\"domain\\\\user\",\"password\".toCharArray());\n }\n});\n\nURL url = new URL(\"http://www.google.com/\");\nURLConnection con = url.openConnection();\n\nBufferedReader in = new BufferedReader(new InputStreamReader(\n con.getInputStream()));\n\n// Read it ...\nString inputLine;\nwhile ((inputLine = in.readLine()) != null)\n System.out.println(inputLine);\n\nin.close();\n" }, { "answer_id": 12995494, "author": "Sorter", "author_id": 1097600, "author_profile": "https://Stackoverflow.com/users/1097600", "pm_score": 2, "selected": false, "text": "System.getProperties().put(\"http.proxyHost\", \"someProxyURL\");\nSystem.getProperties().put(\"http.proxyPort\", \"someProxyPort\");\nSystem.getProperties().put(\"http.proxyUser\", \"someUserName\");\nSystem.getProperties().put(\"http.proxyPassword\", \"somePassword\");\n" }, { "answer_id": 13967127, "author": "patdevelop", "author_id": 920859, "author_profile": "https://Stackoverflow.com/users/920859", "pm_score": 1, "selected": false, "text": "-Dhttp.proxyHost= -Dhttp.proxyPort=" }, { "answer_id": 24551536, "author": "Viet Tran", "author_id": 1148069, "author_profile": "https://Stackoverflow.com/users/1148069", "pm_score": 2, "selected": false, "text": "public void setHttpProxy(boolean isNeedProxy) {\n if (isNeedProxy) {\n System.setProperty(\"http.proxyHost\", getProxyHost());\n System.setProperty(\"http.proxyPort\", getProxyPort());\n } else {\n System.clearProperty(\"http.proxyHost\");\n System.clearProperty(\"http.proxyPort\");\n }\n}\n" }, { "answer_id": 27919196, "author": "sarath", "author_id": 1491081, "author_profile": "https://Stackoverflow.com/users/1491081", "pm_score": 5, "selected": false, "text": "System.getProperties().put(\"http.proxyHost\", \"someProxyURL\");\nSystem.getProperties().put(\"http.proxyPort\", \"someProxyPort\");\n" }, { "answer_id": 32511851, "author": "Mihai Capotă", "author_id": 200234, "author_profile": "https://Stackoverflow.com/users/200234", "pm_score": 4, "selected": false, "text": "java.net.useSystemProxies" }, { "answer_id": 32897878, "author": "Philip M.", "author_id": 4813037, "author_profile": "https://Stackoverflow.com/users/4813037", "pm_score": 2, "selected": false, "text": "// proxy configuration read from file resource under \"proxyFileName\"\nString proxyFileName = \"proxy.txt\"\nString proxyPort = \"1234\"\nString url = \"http://www.promised.land\"\nFile testProxyFile = new File(proxyFileName)\nURLConnection connection\n\nif (!testProxyFile.exists()) {\n\n logger.debug \"proxyFileName doesn't exist. Bypassing connection via proxy.\"\n connection = url.toURL().openConnection()\n\n} else {\n String proxyAddress = testProxyFile.text\n connection = url.toURL().openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)))\n}\n\ntry {\n connection.connect()\n}\ncatch (Exception e) {\n logger.error e.printStackTrace()\n}\n" }, { "answer_id": 41862236, "author": "Andreas Panagiotidis", "author_id": 823368, "author_profile": "https://Stackoverflow.com/users/823368", "pm_score": 4, "selected": false, "text": "C:\\temp>java -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps.proxyUser=user -Dhttps.proxyPassword=\"password\" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit com.andreas.JavaNetHttpConnection\n" }, { "answer_id": 45060126, "author": "MadBoomy", "author_id": 2135941, "author_profile": "https://Stackoverflow.com/users/2135941", "pm_score": 4, "selected": false, "text": "java -Dhttp.proxyHost=10.10.10.10 -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password -jar myJar.jar\n" }, { "answer_id": 47583369, "author": "Marcelo C.", "author_id": 1907282, "author_profile": "https://Stackoverflow.com/users/1907282", "pm_score": 3, "selected": false, "text": "java -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=8080 org.example.Main\n" }, { "answer_id": 72875447, "author": "nuclear_party", "author_id": 12793815, "author_profile": "https://Stackoverflow.com/users/12793815", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) throws IOException {\n System.setProperty(\"java.net.useSystemProxies\", \"true\");\n final String proxyUser = \"lum-customer-c_f95783f5-zone-datacenter-ip-92.240.207.56\";\n final String proxyPass = \"s3mgwrx2b628\";\n final String host = \"zproxy.lum-superproxy.io\";\n final Integer port = 22225;\n\n // http\n System.setProperty(\"http.proxyHost\",host);\n System.setProperty(\"http.proxyPort\", String.valueOf(port));\n System.setProperty(\"http.proxyUser\", proxyUser);\n System.setProperty(\"http.proxyPassword\", proxyPass);\n\n // https\n System.setProperty(\"https.proxyHost\",host);\n System.setProperty(\"https.proxyPort\", String.valueOf(port));\n System.setProperty(\"https.proxyUser\", proxyUser);\n System.setProperty(\"https.proxyPassword\", proxyPass);\n\n System.setProperty(\"jdk.http.auth.tunneling.disabledSchemes\", \"\");\n System.setProperty(\"jdk.https.auth.tunneling.disabledSchemes\", \"\");\n\n Authenticator.setDefault(new Authenticator() {\n @Override\n public PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());\n }\n }\n );\n\n // create and send a https request to myip.com API\n URL url = new URL(\"https://api.myip.com\");\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n int status = connection.getResponseCode();\n \n // read the response\n BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String responseLine;\n StringBuffer responseContent = new StringBuffer();\n while ((responseLine = in.readLine()) != null) \n responseContent.append(responseLine);\n \n in.close();\n connection.disconnect();\n \n // print the response\n System.out.println(status);\n System.out.println(responseContent);\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649/" ]
120,804
<p>I am going through John Resig's excellent <a href="http://ejohn.org/apps/learn/#47" rel="noreferrer">Advanced javascript tutorial</a> and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice)</p> <pre><code>&gt;&gt;&gt; arguments [3, 1, 2, 3] &gt;&gt;&gt; Array.slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 &gt;&gt;&gt; Array.slice.call( arguments, 1 ) [] &gt;&gt;&gt; Array().slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 &gt;&gt;&gt; Array().slice.call( arguments, 1 ) 1,2,3 0=1 1=2 2=3 </code></pre> <p>Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list).</p>
[ { "answer_id": 121054, "author": "ujh", "author_id": 4936, "author_profile": "https://Stackoverflow.com/users/4936", "pm_score": 3, "selected": false, "text": "Array().slice.call\n" }, { "answer_id": 121120, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": ">>> Array === Array()\nfalse\n\n>>> Array.constructor\nFunction()\n\n>>> Array().constructor\nArray()\n" }, { "answer_id": 121302, "author": "kamens", "author_id": 1335, "author_profile": "https://Stackoverflow.com/users/1335", "pm_score": 6, "selected": true, "text": ">>> String.substring.call(\"foo\", 1)\n\"1\"\n\n>>> String().substring.call(\"foo\", 1)\n\"oo\"\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21075/" ]
120,836
<p>How can one load custom (not an image, nor a sound file) resource file from /res within .jar using MIDP 2.0?</p>
[ { "answer_id": 1224490, "author": "kgutteridge", "author_id": 131410, "author_profile": "https://Stackoverflow.com/users/131410", "pm_score": 0, "selected": false, "text": "getResourceAsStream(\"/res/yourresource\");\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1596171/" ]
120,851
<p>We are creating an XBAP application that we need to have rounded corners in various locations in a single page and we would like to have a WPF Rounded Corner container to place a bunch of other elements within. Does anyone have some suggestions or sample code on how we can best accomplish this? Either with styles on a or with creating a custom control?</p>
[ { "answer_id": 120895, "author": "kobusb", "author_id": 1620, "author_profile": "https://Stackoverflow.com/users/1620", "pm_score": 9, "selected": true, "text": "<Border BorderBrush=\"#FF000000\" BorderThickness=\"1\" CornerRadius=\"8\">\n <Grid/>\n</Border>\n" }, { "answer_id": 209949, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 6, "selected": false, "text": "<Page\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Background=\"Black\"\n>\n <!-- Rounded yellow border -->\n <Border\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\"\n BorderBrush=\"Yellow\"\n BorderThickness=\"3\"\n CornerRadius=\"10\"\n Padding=\"2\"\n >\n <Grid>\n <!-- Rounded mask (stretches to fill Grid) -->\n <Border\n Name=\"mask\"\n Background=\"White\"\n CornerRadius=\"7\"\n />\n\n <!-- Main content container -->\n <StackPanel>\n <!-- Use a VisualBrush of 'mask' as the opacity mask -->\n <StackPanel.OpacityMask>\n <VisualBrush Visual=\"{Binding ElementName=mask}\"/>\n </StackPanel.OpacityMask>\n\n <!-- Any content -->\n <Image Source=\"http://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg\"/>\n <Rectangle\n Height=\"50\"\n Fill=\"Red\"/>\n <Rectangle\n Height=\"50\"\n Fill=\"White\"/>\n <Rectangle\n Height=\"50\"\n Fill=\"Blue\"/>\n </StackPanel>\n </Grid>\n </Border>\n</Page>\n" }, { "answer_id": 6945456, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 4, "selected": false, "text": "<Border\n Width=\"200\"\n Height=\"25\"\n CornerRadius=\"11\"\n Background=\"#FF919194\"\n>\n <Border.Clip>\n <RectangleGeometry\n RadiusX=\"{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}\"\n RadiusY=\"{Binding RadiusX, RelativeSource={RelativeSource Self}}\"\n >\n <RectangleGeometry.Rect>\n <MultiBinding\n Converter=\"{StaticResource widthAndHeightToRectConverter}\"\n >\n <Binding\n Path=\"ActualWidth\"\n RelativeSource=\"{RelativeSource AncestorType={x:Type Border}}\"\n />\n <Binding\n Path=\"ActualHeight\"\n RelativeSource=\"{RelativeSource AncestorType={x:Type Border}}\"\n />\n </MultiBinding>\n </RectangleGeometry.Rect>\n </RectangleGeometry>\n </Border.Clip>\n\n <Rectangle\n Width=\"100\"\n Height=\"100\"\n Fill=\"Blue\"\n HorizontalAlignment=\"Left\"\n VerticalAlignment=\"Center\"\n />\n</Border>\n" }, { "answer_id": 12079207, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 2, "selected": false, "text": " ' Create a ListBox of Buttons, one button for each MEF charting component. \n For Each c As Lazy(Of ICharts, IDictionary(Of String, Object)) In ext.ChartDescriptions\n Dim brdr As New Border\n brdr.BorderBrush = Brushes.Black\n brdr.BorderThickness = New Thickness(2, 2, 2, 2)\n brdr.CornerRadius = New CornerRadius(8, 8, 8, 8)\n Dim btn As New Button\n AddHandler btn.Click, AddressOf GenericButtonClick\n brdr.Child = btn\n brdr.Background = btn.Background\n btn.Margin = brdr.BorderThickness\n btn.Width = ChartsLBx.ActualWidth - 22\n btn.BorderThickness = New Thickness(0, 0, 0, 0)\n btn.Height = 22\n btn.Content = c.Metadata(\"Description\")\n btn.Tag = c\n btn.ToolTip = \"Push button to see \" & c.Metadata(\"Description\").ToString & \" chart\"\n Dim lbi As New ListBoxItem\n lbi.Content = brdr\n ChartsLBx.Items.Add(lbi)\n Next\n\nPublic Event Click As RoutedEventHandler\n\nPrivate Sub GenericButtonClick(sender As Object, e As RoutedEventArgs)\n Dim btn As Button = DirectCast(sender, Button)\n Dim c As Lazy(Of ICharts, IDictionary(Of String, Object)) = DirectCast(btn.Tag, Lazy(Of ICharts, IDictionary(Of String, Object)))\n Dim w As Window = DirectCast(c.Value, Window)\n Dim cc As ICharts = DirectCast(c.Value, ICharts)\n c.Value.CreateChart()\n w.Show()\nEnd Sub\n\n<System.ComponentModel.Composition.Export(GetType(ICharts))> _\n<System.ComponentModel.Composition.ExportMetadata(\"Description\", \"Data vs. Time\")> _\nPublic Class DataTimeChart\n Implements ICharts\n\n Public Sub CreateChart() Implements ICharts.CreateChart\n End Sub\nEnd Class\n\nPublic Interface ICharts\n Sub CreateChart()\nEnd Interface\n\nPublic Class Extensibility\n Public Sub New()\n Dim catalog As New AggregateCatalog()\n\n catalog.Catalogs.Add(New AssemblyCatalog(GetType(Extensibility).Assembly))\n\n 'Create the CompositionContainer with the parts in the catalog\n ChartContainer = New CompositionContainer(catalog)\n\n Try\n ChartContainer.ComposeParts(Me)\n Catch ex As Exception\n Console.WriteLine(ex.ToString)\n End Try\n End Sub\n\n ' must use Lazy otherwise instantiation of Window will hold open app. Otherwise must specify Shutdown Mode of \"Shutdown on Main Window\".\n <ImportMany()> _\n Public Property ChartDescriptions As IEnumerable(Of Lazy(Of ICharts, IDictionary(Of String, Object)))\n\nEnd Class\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21096/" ]
120,858
<p>Is it possible to, for instance, replace and free a TEdit with a subclassed component instantiated (conditionally) at runtime? If so, how and when it should be done? I've tried to set the parent to nil and to call free() in the form constructor and AfterConstruction methods but in both cases I got a runtime error.</p> <hr> <p>Being more specific, I got an Access violation error (EAccessViolation). It seems François is right when he says that freeing components at frame costruction messes with Form controls housekeeping.</p>
[ { "answer_id": 121091, "author": "Loesje", "author_id": 17559, "author_profile": "https://Stackoverflow.com/users/17559", "pm_score": 3, "selected": false, "text": "var Edit2: TEdit;\nbegin\n Edit2 := TEdit.Create(self);\n Edit2.Left := Edit1.Left;\n Edit2.Top := Edit2.Top;\n Edit1.Parent.Insertcontrol(Edit2);\n TWinControl(Edit1.parent).RemoveControl(Edit1);\n Edit1.Free;\nend;\n" }, { "answer_id": 122915, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": true, "text": "function ReplaceControlEx(AControl: TControl; const AControlClass: TControlClass; const ANewName: string; const IsFreed : Boolean = True): TControl;\nbegin\n if AControl = nil then\n begin\n Result := nil;\n Exit;\n end;\n Result := AControlClass.Create(AControl.Owner);\n CloneProperties(AControl, Result);// copy all properties to new control\n // Result.Left := AControl.Left; // or copy some properties manually...\n // Result.Top := AControl.Top;\n Result.Name := ANewName;\n Result.Parent := AControl.Parent; // needed for the InsertControl & RemoveControl magic\n if IsFreed then\n FreeAndNil(AControl);\nend;\n\nfunction ReplaceControl(AControl: TControl; const ANewName: string; const IsFreed : Boolean = True): TControl;\nbegin\n if AControl = nil then\n Result := nil\n else\n Result := ReplaceControlEx(AControl, TControlClass(AControl.ClassType), ANewName, IsFreed);\nend;\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16120/" ]
120,865
<p>Our application has a file format similar to the OpenDocument file format (see <a href="http://en.wikipedia.org/wiki/OpenDocument" rel="noreferrer">http://en.wikipedia.org/wiki/OpenDocument</a>) - i.e. zipped with a manifest file, a thumbnail image, etc.</p> <p>I notice that OpenOffice files have a preview image of the Open Office file as their icons, both in Windows and in Linux. Is there some way to accomplish this for our files: i.e. I want a dynamic icon based on the internal thumbnail.png?</p> <p><strong>Edit 1</strong> Wow, thanks for all the quick answers. <a href="http://library.gnome.org/devel/integration-guide/stable/thumbnailer.html.en" rel="noreferrer">Thumbnailer</a> looks great for the GNOME world. Windows I'll be looking into those links, thanks. As for the comment question: programmatically OR via our installer.</p> <p><strong>Edit 2</strong> Oh, forgot Mac. How about on the Mac? (Sorry Mac lovers!) Also are there any links or info for how OpenOffice does their IconHandler stuff - since ours would be very similar?</p>
[ { "answer_id": 1795641, "author": "gamma", "author_id": 153678, "author_profile": "https://Stackoverflow.com/users/153678", "pm_score": 2, "selected": false, "text": "#include <Cocoa/Cocoa.h>\n#include <Foundation/Foundation.h>\n\nOSStatus GenerateThumbnailForURL(void *thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize)\n{\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n\n /* unzip the thumbnail and put it into an NSData object */\n // Create temporary path and writing handle for extraction\n NSString *tmpPath = [NSTemporaryDirectory() stringByAppendingFormat: [NSString stringWithFormat: @\"%.0f.%@\" , [NSDate timeIntervalSinceReferenceDate] * 1000.0, @\"png\"]];\n [[NSFileManager defaultManager] createFileAtPath: tmpPath contents: [NSData alloc] attributes:nil];\n NSFileHandle *writingHandle = [NSFileHandle fileHandleForWritingAtPath: tmpPath];\n\n\n // Use task to unzip - create command: /usr/bin/unzip -p <pathToFile> <fileToExtract>\n NSTask *unzipTask = [[NSTask alloc] init];\n [unzipTask setLaunchPath: @\"/usr/bin/unzip\"];\n\n // -p -> output to StandardOut, added File to extract, nil to terminate Array\n [unzipTask setArguments: [NSArray arrayWithObjects: @\"-p\", [(NSURL *) url path], @\"Thumbnails/thumbnail.png\", nil]];\n\n // redirect standardOut to writingHandle\n [unzipTask setStandardOutput: writingHandle];\n\n // Unzip - run task\n [unzipTask launch];\n [unzipTask waitUntilExit];\n\n // Read Image Data and remove File\n NSData *thumbnailData = [NSData dataWithContentsOfFile: tmpPath];\n [[NSFileManager defaultManager] removeFileAtPath: tmpPath handler:nil];\n\n\n if ( thumbnailData == nil || [thumbnailData length] == 0 ) {\n // Nothing Found. Don't care.\n [pool release];\n return noErr;\n }\n\n // That is the Size our image should have - create a dictionary too\n CGSize size = CGSizeMake(256, 256);\n NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:\n [NSNumber numberWithInt:size.width],kQLPreviewPropertyWidthKey,\n [NSNumber numberWithInt:size.height],kQLPreviewPropertyHeightKey,\n nil];\n\n // Get CGContext for Thumbnail\n CGContextRef CGContext = QLThumbnailRequestCreateContext(thumbnail, size, TRUE, (CFDictionaryRef)properties);\n if(CGContext) {\n NSGraphicsContext* context = [NSGraphicsContext graphicsContextWithGraphicsPort:(void *)CGContext flipped:size.width > size.height];\n if(context) {\n //These two lines of code are just good safe programming…\n [NSGraphicsContext saveGraphicsState];\n [NSGraphicsContext setCurrentContext:context];\n\n NSBitmapImageRep *thumbnailBitmap = [NSBitmapImageRep imageRepWithData:thumbnailData];\n [thumbnailBitmap draw];\n\n //This line sets the context back to what it was when we're done\n [NSGraphicsContext restoreGraphicsState];\n }\n\n // When we are done with our drawing code QLThumbnailRequestFlushContext() is called to flush the context\n QLThumbnailRequestFlushContext(thumbnail, CGContext);\n\n // Release the CGContext\n CFRelease(CGContext);\n }\n\n [pool release];\n return noErr;\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
120,876
<p>What are the C++ rules for calling the base class constructor from a derived class?</p> <p>For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).</p>
[ { "answer_id": 120916, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 11, "selected": true, "text": "class SuperClass\n{\n public:\n\n SuperClass(int foo)\n {\n // do something with foo\n }\n};\n\nclass SubClass : public SuperClass\n{\n public:\n\n SubClass(int foo, int bar)\n : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.\n {\n // do something with bar\n }\n};\n" }, { "answer_id": 120920, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 5, "selected": false, "text": "class base\n{\n public:\n base (int arg)\n {\n }\n};\n\nclass derived : public base\n{\n public:\n derived () : base (number)\n {\n }\n};\n" }, { "answer_id": 120931, "author": "CR.", "author_id": 20387, "author_profile": "https://Stackoverflow.com/users/20387", "pm_score": 4, "selected": false, "text": "Class2::Class2(string id) : Class1(id) {\n....\n}\n" }, { "answer_id": 120943, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 8, "selected": false, "text": "class Sub : public Base\n{\n Sub(int x, int y)\n : Base(x), member(y)\n {\n }\n Type member;\n};\n" }, { "answer_id": 120955, "author": "Dynite", "author_id": 16177, "author_profile": "https://Stackoverflow.com/users/16177", "pm_score": 3, "selected": false, "text": "CDerived::CDerived()\n: CBase(...), iCount(0) //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)\n {\n //construct body\n }\n" }, { "answer_id": 121024, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 6, "selected": false, "text": "\nclass A : public B\n{\npublic:\n A(int a, int b, int c);\nprivate:\n int b_, c_;\n};\n" }, { "answer_id": 24765899, "author": "JayS", "author_id": 1812942, "author_profile": "https://Stackoverflow.com/users/1812942", "pm_score": 4, "selected": false, "text": "using namespace std;\n\nclass Base\n{\n public:\n Base(int a=1) : _a(a) {}\n\n protected:\n int _a;\n};\n\nclass Derived : public Base\n{\n public:\n Derived() {}\n\n void printit() { cout << _a << endl; }\n};\n\nint main()\n{\n Derived d;\n d.printit();\n return 0;\n}\n" }, { "answer_id": 62698814, "author": "Markus Dutschke", "author_id": 7128154, "author_profile": "https://Stackoverflow.com/users/7128154", "pm_score": 2, "selected": false, "text": "std::string" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4465/" ]
120,886
<p>Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by</p> <pre><code>infinite = itertools.cycle([[1,2,3]]) </code></pre> <p>What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc. In the example above it would return <code>1,2,3,1,2,3,...</code>. The iterator is infinite, so <code>itertools.chain(*infinite)</code> will not work.</p> <h3>Related</h3> <ul> <li><a href="https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li> </ul>
[ { "answer_id": 120905, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": false, "text": "(item for it in infinite for item in it)\n" }, { "answer_id": 120910, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 7, "selected": true, "text": "itertools.chain.from_iterable" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12166/" ]
120,889
<p>When running all my tests in Eclipse (Eclipse 3.4 'Ganymede'), one test is listed under "Unrooted Tests". I'm using Junit 3.8 and this particular test extends TestCase. I do not see any difference between this test and the other tests. I don't remember seeing this occur in Eclipse 3.3 (Europa).</p> <p>Clarification:</p> <p>We haven't moved to JUnit 4.0 yet, so we are not using annotations. I also googled and it seemed like most people were having issues with JUnit 4, but I did not see any solutions. At this point the test passes both locally and in CruiseControl so I'm not overly concerned, but curious.</p> <p>When I first saw this, though, it was on a failing test that only failed when run with other tests. This led me down the rabbit hole looking for a solution to the "Unrooted" issue that I never found. Eventually I found the culprit in another test that was not properly tearing down.</p> <p>I agree, it does seem like an Eclipse issue.</p>
[ { "answer_id": 803487, "author": "ra9r", "author_id": 88916, "author_profile": "https://Stackoverflow.com/users/88916", "pm_score": 4, "selected": false, "text": "import static org.junit.Assert.*; // Notice the use of \"static\" here\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class MyTests { // Notice we don't extent TestCases anymore\n\n @Before\n public void setUp() { // Note: It is not required to call this setUp()\n // ...\n }\n\n @Test\n public void doSomeTest() { // Note: method need not be called \"testXXX\"\n // ...\n assertTrue(1 == 1);\n }\n}\n" }, { "answer_id": 4693055, "author": "Jose Manuel Prieto", "author_id": 329631, "author_profile": "https://Stackoverflow.com/users/329631", "pm_score": 0, "selected": false, "text": "import static org.junit.Assert.*;\n" }, { "answer_id": 11220559, "author": "Kenny Cason", "author_id": 403682, "author_profile": "https://Stackoverflow.com/users/403682", "pm_score": 1, "selected": false, "text": "import org.junit.Test;\n\npublic class MyTest {\n\n @Test\n public void someMethod(String param) {\n // stuff\n }\n\n}\n" }, { "answer_id": 14318219, "author": "Tobber", "author_id": 722929, "author_profile": "https://Stackoverflow.com/users/722929", "pm_score": 0, "selected": false, "text": "@BeforeClass" }, { "answer_id": 22900958, "author": "Nuno77", "author_id": 3441836, "author_profile": "https://Stackoverflow.com/users/3441836", "pm_score": 1, "selected": false, "text": "@Test\n public void testOne() { // ...\n assertTrue(1 == 1);\n }" }, { "answer_id": 25029341, "author": "Neil", "author_id": 747456, "author_profile": "https://Stackoverflow.com/users/747456", "pm_score": 0, "selected": false, "text": "@Test \npublic void test() {\n // ... assertTrue(1 == 1); \n}\n" }, { "answer_id": 30382422, "author": "Stubbs", "author_id": 1013395, "author_profile": "https://Stackoverflow.com/users/1013395", "pm_score": 0, "selected": false, "text": "static" }, { "answer_id": 42928458, "author": "Fran G Aparicio", "author_id": 5060742, "author_profile": "https://Stackoverflow.com/users/5060742", "pm_score": 0, "selected": false, "text": "@Test\n@Transactional\n@Rollback(true)\npublic void testInsertCustomer() { \n (...)\n}\n" }, { "answer_id": 52895455, "author": "rakwaht", "author_id": 5226835, "author_profile": "https://Stackoverflow.com/users/5226835", "pm_score": 0, "selected": false, "text": "@AfterClass" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
120,900
<p>I'm working on databases that have moving tables auto-generated by some obscure tools. By the way, we have to track information changes in the table via some triggers. And, of course, it occurs that some changes in the table structure broke some triggers, by removing a column or changing its type, for example.</p> <p>So, the question is: Is there a way to query the Oracle metadata to check is some triggers are broken, in order to send a report to the support team? </p> <p>The user_triggers give all the triggers and tells if they are enable or not, but does not indicate if they are still valid.</p>
[ { "answer_id": 120911, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 5, "selected": true, "text": "SELECT *\nFROM ALL_OBJECTS\nWHERE OBJECT_NAME = trigger_name\nAND OBJECT_TYPE = 'TRIGGER'\nAND STATUS <> 'VALID'\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396/" ]
120,907
<p>This is a scenario I've seen in multiple places over the years; I'm wondering if anyone else has run across a better solution than I have...</p> <p>My company sells a relatively small number of products, however the products we sell are highly specialized (i.e. in order to select a given product, a significant number of details must be provided about it). The problem is that while the <em>amount</em> of detail required to choose a given product is relatively constant, the <em>kinds</em> of details required vary greatly between products. For instance: </p> <p>Product X might have identifying characteristics like (hypothetically) </p> <ul> <li>'Color',</li> <li>'Material'</li> <li>'Mean Time to Failure'</li> </ul> <p>but Product Y might have characteristics </p> <ul> <li>'Thickness', </li> <li>'Diameter'</li> <li>'Power Source'</li> </ul> <p>The problem (one of them, anyway) in creating an order system that utilizes both Product X and Product Y is that an Order Line has to refer, at some point, to what it is "selling". Since Product X and Product Y are defined in two different tables - and denormalization of products using a wide table scheme is not an option (the product definitions are quite deep) - it's difficult to see a clear way to define the Order Line in such a way that order entry, editing and reporting are practical.</p> <hr> <p><strong>Things I've Tried In the Past</strong></p> <ul> <li>Create a parent table called 'Product' with columns common to Product X and Product Y, then using 'Product' as the reference for the OrderLine table, and creating a FK relationship with 'Product' as the primary side between the tables for Product X and Product Y. This basically places the 'Product' table as the parent of both OrderLine and all the disparate product tables (e.g. Products X and Y). It works fine for order entry, but causes problems with order reporting or editing since the 'Product' record has to track what kind of product it is in order to determine how to join 'Product' to its more detailed child, Product X or Product Y. <strong>Advantages</strong>: key relationships are preserved. <strong>Disadvantages</strong>: reporting, editing at the order line/product level.</li> <li>Create 'Product Type' and 'Product Key' columns at the Order Line level, then use some CASE logic or views to determine the customized product to which the line refers. This is similar to item (1), without the common 'Product' table. I consider it a more "quick and dirty" solution, since it completely does away with foreign keys between order lines and their product definitions. <strong>Advantages</strong>: quick solution. <strong>Disadvantages</strong>: same as item (1), plus lost RI.</li> <li>Homogenize the product definitions by creating a common header table and using key/value pairs for the customized attributes (OrderLine [n] &lt;- [1] Product [1] &lt;- [n] ProductAttribute). <strong>Advantages</strong>: key relationships are preserved; no ambiguity about product definition. <strong>Disadvantages</strong>: reporting (retrieving a list of products with their attributes, for instance), data typing of attribute values, performance (fetching product attributes, inserting or updating product attributes etc.)</li> </ul> <p>If anyone else has tried a different strategy with more success, I'd sure like to hear about it.</p> <p>Thank you.</p>
[ { "answer_id": 121044, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 2, "selected": false, "text": "Table Product ( id PK, name, price, units_per_package)\nTable Product_Attribs (id FK ref Product, AttribName, AttribValue)\n" }, { "answer_id": 121096, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": false, "text": "Attribute(attribute_id, description, is_listed) \n-- contains values like \"colour\", \"width\", \"power source\", etc. \n-- \"is_listed\" tells us if we can get a list of valid values: \n\nAttributeValue(attribute_id, value)\n-- lists of valid values for different attributes. \n\nProduct (product_id, description)\n\nProductAttribute (product_id, attribute_id) \n-- tells us which attributes apply to which products\n\nOrder (order_id, etc)\n\nOrderLine (order_id, order_line_id, product_id)\n\nOrderLineProductAttributeValue (order_line_id, attribute_id, value)\n-- tells us things like: order line 999 has \"colour\" of \"blue\"\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7388/" ]
120,908
<p>I try to open and excel reference in LabVIEW and then close it after sometime. But the LabVIEW keeps holding the reference and does not release it unless I close the VI. Why is this happening? Is there anyway to force it to release the Reference?</p> <p>I am checking the error out for any errors. But it is not throwing up any errors.</p>
[ { "answer_id": 121044, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 2, "selected": false, "text": "Table Product ( id PK, name, price, units_per_package)\nTable Product_Attribs (id FK ref Product, AttribName, AttribValue)\n" }, { "answer_id": 121096, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": false, "text": "Attribute(attribute_id, description, is_listed) \n-- contains values like \"colour\", \"width\", \"power source\", etc. \n-- \"is_listed\" tells us if we can get a list of valid values: \n\nAttributeValue(attribute_id, value)\n-- lists of valid values for different attributes. \n\nProduct (product_id, description)\n\nProductAttribute (product_id, attribute_id) \n-- tells us which attributes apply to which products\n\nOrder (order_id, etc)\n\nOrderLine (order_id, order_line_id, product_id)\n\nOrderLineProductAttributeValue (order_line_id, attribute_id, value)\n-- tells us things like: order line 999 has \"colour\" of \"blue\"\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13440/" ]
120,914
<p>I want my WPF application to be skinnable, by applying a certain XAML template, and the changes to be application wide, even for dynamic controls or controls that aren't even in the visual/logical tree. </p> <p>What can I use to accomplish this type of functionality? Are there any good resources or tutorials that show how this specific task can be done?</p>
[ { "answer_id": 126578, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 2, "selected": false, "text": " <Application.Resources>\n <Style x:Key=\"{x:Type Button}\" TargetType=\"{x:Type Button}\">\n <Setter Property=\"Button.Background\" Value=\"CornflowerBlue\"/>\n <Setter Property=\"Button.Template\">\n <Setter.Value>\n <ControlTemplate x:Name=\"MyTemplate\">\n ...\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n</Application.Resources>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
120,917
<p>How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on <code>D:\temp\dbFolder</code>. How to do this?</p>
[ { "answer_id": 120940, "author": "Leah", "author_id": 5506, "author_profile": "https://Stackoverflow.com/users/5506", "pm_score": 6, "selected": true, "text": "USE [master]\nGO\n\n CREATE DATABASE [AdventureWorks] ON PRIMARY \n ( NAME = N'AdventureWorks_Data', FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\AdventureWorks_Data.mdf' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )\n LOG ON \n ( NAME = N'AdventureWorks_Log', FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\AdventureWorks_Log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB )\n GO\n" }, { "answer_id": 120946, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 4, "selected": false, "text": "USE master\nGO\nCREATE DATABASE Sales\nON \n( NAME = Sales_dat,\n FILENAME = 'c:\\program files\\microsoft sql server\\mssql\\data\\saledat.mdf',\n SIZE = 10,\n MAXSIZE = 50,\n FILEGROWTH = 5 )\nLOG ON\n( NAME = 'Sales_log',\n FILENAME = 'c:\\program files\\microsoft sql server\\mssql\\data\\salelog.ldf',\n SIZE = 5MB,\n MAXSIZE = 25MB,\n FILEGROWTH = 5MB )\nGO\n" }, { "answer_id": 17642564, "author": "landrew", "author_id": 1621021, "author_profile": "https://Stackoverflow.com/users/1621021", "pm_score": 2, "selected": false, "text": "USE master; \nGO \nCREATE DATABASE TestDB1 \nON ( NAME = Sales_dat, FILENAME = 'D:\\temp\\dbFolder\\TestDB1.mdf') \nLOG ON ( NAME = Sales_log, FILENAME = 'D:\\temp\\dbFolder\\TestDB1.ldf'); \nGO\n" }, { "answer_id": 18658543, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 0, "selected": false, "text": "CREATE DATABASE [ADestinyDb] CONTAINMENT = NONE ON PRIMARY \n( NAME = N'ADestinyDb', \n FILENAME = N'D:\\temp\\dbFolder\\ADestinyDb.mdf' , \n SIZE = 3136 KB , MAXSIZE = UNLIMITED, \n FILEGROWTH = 1024 KB )\nLOG ON \n( NAME = N'ADestinyDb_log', \n FILENAME = N'D:\\temp\\dbFolder\\_log.ldf' , \n SIZE = 832KB , MAXSIZE = 2048 GB , FILEGROWTH = 10 %)\n" }, { "answer_id": 21545332, "author": "Avinash", "author_id": 1251692, "author_profile": "https://Stackoverflow.com/users/1251692", "pm_score": 0, "selected": false, "text": " USE master\nCREATE DATABASE [faltu] ON PRIMARY \n( NAME = N'faltu', FILENAME = N'D:\\temp\\dbFolder\\faltu.mdf' , SIZE = 2048KB , FILEGROWTH = 1024KB )\n LOG ON \n( NAME = N'faltu_log', FILENAME = N'D:\\temp\\dbFolder\\faltu_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)\n" }, { "answer_id": 41548078, "author": "Brett Bieker", "author_id": 7394310, "author_profile": "https://Stackoverflow.com/users/7394310", "pm_score": 2, "selected": false, "text": "MKDIR \"E:\\MSSQL\\DATA\\DB\"\nMKDIR \"E:\\MSSQL\\DATA\\Logs\"\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
120,926
<p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p> <p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
[ { "answer_id": 121126, "author": "Rod Daunoravicius", "author_id": 20989, "author_profile": "https://Stackoverflow.com/users/20989", "pm_score": 0, "selected": false, "text": ":set expandtab" }, { "answer_id": 144096, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 5, "selected": false, "text": "def foo():\n x = some_function_with_lots_of_args(foo, bar, baz,\n xyzzy, blah)\n" }, { "answer_id": 15076562, "author": "Gerald Senarclens de Grancy", "author_id": 104659, "author_profile": "https://Stackoverflow.com/users/104659", "pm_score": 0, "selected": false, "text": "foo = long_function_name(var_one, var_two,\n var_three, var_four)\n\n# the same for lists\na_long_list = [1,\n 2,\n # ...\n 79]\n\n# or dictionaries\na_dict = {\"a_key\": \"a_value\",\n \"another_key\": \"another_value\"}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4834/" ]
120,928
<p>I have a web part that I've developed, and if I manually install the web part it is fine.</p> <p>However when I have packaged the web part following the instructions on this web site as a guide: <a href="http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html" rel="noreferrer">http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html</a></p> <p>I get this error in the log files:</p> <pre><code>09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 8l4d Monitorable Error importing WebPart. Cannot import Project Filter. 09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High Failed to add webpart http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(... 09/23/2008 14:13:03.67* w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High ...String eventArgument) </code></pre> <p>The pertinent bit is:</p> <pre><code>http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) </code></pre> <p>And that's accompanied by a rather terse error message: "Cannot import web part".</p> <p>I have checked and my .dll is registered as safe, it is in the GAC, the feature is activated, and the web parts appear in the web part library with all of the correct properties showing that the webpart files were read successfully.</p> <p>Everything appears to be in place, yet I get that error and little explanation from SharePoint of how to resolve it.</p> <p>Any help finding a solution is appreciated.</p>
[ { "answer_id": 121883, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<webParts>\n <webPart xmlns=\"http://schemas.microsoft.com/WebPart/v3\">\n <metaData>\n <!--\n The following Guid is used as a reference to the web part class, \n and it will be automatically replaced with actual type name at deployment time.\n -->\n <type name=\"7F8C4D34-6311-4f22-87B4-A221FA8735BA\" />\n <importErrorMessage>Cannot import Project Filter.</importErrorMessage>\n </metaData>\n <data>\n <properties>\n <property name=\"Title\" type=\"string\">Project Filter</property>\n <property name=\"Description\" type=\"string\">Provides a list of Projects that can be used to Filter other Web Parts.</property>\n </properties>\n </data>\n </webPart>\n</webParts>\n" }, { "answer_id": 449535, "author": "Smxyhd", "author_id": 55728, "author_profile": "https://Stackoverflow.com/users/55728", "pm_score": 1, "selected": false, "text": "namespace ProjectInfo\n....\n public class ProjectInfo:System.Web.UI.WebControls.WebParts.Web.part\n {\n .....\n private SPWeb _spWeb;\n private SPList _spList;\n private string _listName = \"ProjectDocs\";\n ......\n }\npublic ProjectInfo()\n {\n .....\n _spWeb = SPContext.Current.Web;\n //It show me a error here when i trace the code\n _spList = _spWeb.Lists[_listName]; \n .....\n }\n" }, { "answer_id": 456810, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "===========================================================================\nError importing WebPart. Cannot import ........ Web Part.\nFailed to add webpart \nException Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import ... Web Part. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) \n===========================================================================\n" }, { "answer_id": 677930, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public class DerivedWebPart : BaseWebPart\n" }, { "answer_id": 4235161, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "CLSCompliannt" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
120,936
<p>I can add custom version strings to a C++ DLL in Visual Studio by editing the .rc file by hand. For example, if I add to the VersionInfo section of the .rc file</p> <pre><code>VALUE "BuildDate", "2008/09/19 15:42:52" </code></pre> <p>Then that date is visible in the file explorer, in the DLL's properties, under the Version tab.</p> <p>Can I do the same for a C# DLL? Not just for build date, but for other version information (such as source control information)</p> <p>UPDATE: I think there may be a way to do this by embedding a windows resource, so I've <a href="https://stackoverflow.com/questions/200485">asked how to do that</a>.</p>
[ { "answer_id": 120958, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 2, "selected": false, "text": "[assembly: System.Reflection.AssemblyInformationalVersion(\"whatever you want\")]\n" }, { "answer_id": 122055, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 3, "selected": false, "text": "[assembly: CustomResource(\"Build Date\", \"12/12/2012\")]\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
120,937
<p>After reading the Test-and-Set <a href="http://en.wikipedia.org/wiki/Test-and-set" rel="noreferrer">Wikipedia entry</a>, I am still left with the question "What would a Test-and-Set be used for?"</p> <p>I realize that you can use it to implement Mutex (as described in wikipedia), but what other uses does it have?</p>
[ { "answer_id": 120999, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "a = a + 1" }, { "answer_id": 71088489, "author": "Chen Li", "author_id": 6949852, "author_profile": "https://Stackoverflow.com/users/6949852", "pm_score": 0, "selected": false, "text": "void spin_lock(struct spinlock *lock)\n{\n while (test_and_set(&lock->locked));\n}\n" }, { "answer_id": 71219219, "author": "Aleksei Marashov", "author_id": 7338234, "author_profile": "https://Stackoverflow.com/users/7338234", "pm_score": 0, "selected": false, "text": "TLS <destination> <origin>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
120,941
<p>I am building a small website for fun/learning using a fairly standard Web/Service/Data Access layered design.</p> <p>For the Data Access Layer, what is the best way to handle creating Connection objects to call my SQL stored procedures and why? Bearing in mind I am writing a lot of the code by hand (I know I could be using Hibernate etc to do a lot of this for me)...</p> <p>1) Should I create one static instance of the Connection and run all my querys through it or will this cause concurrency problems?</p> <p>2) Should I create a Connection instance per database call and accept the performance overhead? (I will look into connection pooling at a later date if this is the case)</p>
[ { "answer_id": 120999, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "a = a + 1" }, { "answer_id": 71088489, "author": "Chen Li", "author_id": 6949852, "author_profile": "https://Stackoverflow.com/users/6949852", "pm_score": 0, "selected": false, "text": "void spin_lock(struct spinlock *lock)\n{\n while (test_and_set(&lock->locked));\n}\n" }, { "answer_id": 71219219, "author": "Aleksei Marashov", "author_id": 7338234, "author_profile": "https://Stackoverflow.com/users/7338234", "pm_score": 0, "selected": false, "text": "TLS <destination> <origin>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
120,951
<p>I'd like to know do I normalize a URL in python. </p> <p>For example, If I have a url string like : "<a href="http://www.example.com/foo" rel="noreferrer">http://www.example.com/foo</a> goo/bar.html"</p> <p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
[ { "answer_id": 120959, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "from urllib.parse import urlparse, urlunparse, quote\ndef myquote(url):\n parts = urlparse(url)\n return urlunparse(parts._replace(path=quote(parts.path)))\n\n>>> myquote('https://www.example.com/~user/with space/index.html?a=1&b=2')\n'https://www.example.com/~user/with%20space/index.html?a=1&b=2'\n" }, { "answer_id": 120971, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": false, "text": "urllib.quote" }, { "answer_id": 121017, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 6, "selected": false, "text": "werkzeug.urls" }, { "answer_id": 845595, "author": "Oleg Sakharov", "author_id": 87057, "author_profile": "https://Stackoverflow.com/users/87057", "pm_score": 6, "selected": false, "text": " # percent encode url, fixing lame server errors for e.g, like space\n # within url paths.\n fullurl = quote(fullurl, safe=\"%/:=&?~#+!$,;'@()*[]\")\n" }, { "answer_id": 24203504, "author": "WKPlus", "author_id": 552942, "author_profile": "https://Stackoverflow.com/users/552942", "pm_score": 1, "selected": false, "text": "fullurl = quote(fullurl, safe=\"%/:=&?~#+!$,;'@()*[]\")" }, { "answer_id": 42610024, "author": "Hélder Lima", "author_id": 1699147, "author_profile": "https://Stackoverflow.com/users/1699147", "pm_score": 2, "selected": false, "text": "import urllib.parse\n\nurllib.parse.quote([your_url], \"\\./_-:\")\n" }, { "answer_id": 73066013, "author": "Granitosaurus", "author_id": 3737009, "author_profile": "https://Stackoverflow.com/users/3737009", "pm_score": 0, "selected": false, "text": "w3lib.url.canonicalize_url" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
120,952
<p>I have an SP that takes 10 seconds to run about 10 times (about a second every time it is ran). The platform is asp .net, and the server is SQL Server 2005. I have indexed the table (not on the PK also), and that is not the issue. Some caveats:</p> <ul> <li>usp_SaveKeyword is not the issue. I commented out that entire SP and it made not difference. </li> <li>I set @SearchID to 1 and the time was significantly reduced, only taking about 15ms on average for the transaction. </li> <li>I commented out the entire stored procedure except the insert into tblSearches and strangely it took more time to execute. </li> </ul> <p>Any ideas of what could be going on? </p> <pre><code>set ANSI_NULLS ON go ALTER PROCEDURE [dbo].[usp_NewSearch] @Keyword VARCHAR(50), @SessionID UNIQUEIDENTIFIER, @time SMALLDATETIME = NULL, @CityID INT = NULL AS BEGIN SET NOCOUNT ON; IF @time IS NULL SET @time = GETDATE(); DECLARE @KeywordID INT; EXEC @KeywordID = usp_SaveKeyword @Keyword; PRINT 'KeywordID : ' PRINT @KeywordID DECLARE @SearchID BIGINT; SELECT TOP 1 @SearchID = SearchID FROM tblSearches WHERE SessionID = @SessionID AND KeywordID = @KeywordID; IF @SearchID IS NULL BEGIN INSERT INTO tblSearches (KeywordID, [time], SessionID, CityID) VALUES (@KeywordID, @time, @SessionID, @CityID) SELECT Scope_Identity(); END ELSE BEGIN SELECT @SearchID END END </code></pre>
[ { "answer_id": 121094, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": true, "text": "top 1 @SearchID" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
120,957
<p>What features of C++ should be avoided in embedded systems?</p> <p>Please classify the answer by reason such as:</p> <ul> <li>memory usage </li> <li>code size</li> <li>speed</li> <li>portability</li> </ul> <p>EDIT: Lets' use an ARM7TDMI with 64k ram as a target to control the scope of the answers.</p>
[ { "answer_id": 121633, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 1, "selected": false, "text": "// foo.h\ntemplate <typename T> void foo () { /* some relatively large definition */ }\n\n// b1.cc\n#include \"foo.h\"\nvoid b1 () { foo<int> (); }\n\n// b2.cc\n#include \"foo.h\"\nvoid b2 () { foo<int> (); }\n\n// b3.cc\n#include \"foo.h\"\nvoid b3 () { foo<int> (); }\n" }, { "answer_id": 125441, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "ABORT" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
120,966
<p>I was writing a (seemingly) straight-forward SQL snippet that drops a column after it makes sure the column exists.<br> The problem: if the column does NOT exist, the code <em>inside</em> the IF clause complains that it can't find the column! Well, <em>doh</em>, that's why it's inside the IF clause!<br> So my question is, why does a piece of code that shouldn't be executed give errors?</p> <p>Here's the snippet:</p> <pre><code>IF exists (select * from syscolumns WHERE id=object_id('Table_MD') and name='timeout') BEGIN ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout END GO </code></pre> <p>...and here's the error:</p> <p><code>Error executing SQL script [...]. Invalid column name 'timeout'</code></p> <p>I'm using Microsoft SQL Server 2005 Express Edition.</p>
[ { "answer_id": 120985, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 4, "selected": true, "text": "IF exists (select * from syscolumns\n WHERE id=object_id('Table_MD') and name='timeout')\nBEGIN\n DECLARE @SQL nvarchar(1000)\n SET @SQL = N'ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout'\n EXEC sp_executesql @SQL\nEND\nGO\n" }, { "answer_id": 121070, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 0, "selected": false, "text": "ALTER ... DROP ..." } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
120,977
<p>I understand the mantra of "don't roll your own" when it comes to site security frameworks.</p> <p>For most cases anyway.</p> <p>I'm going to be collaborating on a site that integrates text-messaging into the system.</p> <p>I'd like to use an existing, well-tested security framework to protect the users data, but I need it to also protect a users phone number as well.</p> <p>I wouldn't want to be the one responsible for a list of users cell phone numbers getting jacked and spammed.</p> <p>What suggestions can the community offer?</p>
[ { "answer_id": 4090666, "author": "aek", "author_id": 496368, "author_profile": "https://Stackoverflow.com/users/496368", "pm_score": 1, "selected": false, "text": "$context = new substrate_Context(\n './path/to/hole-security/hole-security-config.php'\n);\n\n$context->execute();\n\n$hole_Security = $context->get('hole_FilterChainProxy' );\n$hole_Security->doFilter();\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9094/" ]
120,997
<p>I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags?</p> <p>For example, when you create an <code>asp:repeater</code> you can add a nested tag for <code>itemtemplate</code>.</p>
[ { "answer_id": 121007, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 5, "selected": true, "text": "<Abc:CustomControlUno runat=\"server\" ID=\"Control1\">\n <Children>\n <Abc:Control1Child IntegerProperty=\"1\" />\n </Children>\n</Abc:CustomControlUno>\n" }, { "answer_id": 1102226, "author": "Guðmundur H", "author_id": 73256, "author_profile": "https://Stackoverflow.com/users/73256", "pm_score": 3, "selected": false, "text": "<wc:PriceInfo runat=\"server\" ID=\"PriceInfo\">\n <IfDiscount>\n You don't have a discount.\n </IfDiscount>\n <IfNotDiscount>\n Lucky you, <b>you have a discount!</b>\n </IfNotDiscount>\n</wc:PriceInfo>\n" }, { "answer_id": 24000778, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 2, "selected": false, "text": "ITemplate" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/120997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11508/" ]
121,000
<p>I'm trying to create an Extension Method for MVC's htmlHelper. The purpose is to enable or disable an ActionLink based on the AuthorizeAttribute set on the controller/action. Borrowing from the <a href="http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx" rel="nofollow noreferrer">MVCSitemap</a><br> code that Maarten Balliauw created, I wanted to validate the user's permissions against the controller/action before deciding how to render the actionlink. When I try to get the MvcHandler, I get a null value. Is there a better way to the the attributes for the controller/action?</p> <p>Here is the code for the extension method:</p> <pre><code>public static class HtmlHelperExtensions { public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller) { //simplified for brevity if (IsAccessibleToUser(action, controller)) { return htmlHelper.ActionLink(linkText, action,controller); } else { return String.Format("&lt;span&gt;{0}&lt;/span&gt;",linkText); } } public static bool IsAccessibleToUser(string action, string controller) { HttpContext context = HttpContext.Current; MvcHandler handler = context.Handler as MvcHandler; IController verifyController = ControllerBuilder .Current .GetControllerFactory() .CreateController(handler.RequestContext, controller); object[] controllerAttributes = verifyController.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true); object[] actionAttributes = verifyController.GetType().GetMethod(action).GetCustomAttributes(typeof(AuthorizeAttribute), true); if (controllerAttributes.Length == 0 &amp;&amp; actionAttributes.Length == 0) return true; IPrincipal principal = handler.RequestContext.HttpContext.User; string roles = ""; string users = ""; if (controllerAttributes.Length &gt; 0) { AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (actionAttributes.Length &gt; 0) { AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (string.IsNullOrEmpty(roles) &amp;&amp; string.IsNullOrEmpty(users) &amp;&amp; principal.Identity.IsAuthenticated) return true; string[] roleArray = roles.Split(','); string[] usersArray = users.Split(','); foreach (string role in roleArray) { if (role != "*" &amp;&amp; !principal.IsInRole(role)) return false; } foreach (string user in usersArray) { if (user != "*" &amp;&amp; (principal.Identity.Name == "" || principal.Identity.Name != user)) return false; } return true; } } </code></pre>
[ { "answer_id": 121353, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 0, "selected": false, "text": "<%= this.SecurityLink(text, demandRole, controller, action, values) %>" }, { "answer_id": 227890, "author": "Robert Dean", "author_id": 3396, "author_profile": "https://Stackoverflow.com/users/3396", "pm_score": 3, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Security.Principal;\nusing System.Web.Routing;\nusing System.Web.Mvc;\nusing System.Collections;\nusing System.Reflection;\nnamespace System.Web.Mvc.Html\n{\n public static class HtmlHelperExtensions\n {\n public static string SecurityTrimmedActionLink(\n this HtmlHelper htmlHelper,\n string linkText,\n string action,\n string controller)\n {\n return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false);\n }\n public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, bool showDisabled)\n {\n if (IsAccessibleToUser(action, controller))\n {\n return htmlHelper.ActionLink(linkText, action, controller);\n }\n else\n {\n return showDisabled ? String.Format(\"<span>{0}</span>\", linkText) : \"\";\n }\n }\n public static bool IsAccessibleToUser(string actionAuthorize, string controllerAuthorize)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n GetControllerType(controllerAuthorize);\n Type controllerType = GetControllerType(controllerAuthorize);\n var controller = (IController)Activator.CreateInstance(controllerType);\n ArrayList controllerAttributes = new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true));\n ArrayList actionAttributes = new ArrayList();\n MethodInfo[] methods = controller.GetType().GetMethods();\n foreach (MethodInfo method in methods)\n {\n object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);\n if ((attributes.Length == 0 && method.Name == actionAuthorize) || (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == actionAuthorize))\n {\n actionAttributes.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));\n }\n }\n if (controllerAttributes.Count == 0 && actionAttributes.Count == 0)\n return true;\n\n IPrincipal principal = HttpContext.Current.User;\n string roles = \"\";\n string users = \"\";\n if (controllerAttributes.Count > 0)\n {\n AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n if (actionAttributes.Count > 0)\n {\n AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n\n if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)\n return true;\n\n string[] roleArray = roles.Split(',');\n string[] usersArray = users.Split(',');\n foreach (string role in roleArray)\n {\n if (role == \"*\" || principal.IsInRole(role))\n return true;\n }\n foreach (string user in usersArray)\n {\n if (user == \"*\" && (principal.Identity.Name == user))\n return true;\n }\n return false;\n }\n\n public static Type GetControllerType(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n foreach (Type type in assembly.GetTypes())\n {\n if (type.BaseType.Name == \"Controller\" && (type.Name.ToUpper() == (controllerName.ToUpper() + \"Controller\".ToUpper())))\n {\n return type;\n }\n }\n return null;\n }\n }\n}\n" }, { "answer_id": 32997392, "author": "viggity", "author_id": 4572, "author_profile": "https://Stackoverflow.com/users/4572", "pm_score": 0, "selected": false, "text": "[Authorize(Roles = \"SuperAdmin,Executives\")]\npublic class SomeController() {\n [Authorize(Roles = \"Accounting\")] \n public ActionResult Stuff() {\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/121000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3396/" ]