qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
201,355
<p>I have a web application which provides Excel files via IE 7. It requests the files with an HTTP GET from a URL which returns the data with a content type of 'application/vnd.ms-excel'. It then opens the spreadsheets in an IFrame.</p> <p>This all works fine unless Excel is already open when a spreadsheet is downloaded. In this case it is still displayed correctly but reuses the instance of Excel which is open. When the IFrame is closed, Excel hangs. Excel only becomes unlocked if the user logs out of the web application or if they download a file of a different type.</p> <p>I've tried turning on the 'Ignore other applications' setting under Tools | Options | General but it didn't solve the problem.</p> <p>I've also tried following the steps in <a href="https://stackoverflow.com/questions/213110/make-excel-2003-open-spreadsheets-in-new-instances/213187#213187">this answer</a> (as the <a href="http://www.drewery.net/blog/2006/08/29/utilising-dual-monitors-with-microsoft-excel-2003/" rel="nofollow noreferrer">linked reference</a> says 'This issue has been addressed in Excel 2007 beta 2.') with no luck.</p> <p>Is there some kind of 'disposal' step which I'm not currently doing which would prevent Excel from hanging?</p> <p>Versions:</p> <p>Excel 2003 (11.8220.8221) SP3</p> <p>IE 7.0.5730.11 (Update Versions: 0)</p>
[ { "answer_id": 495387, "author": "Matthew Murdoch", "author_id": 4023, "author_profile": "https://Stackoverflow.com/users/4023", "pm_score": 2, "selected": true, "text": "response.setHeader(\"Content-Disposition\", \n \"attachment; filename=\\\"\" + filename + \"\\\"\");\n Content-Disposition" }, { "answer_id": 497100, "author": "Robert Vuković", "author_id": 438025, "author_profile": "https://Stackoverflow.com/users/438025", "pm_score": 1, "selected": false, "text": "\nResponse.Clear();\nResponse.Buffer = true;\n\nResponse.AppendHeader(\"Content-Disposition\", \"attachment; filename=export.csv\");\nResponse.Cache.SetCacheability(HttpCacheability.Private);\nResponse.Cache.SetExpires(DateTime.MinValue);\nResponse.Cache.SetLastModified(DateTime.Now);\nResponse.Cache.SetMaxAge(new TimeSpan(1));\nResponse.ContentType = \"text/csv\";\n\nResponse.ContentEncoding = System.Text.Encoding.Unicode;\n\n...\n//Some writing to the Response.OutputStream\n...\n\nResponse.Flush();\n\n//I am not sure about the following line:\nResponse.End(); \n\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
201,359
<p>int l = strlen(s);</p> <p>warning C4244: '=' : conversion from '__w64 int' to 'int', possible loss of data</p> <p>I need to replace strlen with an inline function int l = new_strlen(s);</p> <p>But how do I portably get the result of the strlen into the int without a warning, and without using pragmas? I can guarantee there aren't more than 2 billion characters in my string!</p> <p>All the obvious things like reinterpret_cast, static_cast also produce errors or warnings.</p> <p>EDIT: Argh. a c-style cast: (int) does work. I had been convinced that it did not.</p>
[ { "answer_id": 201373, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "int i = (int) strlen(s);\n" }, { "answer_id": 201394, "author": "Igor Semenov", "author_id": 11401, "author_profile": "https://Stackoverflow.com/users/11401", "pm_score": 3, "selected": false, "text": "const char * str = \"Hello\";\nint len = static_cast< int >( strlen( str ) );\nreturn len;\n" }, { "answer_id": 201560, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 1, "selected": false, "text": "/Wp64 PtrToUlong() const char* p = \"abc\";\nunsigned int u = reinterpret_cast<unsigned int>(p);\n const char* p = \"abc\";\nunsigned int u = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(p));\n size_t int const char* s = \"abcdef\";\nint l = static_cast<int>(static_cast<intptr_t>(strlen(s)));\n /Wp64 __w64 /Wp64" }, { "answer_id": 201692, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 1, "selected": false, "text": "#pragma warning( suppress : 6001 ) \narr[i+1] = 0; // Warning 6001 is suppressed\nj++; // Warning 6001 is reported\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
201,368
<p>Not of the site collection itself, but the individual SPWeb's.</p>
[ { "answer_id": 201393, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 3, "selected": false, "text": "private long GetWebSize(SPWeb web)\n{\n long total = 0;\n\n foreach (SPFolder folder in web.Folders)\n {\n total += GetFolderSize(folder);\n }\n\n foreach (SPWeb subweb in web.Webs)\n {\n total += GetWebSize(subweb);\n subweb.Dispose();\n }\n\n return total;\n}\n" }, { "answer_id": 24517075, "author": "JasonV", "author_id": 658944, "author_profile": "https://Stackoverflow.com/users/658944", "pm_score": 0, "selected": false, "text": "private long GetFolderSize(SPFolder folder)\n{\n long folderSize = 0;\n\n foreach (SPFile file in folder.Files)\n {\n folderSize += file.Length;\n }\n\n foreach (SPFolder subfolder in folder.SubFolders)\n {\n folderSize += GetFolderSize(subfolder);\n }\n\n return folderSize;\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
201,370
<p>On the site we are building. We need to be able to redirect the user to a default page when his session has ended.</p> <p>At first sight we used the Session_End with a Response.Redirect to do this job.</p> <pre><code>Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) Response.Redirect("~/global/exit.aspx") End Sub </code></pre> <p>But it generates a crapload of <em>Response is not available in this context</em> errors. Naturally we don't want to spam our servers error logs.</p> <p>What is the most efficient way to handle session ending with ASP.NET 2.0?</p>
[ { "answer_id": 203951, "author": "Schalk Versteeg", "author_id": 15724, "author_profile": "https://Stackoverflow.com/users/15724", "pm_score": 2, "selected": false, "text": " private void IsAuthenticated()\n {\n string vFileName = Path.GetFileName(HttpContext.Current.Request.Path);\n string vExt = Path.GetExtension(vFileName).ToLower();\n if ((vFileName != \"Login.aspx\") && (vExt == \".aspx\"))\n {\n if (HttpContext.Current.Session[\"LoggedIn\"] == null)\n {\n HttpContext.Current.Response.Redirect(\"~/Login.aspx\");\n }\n }\n }\n void Application_PostAcquireRequestState(object sender, EventArgs e)\n {\n IsAuthenticated();\n } \n <%@ Application Inherits=\"???.Global\" Language=\"C#\" %>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291/" ]
201,374
<p>I'm trying to work through Project Euler and I'm hitting a barrier on problem 03. I have an algorithm that works for smaller numbers, but problem 3 uses a very, very large number.</p> <p><strong>Problem 03:</strong> The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?</p> <p>Here is my solution in C# and it's been running for I think close to an hour. I'm not looking for an answer because I do actually want to solve this myself. Mainly just looking for some help.</p> <pre><code> static void Main(string[] args) { const long n = 600851475143; //const long n = 13195; long count, half, largestPrime = 0; bool IsAPrime; half = n / 2; for (long i = half; i &gt; 1 &amp;&amp; largestPrime == 0; i--) { if (n % i == 0) { // these are factors of n count = 1; IsAPrime = true; while (++count &lt; i &amp;&amp; IsAPrime) { if (i % count == 0) { // does a factor of n have a factor? (not prime) IsAPrime = false; } } if (IsAPrime) { largestPrime = i; } } } Console.WriteLine("The largest prime factor is " + largestPrime.ToString() + "."); Console.ReadLine(); } </code></pre>
[ { "answer_id": 201387, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "n = 27\nstart at floor(sqrt(27)) = 5\nis 5 a factor? no\nis 4 a factor? no\nis 3 a factor? yes. 27 / 3 = 9. 9 is also a factor.\nis 2 a factor? no.\nfactors are 3 and 9.\n" }, { "answer_id": 201480, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "n = abs(number);\nresult = 1;\nif (n mod 2 = 0) {\n result = 2;\n while (n mod 2 = 0) n /= 2;\n}\nfor(i=3; i<sqrt(n); i+=2) {\n if (n mod i = 0) {\n result = i;\n while (n mod i = 0) n /= i;\n }\n}\nreturn max(n,result)\n" }, { "answer_id": 210103, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "p n % p == 0 n = 1 n n 2 <= n <= sqrt(p)" }, { "answer_id": 211229, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "from math import sqrt\n\ndef largest_primefactor(number):\n for divisor in range(2, int(sqrt(number) + 1.5)): # divisor <= sqrt(n)\n q, r = divmod(number, divisor)\n if r == 0:\n #assert(isprime(divisor))\n # recursion depth == number of prime factors,\n # e.g. 4 has two prime factors: {2,2}\n return largest_primefactor(q) \n\n return number # number is a prime itself\n" }, { "answer_id": 3004386, "author": "st0le", "author_id": 216517, "author_profile": "https://Stackoverflow.com/users/216517", "pm_score": 3, "selected": false, "text": "long n = 600851475143L; //not even, so 2 wont be a factor\nint factor = 3; \nwhile( n > 1)\n{\n if(n % factor == 0)\n {\n n/=factor;\n }else\n factor += 2; //skip even numbrs\n}\n print factor;\n" }, { "answer_id": 3376319, "author": "Deepak", "author_id": 407233, "author_profile": "https://Stackoverflow.com/users/407233", "pm_score": 1, "selected": false, "text": "#include <iostream>\n\nusing namespace std;\n\n\nint main()\n{\n unsigned long long int largefactor = 600851475143;\n for(int i = 2;;)\n {\n if (largefactor <= i)\n break;\n if (largefactor % i == 0)\n {\n largefactor = largefactor / i;\n }\n else\n i++;\n }\n\n cout << largefactor << endl;\n\n cin.get();\n return 0;\n}\n" }, { "answer_id": 7017924, "author": "Dangrr888", "author_id": 888774, "author_profile": "https://Stackoverflow.com/users/888774", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include <cmath>\n#include <ctime>\n\nusing std::sqrt; using std::cin;\nusing std::cout; using std::endl;\n\nlong lpf(long n)\n{\n long start = (sqrt(n) + 2 % 2);\n if(start % 2 == 0) start++;\n\n for(long i = start; i != 2; i -= 2)\n {\n if(n % i == 0) //then i is a factor of n \n {\n long j = 2L;\n do {\n ++j;\n }\n while(i % j != 0 && j <= i);\n\n if(j == i) //then i is a prime number \n return i;\n }\n }\n}\n\nint main()\n{\n long n, ans;\n cout << \"Please enter your number: \";\n cin >> n; //600851475143L \n\n time_t start, end;\n time(&start);\n int i;\n for(i = 0; i != 3000; ++i)\n ans = lpf(n);\n time(&end);\n\n cout << \"The largest prime factor of your number is: \" << ans << endl;\n cout << \"Running time: \" << 1000*difftime(end, start)/i << \" ms.\" << endl;\n\n return 0;\n}\n" }, { "answer_id": 32215017, "author": "stian", "author_id": 1546268, "author_profile": "https://Stackoverflow.com/users/1546268", "pm_score": -1, "selected": false, "text": "import Data.Numbers.Primes\nlast (primeFactors 600851475143)\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444511/" ]
201,377
<p>For example, I am trying to get a min date, a max date, and a sum in different instances. I am trying to avoid hard coding a SQL string or looping through an IList to get these values.</p>
[ { "answer_id": 201387, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "n = 27\nstart at floor(sqrt(27)) = 5\nis 5 a factor? no\nis 4 a factor? no\nis 3 a factor? yes. 27 / 3 = 9. 9 is also a factor.\nis 2 a factor? no.\nfactors are 3 and 9.\n" }, { "answer_id": 201480, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "n = abs(number);\nresult = 1;\nif (n mod 2 = 0) {\n result = 2;\n while (n mod 2 = 0) n /= 2;\n}\nfor(i=3; i<sqrt(n); i+=2) {\n if (n mod i = 0) {\n result = i;\n while (n mod i = 0) n /= i;\n }\n}\nreturn max(n,result)\n" }, { "answer_id": 210103, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "p n % p == 0 n = 1 n n 2 <= n <= sqrt(p)" }, { "answer_id": 211229, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "from math import sqrt\n\ndef largest_primefactor(number):\n for divisor in range(2, int(sqrt(number) + 1.5)): # divisor <= sqrt(n)\n q, r = divmod(number, divisor)\n if r == 0:\n #assert(isprime(divisor))\n # recursion depth == number of prime factors,\n # e.g. 4 has two prime factors: {2,2}\n return largest_primefactor(q) \n\n return number # number is a prime itself\n" }, { "answer_id": 3004386, "author": "st0le", "author_id": 216517, "author_profile": "https://Stackoverflow.com/users/216517", "pm_score": 3, "selected": false, "text": "long n = 600851475143L; //not even, so 2 wont be a factor\nint factor = 3; \nwhile( n > 1)\n{\n if(n % factor == 0)\n {\n n/=factor;\n }else\n factor += 2; //skip even numbrs\n}\n print factor;\n" }, { "answer_id": 3376319, "author": "Deepak", "author_id": 407233, "author_profile": "https://Stackoverflow.com/users/407233", "pm_score": 1, "selected": false, "text": "#include <iostream>\n\nusing namespace std;\n\n\nint main()\n{\n unsigned long long int largefactor = 600851475143;\n for(int i = 2;;)\n {\n if (largefactor <= i)\n break;\n if (largefactor % i == 0)\n {\n largefactor = largefactor / i;\n }\n else\n i++;\n }\n\n cout << largefactor << endl;\n\n cin.get();\n return 0;\n}\n" }, { "answer_id": 7017924, "author": "Dangrr888", "author_id": 888774, "author_profile": "https://Stackoverflow.com/users/888774", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include <cmath>\n#include <ctime>\n\nusing std::sqrt; using std::cin;\nusing std::cout; using std::endl;\n\nlong lpf(long n)\n{\n long start = (sqrt(n) + 2 % 2);\n if(start % 2 == 0) start++;\n\n for(long i = start; i != 2; i -= 2)\n {\n if(n % i == 0) //then i is a factor of n \n {\n long j = 2L;\n do {\n ++j;\n }\n while(i % j != 0 && j <= i);\n\n if(j == i) //then i is a prime number \n return i;\n }\n }\n}\n\nint main()\n{\n long n, ans;\n cout << \"Please enter your number: \";\n cin >> n; //600851475143L \n\n time_t start, end;\n time(&start);\n int i;\n for(i = 0; i != 3000; ++i)\n ans = lpf(n);\n time(&end);\n\n cout << \"The largest prime factor of your number is: \" << ans << endl;\n cout << \"Running time: \" << 1000*difftime(end, start)/i << \" ms.\" << endl;\n\n return 0;\n}\n" }, { "answer_id": 32215017, "author": "stian", "author_id": 1546268, "author_profile": "https://Stackoverflow.com/users/1546268", "pm_score": -1, "selected": false, "text": "import Data.Numbers.Primes\nlast (primeFactors 600851475143)\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
201,386
<p>On my reading spree, I stumbled upon something called <a href="http://en.wikipedia.org/wiki/Intentional_programming" rel="noreferrer">Intentional Programming</a>. I understood it somewhat, but I not fully. If anyone can explain it in better detail, please do. Is it being used in any real application?</p>
[ { "answer_id": 4209826, "author": "Igor Zevaka", "author_id": 129404, "author_profile": "https://Stackoverflow.com/users/129404", "pm_score": 2, "selected": false, "text": "//C#, Normal version\nCustomer customer = CustomerService.Get(23);\n\nOrder order = new Order();\n//What is 0.1? Need to look at Discount property to understand\norder.Discount = 0.1; \norder.Customer = customer;\n\n//What's 34?\nProduct product = ProductService.Get(34); \n//Do we really care about Order stores OrderLines?\norder.OrderLines.Add(new OrderLine(product, 1)); \n\nProduct product2 = ProductService.Get(54);\norder.OrderLines.Add(new OrderLine(product2, 2)); //What's 2?\n\nOrder.Submit();\n\n//C#, Fluent version\n//byId is named parameter, states that this method looks up customer by Id\nICustomerForOrderCreation customer = \n CustomerService.GetCustomerForOrderCreation(byId: 23); \n//Explicit method to create a discount order and explicit percentage\nOrder order = customer.CreateDiscountOrder(10.Percent()) \n .WithProduct(ProductService.Get(byId: 34))\n .WithProduct(ProductService.Get(byId: 54))\n .WithQuantity(2); //Explicit quantity\n\nOrder.Submit();\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6613/" ]
201,391
<p>Why is the <em>CheckBoxList</em> removed from ASP.NET MVC preview release 5? </p> <p>Currently I don't see any way in which I can create a list of checkboxes (with similar names but different id's) so people can select 0-1-more options from the list.</p> <p>There is an <code>CheckBoxList</code> list present in the MVCContrib library, but it is deprecated. I can understand this for the other HtmlHelpers, but there does not seem to be a replacement for the <code>CheckBoxList</code> in preview 5.</p> <p>I would like to create a very simple list like you see below, but what is the best way to do this using ASP.NET MVC preview release 5?</p> <pre><code>&lt;INPUT TYPE="checkbox" NAME="Inhoud" VALUE="goed"&gt; goed &lt;INPUT TYPE="checkbox" NAME="Inhoud" VALUE="redelijk"&gt; redelijk &lt;INPUT TYPE="checkbox" NAME="Inhoud" VALUE="matig"&gt; matig &lt;INPUT TYPE="checkbox" NAME="Inhoud" VALUE="slecht"&gt; slecht </code></pre>
[ { "answer_id": 201423, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 4, "selected": false, "text": "<% foreach(Inhoud i in ViewData[\"InhoudList\"] as List<Inhoud>) { %>\n <input type=\"checkbox\" name=\"Inhoud\" value=\"<%= i.name %>\" checked=\"checked\" /> <%= i.name %>\n<% } %> \n Html.Checkbox" }, { "answer_id": 706208, "author": "javierlinked", "author_id": 65629, "author_profile": "https://Stackoverflow.com/users/65629", "pm_score": 0, "selected": false, "text": " var rolesList = new List<CheckBoxListInfo>();\n foreach (var role in Roles.GetAllRoles())\n {\n rolesList.Add(new CheckBoxListInfo(role, role, Roles.IsUserInRole(user.UserName, role)));\n }\n ViewData[\"roles\"] = listaRoles;\n <div><%= Html.CheckBoxList(\"roles\", ViewData[\"roles\"]) %></div>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27857/" ]
201,392
<p>I have a large number of files in a .tar.gz archive. Checking the file type with the command</p> <pre><code>file SMS.tar.gz </code></pre> <p>gives the response</p> <pre><code>gzip compressed data - deflate method , max compression </code></pre> <p>When I try to extract the archive with gunzip, after a delay I receive the message</p> <pre><code>gunzip: SMS.tar.gz: unexpected end of file </code></pre> <p>Is there any way to recover even part of the archive?</p>
[ { "answer_id": 222943, "author": "Liudvikas Bukys", "author_id": 5845, "author_profile": "https://Stackoverflow.com/users/5845", "pm_score": 5, "selected": false, "text": "gunzip < SMS.tar.gz > SMS.tar.partial\n" }, { "answer_id": 18915270, "author": "Anthony Palmer", "author_id": 572860, "author_profile": "https://Stackoverflow.com/users/572860", "pm_score": 2, "selected": false, "text": "gzip -d A.tar.gz\ngzip: A.tar.gz: invalid compressed data--format violated\n dos2unix dos2unix A.tar.gz\ndos2unix: converting file A.tar.gz to UNIX format ...\ntar -xvf A.tar\nfile1.txt\nfile2.txt \n....etc.\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11787/" ]
201,401
<p>I am looking to improve the performance of my site, not because it is performing badly but just as a general exercise. The usual suggestion for asp.net sites is to remove viewstate wherever possible. I believe this can be done by each control on a page separately or for the whole page.</p> <p>My question is if I disable the page viewstate will this stop the viewstate of controls on a masterpage (as I understand it the masterpage is actually a control on the page). </p>
[ { "answer_id": 204119, "author": "PhilPursglove", "author_id": 1738, "author_profile": "https://Stackoverflow.com/users/1738", "pm_score": 2, "selected": false, "text": "Imports System \nImports System.Web.UI\n\nPublic Class SessionPageStateAdapter\n Inherits System.Web.UI.Adapters.PageAdapter\n\n Public Overrides Function GetStatePersister() As System.Web.UI.PageStatePersister\n\n Return New SessionPageStatePersister(Page)\n\n End Function\nEnd Class\n App_Browsers App_Browsers default.browser <browsers>\n <browser refID=\"Default\">\n <controlAdapters>\n <adapter controlType=\"System.Web.UI.Page\" adapterType=\"[YourNamespaceGoesHere].SessionPageStateAdapter\" />\n </controlAdapters>\n </browser>\n </browsers>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
201,413
<p>Just because I'm curious--is there any C analog to the functionality of the STL in C++? I've seen mention of a <a href="http://www.gtk.org" rel="noreferrer">GTK+</a> library called glib that a few people consider fills the bill but are there other libraries that would provide STL functionality in C?</p>
[ { "answer_id": 201483, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 6, "selected": true, "text": "glib GObject gobject_set_property" }, { "answer_id": 63071045, "author": "msune", "author_id": 9321563, "author_profile": "https://Stackoverflow.com/users/9321563", "pm_score": 2, "selected": false, "text": "libcdada libstdc++" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
201,436
<p>I'm trying to get the following code working: </p> <pre><code> string url = String.Format(@"SOMEURL"); string user = "SOMEUSER"; string password = "SOMEPASSWORD"; FtpWebRequest ftpclientRequest = (FtpWebRequest)WebRequest.Create(new Uri(url)); ftpclientRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpclientRequest.UsePassive = true; ftpclientRequest.Proxy = null; ftpclientRequest.Credentials = new NetworkCredential(user, password); FtpWebResponse response = ftpclientRequest.GetResponse() as FtpWebResponse; </code></pre> <p>This normally works, but for 1 particular server this gives an Error 500: Syntax not recognized. The Change Directory command is disabled on the problem server, and the site administrator told me that .NET issues a Change Directory command by default with all FTP connections. Is that true? Is there a way to disable that? <BR>EDIT: When I login from a command line I am in the correct directory:<BR> ftp> pwd<BR> 257 "/" is current directory</p>
[ { "answer_id": 201847, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 5, "selected": true, "text": "if (m_PreviousServerPath != newServerPath) { \n if (!m_IsRootPath\n && m_LoginState == FtpLoginState.LoggedIn\n && m_LoginDirectory != null)\n { \n newServerPath = m_LoginDirectory+newServerPath;\n } \n m_NewServerPath = newServerPath; \n\n commandList.Add(new PipelineEntry(FormatFtpCommand(\"CWD\", newServerPath), PipelineEntryFlags.UserCommand)); \n}\n" }, { "answer_id": 205615, "author": "David Grayson", "author_id": 28128, "author_profile": "https://Stackoverflow.com/users/28128", "pm_score": 0, "selected": false, "text": "FtpClient ftp = new FtpClient(FtpServer,FtpUserName,FtpPassword);\nftp.Login();\nftp.Upload(@\"C:\\image.jpg\");\nftp.Close(); \n" }, { "answer_id": 8165539, "author": "Riddle", "author_id": 1051534, "author_profile": "https://Stackoverflow.com/users/1051534", "pm_score": 1, "selected": false, "text": "ftp://server/path ftp://server/%2fpath/ %2f / ftp://server/ user_home_path/path" }, { "answer_id": 46574248, "author": "Jim Software", "author_id": 6827636, "author_profile": "https://Stackoverflow.com/users/6827636", "pm_score": 0, "selected": false, "text": "Private Function GetRequest(ByVal URI As String) As FtpWebRequest\n 'create request\n Dim result As FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)\n Return result\nEnd Function\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20754/" ]
201,450
<p>I've been working for years with VS's debugger, but every now and then I come across a feature I have never noticed before, and think &quot;Damn! How could I have missed that? It's <strong>so</strong> useful!&quot;</p> <p>[Disclaimer: These tips work in VS 2005 on a C# project, no guarantees for older incarnations of VS or other languages]</p> <h3>Keep track of object instances</h3> <p>Working with multiple instances of a given class? How can you tell them apart? In pre-garbage collection programming days, it was easy to keep track of references - just look at the memory address. With .NET, you can't do that - objects can get moved around. Fortunately, the watches view lets you right-click on a watch and select 'Make Object ID'.</p> <p>This appends a {1#}, {2#} etc. after the instance's value, effectively giving the instance a unique label.</p> <p>The label is persisted for the lifetime of that object.</p> <h3>Meaningful values for watched variables</h3> <p>By default, a watched variable's value is it's type. If you want to see its fields, you have to expand it, and this could take a long time (or even timeout!) if there are many fields or they do something complicated.</p> <p>However, some predefined types show more meaningful information :</p> <ul> <li>strings show their actual contents</li> <li>lists and dictionaries show their elements count etc.</li> </ul> <p>Wouldn't it be nice to have that for my own types?</p> <p>Hmm...</p> <p>...some quality time with .NET Reflector shows how easily this can be accomplished with the <code>DebuggerDisplay</code> attribute on my custom type:</p> <pre><code>[System.Diagnostics.DebuggerDisplay(&quot;Employee: '{Name}'&quot;)] public class Employee { public string Name { get { ... } } ... } </code></pre> <p>... re-run, and it works.</p> <p>There's a lot more info on the subject here: <a href="http://msdn.microsoft.com/en-us/magazine/cc163974.aspx" rel="nofollow noreferrer">MSDN</a></p> <h3>Break on all exceptions</h3> <p>... even the ones that are handled in code! I know, I'm such a n00b for not knowing about this ever since I was born, but here it goes anyway - maybe this will help someone someday:</p> <p>You can force a debugged process to break into debug mode each time an exception is thrown. Ever went on a bug hunt for hours only to come across a piece of code like this?</p> <pre><code>try { runStrangeContraption(); } catch(Exception ex) { /* TODO: Will handle this error later */ } </code></pre> <p>Catching all exceptions is really handy in these cases. This can be enabled from <em>Debug &gt; Exceptions... (Ctrl-Alt-E)</em>. Tick the boxes in the 'Thrown' column for each type of exception you need.</p> <hr /> <p>Those were a few forehead-slapping moments for me. Would you care to share yours?</p>
[ { "answer_id": 204458, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 4, "selected": false, "text": "System.Diagnostics.Debugger.Break()\n" }, { "answer_id": 204591, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": false, "text": ".load sos" }, { "answer_id": 204609, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 4, "selected": false, "text": "try {\n // do something big\n}\ncatch {\n // breakpoint set here:\n throw CantHappenException(\"something horrible happened that should never happen.\");\n}\n" }, { "answer_id": 400874, "author": "CestLaGalere", "author_id": 6684, "author_profile": "https://Stackoverflow.com/users/6684", "pm_score": 2, "selected": false, "text": "Debug.Assert(<condition>, <message>)\n <DebuggerHidden()> _\nPublic Sub ReadDocumentProperty(ByVal propertyName As String, ByRef PropVal As Integer, ByVal DefaultVal As Integer)\n Try\n Dim prop As Office.DocumentProperty\n prop = CustomProps.Item(propertyName)\n PropVal = CType(prop.Value, Integer)\n Catch\n PropVal = DefaultVal\n End Try\nEnd Sub\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
201,457
<p>What's the best way to implement a URL interpreter / dispatcher, such as found in <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs" rel="nofollow noreferrer">Django</a> and RoR, in PHP?</p> <p>It should be able to interpret a query string as follows:</p> <ul> <li><code>/users/show/4</code> maps to <ul> <li><em>area</em> = <strong>Users</strong></li> <li><em>action</em> = <strong>show</strong></li> <li><em>Id</em> = <strong>4</strong></li> </ul></li> <li><code>/contents/list/20/10</code> maps to <ul> <li><em>area</em> = <strong>Contents</strong></li> <li><em>action</em> = <strong>list</strong></li> <li><em>Start</em> = <strong>20</strong></li> <li><em>Count</em> = <strong>10</strong></li> </ul></li> <li><code>/toggle/projects/10/active</code> maps to <ul> <li><em>action</em> = <strong>toggle</strong></li> <li>area = <strong>Projects</strong></li> <li><em>id</em> = <strong>10</strong></li> <li><em>field</em> = <strong>active</strong></li> </ul></li> </ul> <p>Where the query string can be a specified GET / POST variable, or a string passed to the interpreter.</p> <p>Edit: I'd prefer an implementation that does not use mod_rewrite.</p> <p>Edit: This question is not about clean urls, but about interpreting a URL. Drupal uses mod_rewrite to redirect requests such as <a href="http://host/node/5" rel="nofollow noreferrer">http://host/node/5</a> to <a href="http://host/?q=node/5" rel="nofollow noreferrer">http://host/?q=node/5</a>. It then interprets the value of $_REQUEST['q']. I'm interested in the interpreting part.</p>
[ { "answer_id": 201659, "author": "adnam", "author_id": 27886, "author_profile": "https://Stackoverflow.com/users/27886", "pm_score": 2, "selected": false, "text": "<IfModule mod_rewrite.c>\n RewriteEngine On\n RewriteCond %{REQUEST_FILENAME} -f\n RewriteRule ^(.*)$ $1 [L]\n RewriteRule ^([a-z]{2})/(.*)$ $2?lang=$1 [QSA,L]\n RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]\n</IfModule>\n /en/foo /de/foo GET" }, { "answer_id": 203572, "author": "James Anderson", "author_id": 27632, "author_profile": "https://Stackoverflow.com/users/27632", "pm_score": 1, "selected": false, "text": "<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n $req = $_SERVER['REQUEST_URI'];\n$req = explode(\"/\",$req);\n $area = $req['0'];\n$action= $req['1'];\n$id = $req['2'];\n function get_page($offset) {//offset is the chunk of URL we want to look at\n $req = $_SERVER['REQUEST_URI'];\n $req = explode(\"/\",$req);\n $page = $req[$offset];\n return $page;\n}\n$area = get_page(0);\n$action = get_page(1);\n$id = get_page(2); \n" }, { "answer_id": 328109, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": -1, "selected": false, "text": "_ _ _ $_SERVER phpinfo()" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
201,461
<p>I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:</p> <pre><code>def r(a):i=a.find('0');~i or exit(a);[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import*;r(argv[1]) </code></pre> <p>My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?</p> <p><a href="http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html" rel="noreferrer">http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html</a></p>
[ { "answer_id": 201550, "author": "Tetha", "author_id": 17663, "author_profile": "https://Stackoverflow.com/users/17663", "pm_score": 3, "selected": false, "text": "def r(a):\n i = a.find('0') # returns -1 on fail, index otherwise\n ~i or exit(a) # ~(-1) == 0, anthing else is not 0\n # thus: if i == -1: exit(a)\n inner_lexp = [ (i-j)%9*(i/9 ^ j/9)*(i/27 ^ j/27 | i%9/3 ^ j%9/3) or a[j] \n for j in range(81)] # r appears to be a string of 81 \n # characters with 0 for empty and 1-9 \n # otherwise\n [m in inner_lexp or r(a[:i]+m+a[i+1:]) for m in'%d'%5**18] # recurse\n # trying all possible digits for that empty field\n # if m is not in the inner lexp\n\nfrom sys import *\nr(argv[1]) # thus, a is some string\n" }, { "answer_id": 201566, "author": "Deestan", "author_id": 6848, "author_profile": "https://Stackoverflow.com/users/6848", "pm_score": 3, "selected": false, "text": "r(a) 0 i=a.find('0');~i or exit(a) 0 m 0 m\nin[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for\nj in range(81)] m 0 is_bad or r(a[:i]+m+a[i+1:] 0 for m in '%d'%5**18" }, { "answer_id": 201771, "author": "Bill Barksdale", "author_id": 16113, "author_profile": "https://Stackoverflow.com/users/16113", "pm_score": 9, "selected": true, "text": "def r(a):\n i = a.find('0')\n ~i or exit(a)\n [m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]\nfrom sys import *\nr(argv[1])\n from sys import exit, argv\ndef r(a):\n i = a.find('0')\n if i == -1:\n exit(a)\n for m in '%d' % 5**18:\n m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)] or r(a[:i]+m+a[i+1:])\n\nr(argv[1])\n for m in'%d'%5**18 '%d'%5**18 '3814697265625' r(a[:i]+m+a[i+1:]) m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)] (i-j)%9 (i/9^j/9) (i/27^j/27|i%9/3^j%9/3) i/27^j^27 i%9/3^j%9/3 from sys import exit, argv\ndef r(a):\n i = a.find('0')\n if i == -1:\n exit(a)\n for m in '3814697265625':\n okay = True\n for j in range(81):\n if (i-j)%9 == 0 or (i/9 == j/9) or (i/27 == j/27 and i%9/3 == j%9/3):\n if a[j] == m:\n okay = False\n break\n if okay:\n # At this point, m is not excluded by any row, column, or block, so let's place it and recurse\n r(a[:i]+m+a[i+1:])\n\nr(argv[1])\n $ time python sudoku.py 530070000600195000098000060800060003400803001700020006060000280000419005000080079\n534678912672195348198342567859761423426853791713924856961537284287419635345286179\n\nreal 0m47.881s\nuser 0m47.223s\nsys 0m0.137s\n import sys\n\ndef same_row(i,j): return (i/9 == j/9)\ndef same_col(i,j): return (i-j) % 9 == 0\ndef same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)\n\ndef r(a):\n i = a.find('0')\n if i == -1:\n sys.exit(a)\n\n excluded_numbers = set()\n for j in range(81):\n if same_row(i,j) or same_col(i,j) or same_block(i,j):\n excluded_numbers.add(a[j])\n\n for m in '123456789':\n if m not in excluded_numbers:\n # At this point, m is not excluded by any row, column, or block, so let's place it and recurse\n r(a[:i]+m+a[i+1:])\n\nif __name__ == '__main__':\n if len(sys.argv) == 2 and len(sys.argv[1]) == 81:\n r(sys.argv[1])\n else:\n print 'Usage: python sudoku.py puzzle'\n print ' where puzzle is an 81 character string representing the puzzle read left-to-right, top-to-bottom, and 0 is a blank'\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27736/" ]
201,468
<p>I like the flexibility of Dynamic SQL and I like the security + improved performance of Prepared Statements. So what I really want is Dynamic Prepared Statements, which is troublesome to make because bind_param and bind_result accept "fixed" number of arguments. So I made use of an eval() statement to get around this problem. But I get the feeling this is a bad idea. Here's example code of what I mean</p> <pre><code>// array of WHERE conditions $param = array('customer_id'=&gt;1, 'qty'=&gt;'2'); $stmt = $mysqli-&gt;stmt_init(); $types = ''; $bindParam = array(); $where = ''; $count = 0; // build the dynamic sql and param bind conditions foreach($param as $key=&gt;$val) { $types .= 'i'; $bindParam[] = '$p'.$count.'=$param["'.$key.'"]'; $where .= "$key = ? AND "; $count++; } // prepare the query -- SELECT * FROM t1 WHERE customer_id = ? AND qty = ? $sql = "SELECT * FROM t1 WHERE ".substr($where, 0, strlen($where)-4); $stmt-&gt;prepare($sql); // assemble the bind_param command $command = '$stmt-&gt;bind_param($types, '.implode(', ', $bindParam).');'; // evaluate the command -- $stmt-&gt;bind_param($types,$p0=$param["customer_id"],$p1=$param["qty"]); eval($command); </code></pre> <p>Is that last eval() statement a bad idea? I tried to avoid code injection by encapsulating values behind the variable name $param.</p> <p>Does anyone have an opinion or other suggestions? Are there issues I need to be aware of?</p>
[ { "answer_id": 201639, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "eval() \"SELECT * FROM t1 WHERE p1 = ? AND p2 = ?\" prepare() call_user_func_array() bind_param() call_user_func_array(array($stmt, 'bind_param'), array($types)+$param);\n" }, { "answer_id": 205145, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": -1, "selected": false, "text": "// Array of WHERE conditions\n$conds = array(\"customer_id\" => 1, \"qty\" => 2);\n\n$wherec = array(\"1\");\nforeach ($conds as $col=>$val) $wherec[] = sprintf(\"`%s` = '%s'\", $col, mysql_real_escape_string($val));\n\n$result_set = mysql_query(\"SELECT * FROM t1 WHERE \" . implode(\" AND \", $wherec);\n function insert($table, $record) {\n $cols = array();\n $vals = array();\n foreach (array_keys($record) as $col) $cols[] = sprintf(\"`%s`\", $col);\n foreach (array_values($record) as $val) $vals[] = sprintf(\"'%s'\", mysql_real_escape_string($val));\n\n mysql_query(sprintf(\"INSERT INTO `%s`(%s) VALUES(%s)\", $table, implode(\", \", $cols), implode(\", \", $vals)));\n}\n\n// Use as follows:\ninsert(\"customer\", array(\"customer_id\" => 15, \"qty\" => 86));\n" }, { "answer_id": 54048416, "author": "boctulus", "author_id": 980631, "author_profile": "https://Stackoverflow.com/users/980631", "pm_score": 0, "selected": false, "text": "private $table_name = \"products\";\n\nprotected $schema = [\n 'id' => 'INT',\n 'name' => 'STR',\n 'description' => 'STR',\n 'size' => 'STR',\n 'cost' => 'INT',\n 'active' => 'BOOL'\n];\n function filter($conditions)\n{\n $vars = array_keys($conditions);\n $values = array_values($conditions);\n\n $where = '';\n foreach($vars as $ix => $var){\n $where .= \"$var = :$var AND \";\n }\n $where =trim(substr($where, 0, strrpos( $where, 'AND ')));\n\n $q = \"SELECT * FROM {$this->table_name} WHERE $where\";\n $st = $this->conn->prepare($q);\n\n foreach($values as $ix => $val){\n $st->bindValue(\":{$vars[$ix]}\", $val, constant(\"PDO::PARAM_{$this->schema[$vars[$ix]]}\"));\n }\n\n $st->execute();\n return $st->fetchAll(PDO::FETCH_ASSOC);\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27305/" ]
201,476
<p>I am getting the following error when I get to the line that invokes a REALLY BASIC web service I have running on Tomcat/Axis.</p> <pre><code>Element or attribute do not match QName production: QName::=(NCName':')?NCName </code></pre> <p>Have I got something wrong with QName?- I can't even find any useful information about it.</p> <p>My client code is below:</p> <pre><code>import javax.xml.namespace.QName; import org.apache.axis.client.Call; import org.apache.axis.client.Service; public class TestClient { public static void main(String [] args) { try{ String endpoint = "http://localhost:8080/TestWebService/services/DoesMagic"; Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpoint) ); call.setOperationName( new QName("http://testPackage.fc.com/, doBasicStuff") ); String ret = (String) call.invoke( new Object[] {"some kind of message"} ); System.out.println(ret); }catch(Exception e){ System.err.println(e.toString()); } } } </code></pre> <p>My web serivce code is really basic - just a simple class that returns your input string with a bit of concat text:</p> <pre><code>public String doBasicStuff(String message) { return "This is your message: " + message; } </code></pre>
[ { "answer_id": 201497, "author": "Rich Kroll", "author_id": 58733, "author_profile": "https://Stackoverflow.com/users/58733", "pm_score": 3, "selected": false, "text": "new QName(\"http://testPackage.fc.com/\", \"doBasicStuff\")\n new QName(\"http://testPackage.fc.com/, doBasicStuff\")\n" }, { "answer_id": 201508, "author": "Martin Probst", "author_id": 22227, "author_profile": "https://Stackoverflow.com/users/22227", "pm_score": 4, "selected": true, "text": "new QName(\"http://testPackage.fc.com/, doBasicStuff\")\n" }, { "answer_id": 2632101, "author": "Don G.", "author_id": 315793, "author_profile": "https://Stackoverflow.com/users/315793", "pm_score": 0, "selected": false, "text": "public QName(String localPart) or\npublic QName(final String namespaceURI, final String localPart)\n" }, { "answer_id": 13887993, "author": "mohamed", "author_id": 1905444, "author_profile": "https://Stackoverflow.com/users/1905444", "pm_score": 0, "selected": false, "text": "call.setOperationName(\"doBasicStuff\");" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5175/" ]
201,479
<p>I've heard people talking about "base 64 encoding" here and there. What is it used for?</p>
[ { "answer_id": 201495, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "+ / =" }, { "answer_id": 201823, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 3, "selected": false, "text": "import base64\nimageAsBytes = base64.b64decode( dataFromWS )\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
201,501
<p>I have a strange issue: I am using SPContext.Current.Web in a .aspx page, but at the end, I get a "Trying to use an SPWeb object that has been closed or disposed and is no longer valid." error message.</p> <p>From what I see, SPContext.Current.Web is Disposed by someone, <strong>but I have no idea where</strong>. I just wonder: With Visual Studio 2005's Debugger, can I somehow see where/who disposed an Object? As I neither create nor have the source code, setting breakpoints is a problem.</p> <p>What would be a good approach for finding out who disposes a given object where, without just randomly commenting out lines?</p> <p>(Note: The Issue has been resolve, but the question itself also applies outside of Sharepoint)</p>
[ { "answer_id": 201645, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": true, "text": "System.IO.StreamReader.Dispose" }, { "answer_id": 202132, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": -1, "selected": false, "text": "using(SPWeb web = ...)\n{\n ....\n}\n SPWeb web = ...\n...\nweb.Dispose()\n" }, { "answer_id": 595091, "author": "Corey Roth", "author_id": 28711, "author_profile": "https://Stackoverflow.com/users/28711", "pm_score": 0, "selected": false, "text": "using (SPWeb myWeb = SPContext.Current.Web)\n{\n // do something\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
201,515
<p>I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". <code>urllib.urlopen</code> will successfully read the page but <code>urllib2.urlopen</code> will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):</p> <pre><code>import urllib, urllib2 print urllib.urlopen("http://127.0.0.1").read() # prints "running" print urllib2.urlopen("http://127.0.0.1").read() # throws an exception </code></pre> <p>Here's the stack trace:</p> <pre><code>Traceback (most recent call last): File "urltest.py", line 5, in &lt;module&gt; print urllib2.urlopen("http://127.0.0.1").read() File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 412, in error result = self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 575, in http_error_302 return self.parent.open(new) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 418, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 499, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 504: Gateway Timeout </code></pre> <p>Any ideas? I might end up needing some of the more advanced features of <code>urllib2</code>, so I don't want to just resort to using <code>urllib</code>, plus I want to understand this problem.</p>
[ { "answer_id": 201737, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "proxy_support = urllib2.ProxyHandler({})\nopener = urllib2.build_opener(proxy_support)\nprint opener.open(\"http://127.0.0.1\").read()\n\n# Optional - makes this opener default for urlopen etc.\nurllib2.install_opener(opener)\nprint urllib2.urlopen(\"http://127.0.0.1\").read()\n" }, { "answer_id": 201754, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": ">>> import urllib2\n>>> urllib2.urlopen('http://mit.edu').read()[:10]\n'<!DOCTYPE '\n>>> urllib2._opener.handlers[1].set_http_debuglevel(100)\n>>> urllib2.urlopen('http://mit.edu').read()[:10]\nconnect: (mit.edu, 80)\nsend: 'GET / HTTP/1.1\\r\\nAccept-Encoding: identity\\r\\nHost: mit.edu\\r\\nConnection: close\\r\\nUser-Agent: Python-urllib/2.5\\r\\n\\r\\n'\nreply: 'HTTP/1.1 200 OK\\r\\n'\nheader: Date: Tue, 14 Oct 2008 15:52:03 GMT\nheader: Server: MIT Web Server Apache/1.3.26 Mark/1.5 (Unix) mod_ssl/2.8.9 OpenSSL/0.9.7c\nheader: Last-Modified: Tue, 14 Oct 2008 04:02:15 GMT\nheader: ETag: \"71d3f96-2895-48f419c7\"\nheader: Accept-Ranges: bytes\nheader: Content-Length: 10389\nheader: Connection: close\nheader: Content-Type: text/html\n'<!DOCTYPE '\n" }, { "answer_id": 201756, "author": "Deestan", "author_id": 6848, "author_profile": "https://Stackoverflow.com/users/6848", "pm_score": 1, "selected": false, "text": "GET / HTTP/1.0\nHost: 127.0.0.1\nUser-Agent: Python-urllib/1.17\n GET / HTTP/1.1\nAccept-Encoding: identity\nHost: 127.0.0.1\nConnection: close\nUser-Agent: Python-urllib/2.5\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
201,518
<p>Greetings!</p> <p>I've created a custom button class to render the following:</p> <pre><code>&lt;span class="btnOrange"&gt; &lt;input type="submit" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/&gt; &lt;/span&gt; </code></pre> <p>However, it renders like this instead (note the extraneous "class" attribute in the INPUT tag):</p> <pre><code>&lt;span class="btnOrange"&gt; &lt;input type="submit" class="btnOrange" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/&gt; &lt;/span&gt; </code></pre> <p>My custom button class looks like this:</p> <pre><code>[ToolboxData(@"&lt;{0}:MyButton runat=server&gt;&lt;/{0}:MyButton&gt;")] public class MyButton : Button { public override void RenderBeginTag(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); writer.RenderBeginTag("span"); base.RenderBeginTag(writer); } public override void RenderEndTag(HtmlTextWriter writer) { writer.RenderEndTag(); base.RenderEndTag(writer); } } </code></pre> <p>Since I only need to set the class attribute for the SPAN tag, is it possible to not include or "blank out" the class attribute for the INPUT tag?</p>
[ { "answer_id": 201526, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "class writer span" }, { "answer_id": 203613, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": true, "text": "private string _heldCssClass = null;\npublic override void RenderBeginTag(HtmlTextWriter writer)\n{\n writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); \n writer.RenderBeginTag(\"span\");\n _heldCssClass = this.CssClass;\n this.CssClass = String.Empty;\n base.RenderBeginTag(writer);\n}\n\npublic override void RenderEndTag(HtmlTextWriter writer)\n{\n writer.RenderEndTag();\n base.RenderEndTag(writer);\n this.CssClass = _heldCssClass;\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
201,524
<p>Our Test DB is suddenly missing rows. We want them back.</p> <p>Is there a way to sift through everything that has happened to the database today? Each SQL statement? I presume this kind of stuff is in the transaction log, but am not sure how to view it.</p> <p>Is there a way to undo delete operations?</p> <p>BTW: Yes, we do have a backup, but would prefer to find the cause of the deletion as well...</p>
[ { "answer_id": 35519886, "author": "Jason Clark", "author_id": 5218011, "author_profile": "https://Stackoverflow.com/users/5218011", "pm_score": -1, "selected": false, "text": "Rollback Begin" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
201,527
<p>I need to create a database table to store different changelog/auditing (when something was added, deleted, modified, etc). I don't need to store particularly detailed info, so I was thinking something along the lines of:</p> <ul> <li>id (for the event)</li> <li>user that triggered it</li> <li>event name</li> <li>event description</li> <li>timestamp of the event</li> </ul> <p>Am I missing something here? Obviously, I can keep improving the design, although I don't plan on making it complicated (creating other tables for event types or stuff like that is out of the question since it's a complication for my need).</p>
[ { "answer_id": 201561, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "mod_user log_datetime seq_num seq_num" }, { "answer_id": 211540, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "Primary Key\nEvent type (e.g. \"UPDATED\", \"APPROVED\")\nDescription (\"Frisbar was added to blong\")\nUser Id\nUser Id of second authoriser\nAmount\nDate/time\nGeneric Id\nTable Name\n" }, { "answer_id": 302311, "author": "Yarik", "author_id": 31415, "author_profile": "https://Stackoverflow.com/users/31415", "pm_score": 7, "selected": true, "text": "event ID\nevent date/time\nevent type\nuser ID\ndescription\n Who the heck created/updated/deleted a record \nwith ID=X in the table Foo and when?\n object type (or table name)\nobject ID\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9114/" ]
201,530
<p>I need to add multiple empty divs to a container element using jQuery.</p> <p>At the moment I am generating a string containing the empty html using a loop</p> <pre><code>divstr = '&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;...&lt;div&gt;&lt;/div&gt;'; </code></pre> <p>and then injecting that into my container:</p> <pre><code>$('#container').html(divstr); </code></pre> <p>Is there a more elegant way to insert multiple, identical elements?</p> <p>I'm hoping to find something that wouldn't break chaining but wouldn't bring the browser to its knees. A chainable <code>.repeat()</code> plugin?</p>
[ { "answer_id": 201564, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 1, "selected": false, "text": "for(i=0;i<10; i++){\n $('#container').append(\"<div></div>\");\n}\n" }, { "answer_id": 201661, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 5, "selected": true, "text": "var i = 10, \n fragment = document.createDocumentFragment(), \n div = document.createElement('div');\n\nwhile (i--) {\n fragment.appendChild(div.cloneNode(true));\n}\n\n$('#container').append(fragment);\n" }, { "answer_id": 201991, "author": "MonkeyBrother", "author_id": 16296, "author_profile": "https://Stackoverflow.com/users/16296", "pm_score": 3, "selected": false, "text": "var cont = []; //Initialize an array to build the content\nfor (var i = 0;i<10;i++) cont.push('<div>bunch of text</div>');\n$('#container').html(cont.join(''));\n" }, { "answer_id": 361563, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "$(['plop', 'onk', 'gloubi'])\n.map(function(i, text)\n{\n return $('<div/>').text(text).get(0);\n})\n.appendTo('#container');\n <div id=\"container\">\n<div>plop</div>\n<div>onk</div>\n<div>gloubi</div>\n</div>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20074/" ]
201,532
<p>I use the ASP.NET Development Web server (also known as the Visual Studio Development Web server) to do local web site debugging and testing.</p> <p>I've pretty much found exact functionality with IIS with the dev web server. However - where can you manage the settings of the dev web server - specifically regarding never caching any content - ever?</p> <p>This of course is useful in a development scenario where I dont want to have to clear my cache...</p>
[ { "answer_id": 13547959, "author": "Ahmad Firdaus", "author_id": 990579, "author_profile": "https://Stackoverflow.com/users/990579", "pm_score": 0, "selected": false, "text": "[WebMethod(CacheDuration=0)]\npublic string mymethod(string s)\n{\n\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
201,589
<p>I know that the JBoss Application Server has the JMX-Console as a GUI for administration. My question is, is there a similar admin tool using the command line? Does this tool come with the application server, and can it report on the status of various services under the control of the server?</p>
[ { "answer_id": 410591, "author": "Nicholas", "author_id": 43786, "author_profile": "https://Stackoverflow.com/users/43786", "pm_score": 1, "selected": false, "text": "import javax.management.*;\nimport javax.naming.*;\nProperties p = new Properties();\np.put(Context.PROVIDER_URL, url);\np.put(Context.INITIAL_CONTEXT_FACTORY, \"org.jnp.interfaces.NamingContextFactory\");\np.put(\"jnp.disableDiscovery\", \"true\");\nctx = new InitialContext(p);\ncontexts.put(url, ctx);\nmbeanServer = ctx.lookup(\"/jmx/rmi/RMIAdaptor\");\n// Lookups here\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27778/" ]
201,590
<p>I've inherited a .NET application that pulls together about 100 dlls built by two teams or purchased from vendors. I would like to quickly identify whether a given dll is a .NET assembly or a COM component. I realize that I could just invoke ildasm on each dll individually and make a note if the dll does not have a valid CLR header, but this approach seems clumsy and difficult to automate.</p>
[ { "answer_id": 201781, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "System.Reflection.Assembly.ReflectionOnlyLoadFrom(\"mydll.dll\")\n" }, { "answer_id": 202633, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 3, "selected": true, "text": "dumpbin unknown.dll /exports | find \"DllGetClassObject\"\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nstatic class NativeStuff\n{\n [DllImport(\"kernel32.dll\")]\n public static extern IntPtr LoadLibrary(string dllToLoad);\n\n [DllImport(\"kernel32.dll\")]\n public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);\n\n [DllImport(\"kernel32.dll\")]\n public static extern bool FreeLibrary(IntPtr hModule);\n}\n\nnamespace IsComDLL\n{\n class Program\n {\n static void Main(string[] args)\n {\n if ( (args.Length == 0 ) || String.IsNullOrEmpty( args[0] ) )\n {\n Console.WriteLine( \"Give DLL name on command line\" );\n Environment.Exit(255);\n }\n\n IntPtr pDll = NativeStuff.LoadLibrary(args[0]);\n if ( pDll == IntPtr.Zero )\n {\n Console.WriteLine( \"DLL file {0} not found\", args[0] );\n Environment.Exit(256);\n }\n\n IntPtr pFunction = NativeStuff.GetProcAddress(pDll, \"DllGetClassObject\");\n int exitValue = 0;\n if (pFunction == IntPtr.Zero)\n {\n Console.WriteLine(\"DLL file {0} does NOT contain COM objects\", args[0]);\n }\n else\n {\n Console.WriteLine(\"DLL file {0} does contain COM objects\", args[0]);\n exitValue = 1;\n }\n\n NativeStuff.FreeLibrary(pDll);\n\n Environment.Exit(exitValue);\n }\n }\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5985/" ]
201,593
<p>Suppose we have some named enums:</p> <pre><code>enum MyEnum { FOO, BAR = 0x50 }; </code></pre> <p>What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.</p> <pre><code>char* enum_to_string(MyEnum t); </code></pre> <p>And a implementation with something like this:</p> <pre><code>char* enum_to_string(MyEnum t){ switch(t){ case FOO: return "FOO"; case BAR: return "BAR"; default: return "INVALID ENUM"; } } </code></pre> <p>The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?</p> <p>EDIT: The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.</p>
[ { "answer_id": 201665, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 5, "selected": false, "text": "enum colours { red, green, blue };\nconst char *colour_names[] = { \"red\", \"green\", \"blue\" };\n colours mycolour = red;\ncout << \"the colour is\" << colour_names[mycolour];\n #define printword(XX) cout << #XX;\nprintword(red);\n" }, { "answer_id": 201770, "author": "Marcin Koziuk", "author_id": 27909, "author_profile": "https://Stackoverflow.com/users/27909", "pm_score": 6, "selected": false, "text": "#include <iostream>\n\nenum Colours {\n# define X(a) a,\n# include \"colours.def\"\n# undef X\n ColoursCount\n};\n\nchar const* const colours_str[] = {\n# define X(a) #a,\n# include \"colours.def\"\n# undef X\n 0\n};\n\nstd::ostream& operator<<(std::ostream& os, enum Colours c)\n{\n if (c >= ColoursCount || c < 0) return os << \"???\";\n return os << colours_str[c];\n}\n\nint main()\n{\n std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;\n}\n X(Red)\nX(Green)\nX(Blue)\nX(Cyan)\nX(Yellow)\nX(Magenta)\n #define X(a, b) a,\n#define X(a, b) b,\n\nX(Red, \"red\")\nX(Green, \"green\")\n// etc.\n" }, { "answer_id": 201792, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "ENUM(Foo, 1)\nENUM(Bar, 2)\n #define ENUMFACTORY_ARGUMENT \"foobar.h\"\n#include \"enumfactory.h\"\n #include ENUMFACTORY_ARGUMENT DECLARE_ENUM DEFINE_ENUM" }, { "answer_id": 201795, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 7, "selected": true, "text": "<GCC_XML>\n <Namespace id=\"_1\" name=\"::\" members=\"_3 \" mangled=\"_Z2::\"/>\n <Namespace id=\"_2\" name=\"std\" context=\"_1\" members=\"\" mangled=\"_Z3std\"/>\n <Enumeration id=\"_3\" name=\"MyEnum\" context=\"_1\" location=\"f0:1\" file=\"f0\" line=\"1\">\n <EnumValue name=\"FOO\" init=\"0\"/>\n <EnumValue name=\"BAR\" init=\"80\"/>\n </Enumeration>\n <File id=\"f0\" name=\"my_enum.h\"/>\n</GCC_XML>\n" }, { "answer_id": 201806, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "#include \"enum_def.h\"\n#include \"colour.h\"\n#include \"enum_conv.h\"\n#include \"colour.h\"\n #undef ENUM_START\n#undef ENUM_ADD\n#undef ENUM_END\n#define ENUM_START(NAME) enum NAME {\n#define ENUM_ADD(NAME, VALUE) NAME = VALUE,\n#define ENUM_END };\n #undef ENUM_START\n#undef ENUM_ADD\n#undef ENUM_END\n#define ENUM_START(NAME) const char *##NAME##_to_string(NAME val) { switch (val) {\n#define ENUM_ADD(NAME, VALUE) case NAME: return #NAME;\n#define ENUM_END default: return \"Invalid value\"; } }\n ENUM_START(colour)\nENUM_ADD(red, 0xff0000)\nENUM_ADD(green, 0x00ff00)\nENUM_ADD(blue, 0x0000ff)\nENUM_END\n printf(\"%s\", colour_to_string(colour::red));\n" }, { "answer_id": 202024, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 1, "selected": false, "text": "#! /usr/bin/env ruby\n\n# Let's \"parse\" the headers\n# Note that using a regular expression is rather fragile\n# and may break on some inputs\n\nGLOBS = [\n \"toto/*.h\",\n \"tutu/*.h\",\n \"tutu/*.hxx\"\n]\n\nenums = {}\nGLOBS.each { |glob|\n Dir[glob].each { |header|\n enums[header] = File.open(header, 'rb') { |f|\n f.read\n }.scan(/enum\\s+(\\w+)\\s+\\{\\s*([^}]+?)\\s*\\}/m).collect { |enum_name, enum_key_and_values|\n [\n enum_name, enum_key_and_values.split(/\\s*,\\s*/).collect { |enum_key_and_value|\n enum_key_and_value.split(/\\s*=\\s*/).first\n }\n ]\n }\n }\n}\n\n\n# Now we build a .h and .cpp alongside the parsed headers\n# using the template engine provided with ruby\nrequire 'erb'\n\ntemplate_h = ERB.new <<-EOS\n#ifndef <%= enum_name %>_to_string_h_\n#define <%= enum_name %>_to_string_h_ 1\n\n#include \"<%= header %>\"\nchar* enum_to_string(<%= enum_name %> e);\n\n#endif\nEOS\n\ntemplate_cpp = ERB.new <<-EOS\n#include \"<%= enum_name %>_to_string.h\"\n\nchar* enum_to_string(<%= enum_name %> e)\n{\n switch (e)\n {<% enum_keys.each do |enum_key| %>\n case <%= enum_key %>: return \"<%= enum_key %>\";<% end %>\n default: return \"INVALID <%= enum_name %> VALUE\";\n }\n}\nEOS\n\nenums.each { |header, enum_name_and_keys|\n enum_name_and_keys.each { |enum_name, enum_keys|\n File.open(\"#{File.dirname(header)}/#{enum_name}_to_string.h\", 'wb') { |built_h|\n built_h.write(template_h.result(binding))\n }\n\n File.open(\"#{File.dirname(header)}/#{enum_name}_to_string.cpp\", 'wb') { |built_cpp|\n built_cpp.write(template_cpp.result(binding))\n }\n }\n}\n toto/MyEnum_to_string.h\ntoto/MyEnum_to_string.cpp\ntoto/MyEnum2_to_string.h\ntoto/MyEnum2_to_string.cpp\n" }, { "answer_id": 202175, "author": "Ronny Brendel", "author_id": 14114, "author_profile": "https://Stackoverflow.com/users/14114", "pm_score": 3, "selected": false, "text": "QNetworkReply::NetworkError error;\n\nerror = fetchStuff();\n\nif (error != QNetworkReply::NoError) {\n\n QString errorValue;\n\n QMetaObject meta = QNetworkReply::staticMetaObject;\n\n for (int i=0; i < meta.enumeratorCount(); ++i) {\n\n QMetaEnum m = meta.enumerator(i);\n\n if (m.name() == QLatin1String(\"NetworkError\")) {\n\n errorValue = QLatin1String(m.valueToKey(error));\n\n break;\n\n }\n\n }\n\n QMessageBox box(QMessageBox::Information, \"Failed to fetch\",\n\n \"Fetching stuff failed with error '%1`\").arg(errorValue),\n\n QMessageBox::Ok);\n\n box.exec();\n\n return 1;\n\n}\n" }, { "answer_id": 202529, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 2, "selected": false, "text": "enum EHelpLocation\n{\n HELP_LOCATION_UNKNOWN = 0, \n HELP_LOCAL_FILE = 1, \n HELP_HTML_ONLINE = 2, \n};\nclass CEnumFormatter_EHelpLocation : public CEnumDefaultFormatter< EHelpLocation >\n{\npublic:\n static inline CString FormatEnum( EHelpLocation eValue )\n {\n switch ( eValue )\n {\n ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_LOCATION_UNKNOWN );\n ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_LOCAL_FILE );\n ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_HTML_ONLINE );\n default:\n return FormatAsNumber( eValue );\n }\n }\n};\nDECLARE_RANGE_CHECK_CLASS( EHelpLocation, CRangeInfoSequential< HELP_HTML_ONLINE > );\ntypedef ESmartEnum< EHelpLocation, HELP_LOCATION_UNKNOWN, CEnumFormatter_EHelpLocation, CRangeInfo_EHelpLocation > SEHelpLocation;\n" }, { "answer_id": 238157, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 6, "selected": false, "text": "#define SOME_ENUM(DO) \\\n DO(Foo) \\\n DO(Bar) \\\n DO(Baz)\n\n#define MAKE_ENUM(VAR) VAR,\nenum MetaSyntacticVariable{\n SOME_ENUM(MAKE_ENUM)\n};\n\n#define MAKE_STRINGS(VAR) #VAR,\nconst char* const MetaSyntacticVariableNames[] = {\n SOME_ENUM(MAKE_STRINGS)\n};\n" }, { "answer_id": 1030248, "author": "Carl", "author_id": 13760, "author_profile": "https://Stackoverflow.com/users/13760", "pm_score": 3, "selected": false, "text": "#include <map>\n#include <string>\nenum test{ one, two, three, five=5, six, seven };\nstruct mymap : std::map<unsigned int, std::string>\n{\n mymap()\n {\n this->operator[]( one ) = \"ONE\";\n this->operator[]( two ) = \"TWO\";\n this->operator[]( three ) = \"THREE\";\n this->operator[]( five ) = \"FIVE\";\n this->operator[]( six ) = \"SIX\";\n this->operator[]( seven ) = \"SEVEN\";\n };\n ~mymap(){};\n};\n #include \"myenummap.h\"\n\n...\nmymap nummap;\nstd::cout<< nummap[ one ] << std::endl;\n #include <vector>\n#include <string>\n#include <algorithm>\n#include <iostream>\n\n//These stay together and must be modified together\nenum test{ one, two, three, five=5, six, seven };\nstd::string enum_to_str(test const& e)\n{\n typedef std::pair<int,std::string> mapping;\n auto m = [](test const& e,std::string const& s){return mapping(static_cast<int>(e),s);}; \n std::vector<mapping> const nummap = \n { \n m(one,\"one\"), \n m(two,\"two\"), \n m(three,\"three\"),\n m(five,\"five\"),\n m(six,\"six\"),\n m(seven,\"seven\"),\n };\n for(auto i : nummap)\n {\n if(i.first==static_cast<int>(e))\n {\n return i.second;\n }\n }\n return \"\";\n}\n\nint main()\n{\n// std::cout<< enum_to_str( 46 ) << std::endl; //compilation will fail\n std::cout<< \"Invalid enum to string : [\" << enum_to_str( test(46) ) << \"]\"<<std::endl; //returns an empty string\n std::cout<< \"Enumval five to string : [\"<< enum_to_str( five ) << \"] \"<< std::endl; //works\n return 0;\n}\n" }, { "answer_id": 11586083, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 3, "selected": false, "text": "#define struct IdAndName\n{\n int id;\n const char * name;\n bool operator<(const IdAndName &rhs) const { return id < rhs.id; }\n};\n#define ID_AND_NAME(x) { x, #x }\n\nconst char * IdToName(int id, IdAndName *table_begin, IdAndName *table_end)\n{\n if ((table_end - table_begin) > 1 && table_begin[0].id > table_begin[1].id)\n std::stable_sort(table_begin, table_end);\n\n IdAndName searchee = { id, NULL };\n IdAndName *p = std::lower_bound(table_begin, table_end, searchee);\n return (p == table_end || p->id != id) ? NULL : p->name;\n}\n\ntemplate<int N>\nconst char * IdToName(int id, IdAndName (&table)[N])\n{\n return IdToName(id, &table[0], &table[N]);\n}\n static IdAndName WindowsErrorTable[] =\n{\n ID_AND_NAME(INT_MAX), // flag value to indicate unsorted table\n ID_AND_NAME(NO_ERROR),\n ID_AND_NAME(ERROR_INVALID_FUNCTION),\n ID_AND_NAME(ERROR_FILE_NOT_FOUND),\n ID_AND_NAME(ERROR_PATH_NOT_FOUND),\n ID_AND_NAME(ERROR_TOO_MANY_OPEN_FILES),\n ID_AND_NAME(ERROR_ACCESS_DENIED),\n ID_AND_NAME(ERROR_INVALID_HANDLE),\n ID_AND_NAME(ERROR_ARENA_TRASHED),\n ID_AND_NAME(ERROR_NOT_ENOUGH_MEMORY),\n ID_AND_NAME(ERROR_INVALID_BLOCK),\n ID_AND_NAME(ERROR_BAD_ENVIRONMENT),\n ID_AND_NAME(ERROR_BAD_FORMAT),\n ID_AND_NAME(ERROR_INVALID_ACCESS),\n ID_AND_NAME(ERROR_INVALID_DATA),\n ID_AND_NAME(ERROR_INVALID_DRIVE),\n ID_AND_NAME(ERROR_CURRENT_DIRECTORY),\n ID_AND_NAME(ERROR_NOT_SAME_DEVICE),\n ID_AND_NAME(ERROR_NO_MORE_FILES)\n};\n\nconst char * error_name = IdToName(GetLastError(), WindowsErrorTable);\n IdToName std::lower_bound switch #define ID_AND_NAME(x) case x: return #x\n\nconst char * WindowsErrorToName(int id)\n{\n switch(id)\n {\n ID_AND_NAME(ERROR_INVALID_FUNCTION);\n ID_AND_NAME(ERROR_FILE_NOT_FOUND);\n ID_AND_NAME(ERROR_PATH_NOT_FOUND);\n ID_AND_NAME(ERROR_TOO_MANY_OPEN_FILES);\n ID_AND_NAME(ERROR_ACCESS_DENIED);\n ID_AND_NAME(ERROR_INVALID_HANDLE);\n ID_AND_NAME(ERROR_ARENA_TRASHED);\n ID_AND_NAME(ERROR_NOT_ENOUGH_MEMORY);\n ID_AND_NAME(ERROR_INVALID_BLOCK);\n ID_AND_NAME(ERROR_BAD_ENVIRONMENT);\n ID_AND_NAME(ERROR_BAD_FORMAT);\n ID_AND_NAME(ERROR_INVALID_ACCESS);\n ID_AND_NAME(ERROR_INVALID_DATA);\n ID_AND_NAME(ERROR_INVALID_DRIVE);\n ID_AND_NAME(ERROR_CURRENT_DIRECTORY);\n ID_AND_NAME(ERROR_NOT_SAME_DEVICE);\n ID_AND_NAME(ERROR_NO_MORE_FILES);\n default: return NULL;\n }\n}\n" }, { "answer_id": 13188585, "author": "Ben", "author_id": 385273, "author_profile": "https://Stackoverflow.com/users/385273", "pm_score": 3, "selected": false, "text": "#define stringify( name ) # name\n\nenum MyEnum {\n ENUMVAL1\n};\n...stuff...\n\nstringify(EnumName::ENUMVAL1); // Returns MyEnum::ENUMVAL1\n" }, { "answer_id": 15270402, "author": "kassak", "author_id": 1904007, "author_profile": "https://Stackoverflow.com/users/1904007", "pm_score": 0, "selected": false, "text": "#pragma once\n#include <boost/unordered_map.hpp>\n\nnamespace enumeration\n{\n\n struct enumerator_base : boost::noncopyable\n {\n typedef\n boost::unordered_map<int, std::wstring>\n kv_storage_t;\n typedef\n kv_storage_t::value_type\n kv_type;\n kv_storage_t const & kv() const\n {\n return storage_;\n }\n\n LPCWSTR name(int i) const\n {\n kv_storage_t::const_iterator it = storage_.find(i);\n if(it != storage_.end())\n return it->second.c_str();\n return L\"empty\";\n }\n\n protected:\n kv_storage_t storage_;\n };\n\n template<class T>\n struct enumerator;\n\n template<class D>\n struct enum_singleton : enumerator_base\n {\n static enumerator_base const & instance()\n {\n static D inst;\n return inst;\n }\n };\n}\n\n#define QENUM_ENTRY(K, V, N) K, N storage_.insert(std::make_pair((int)K, V));\n\n#define QBEGIN_ENUM(NAME, C) \\\nenum NAME \\\n{ \\\n C \\\n} \\\n}; \\\n} \\\n\n#define QEND_ENUM(NAME) \\\n}; \\\nnamespace enumeration \\\n{ \\\ntemplate<> \\\nstruct enumerator<NAME>\\\n : enum_singleton< enumerator<NAME> >\\\n{ \\\n enumerator() \\\n {\n\n//usage\n/*\nQBEGIN_ENUM(test_t,\n QENUM_ENTRY(test_entry_1, L\"number uno\",\n QENUM_ENTRY(test_entry_2, L\"number dos\",\n QENUM_ENTRY(test_entry_3, L\"number tres\",\nQEND_ENUM(test_t)))))\n*/\n enumeration::enum_singleton<your_enum>::instance() kv_storage_t boost::bimap" }, { "answer_id": 16013017, "author": "Andrii Syrokomskyi", "author_id": 963948, "author_profile": "https://Stackoverflow.com/users/963948", "pm_score": 0, "selected": false, "text": "#include <EnumString.h>\n\nenum FORM {\n F_NONE = 0,\n F_BOX,\n F_CUBE,\n F_SPHERE,\n};\n Begin_Enum_String( FORM )\n{\n Enum_String( F_NONE );\n Enum_String( F_BOX );\n Enum_String( F_CUBE );\n Enum_String( F_SPHERE );\n}\nEnd_Enum_String;\n enum FORM f = ...\nconst std::string& str = EnumString< FORM >::From( f );\n assert( EnumString< FORM >::To( f, str ) );\n" }, { "answer_id": 22067277, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#include <stdarg.h>\n#include <algorithm>\n#include <string> \n#include <vector>\n#include <sstream>\n#include <map>\n\n#define SMART_ENUM(EnumName, ...) \\\nclass EnumName \\\n{ \\\nprivate: \\\n static std::map<int, std::string> nameMap; \\\npublic: \\\n enum {__VA_ARGS__}; \\\nprivate: \\\n static std::map<int, std::string> initMap() \\\n { \\\n using namespace std; \\\n \\\n int val = 0; \\\n string buf_1, buf_2, str = #__VA_ARGS__; \\\n replace(str.begin(), str.end(), '=', ' '); \\\n stringstream stream(str); \\\n vector<string> strings; \\\n while (getline(stream, buf_1, ',')) \\\n strings.push_back(buf_1); \\\n map<int, string> tmp; \\\n for(vector<string>::iterator it = strings.begin(); \\\n it != strings.end(); \\\n ++it) \\\n { \\\n buf_1.clear(); buf_2.clear(); \\\n stringstream localStream(*it); \\\n localStream>> buf_1 >> buf_2; \\\n if(buf_2.size() > 0) \\\n val = atoi(buf_2.c_str()); \\\n tmp[val++] = buf_1; \\\n } \\\n return tmp; \\\n } \\\npublic: \\\n static std::string toString(int aInt) \\\n { \\\n return nameMap[aInt]; \\\n } \\\n}; \\\nstd::map<int, std::string> \\\nEnumName::nameMap = EnumName::initMap();\n SMART_ENUM(MyEnum, ONE=1, TWO, THREE, TEN=10, ELEVEN)\ncout<<MyEnum::toString(MyEnum::TWO);\ncout<<MyEnum::toString(10);\n" }, { "answer_id": 22255215, "author": "OlivierB", "author_id": 586277, "author_profile": "https://Stackoverflow.com/users/586277", "pm_score": 0, "selected": false, "text": "#include <string>\n#include <iostream>\n#include <stdexcept>\n#include <algorithm>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\n#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)\n#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)\n#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)\n#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)\n#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)\n#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)\n#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)\n#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)\n#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)\n#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)\n#define MAKE_STRING10_(str) #str\n\n#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)\n#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)\n\n#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \\\n attribute std::istream& operator>>(std::istream& is, name& e) { \\\n const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \\\n std::string str; \\\n std::istream& r = is >> str; \\\n const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \\\n const std::vector<std::string> enumStr(name##Str, name##Str + len); \\\n const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \\\n if (it != enumStr.end())\\\n e = name(it - enumStr.begin()); \\\n else \\\n throw std::runtime_error(\"Value \\\"\" + str + \"\\\" is not part of enum \"#name); \\\n return r; \\\n }; \\\n attribute std::ostream& operator<<(std::ostream& os, const name& e) { \\\n const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \\\n return (os << name##Str[e]); \\\n }\n // Declare global enum\nenum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);\n\nclass Essai {\npublic:\n // Declare enum inside class\n enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);\n\n};\n\nint main() {\n std::cout << Essai::Item1 << std::endl;\n\n Essai::Test ddd = Essai::Item1;\n std::cout << ddd << std::endl;\n\n std::istringstream strm(\"Item2\");\n strm >> ddd;\n\n std::cout << (int) ddd << std::endl;\n std::cout << ddd << std::endl;\n}\n" }, { "answer_id": 23290572, "author": "user3510054", "author_id": 3510054, "author_profile": "https://Stackoverflow.com/users/3510054", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <map>\n#define IDMAP(x) (x,#x)\n\nstd::map<int , std::string> enToStr;\nclass mapEnumtoString\n{\npublic:\n mapEnumtoString(){ }\n mapEnumtoString& operator()(int i,std::string str)\n {\n enToStr[i] = str;\n return *this;\n }\npublic:\n std::string operator [] (int i)\n {\n return enToStr[i];\n }\n\n};\nmapEnumtoString k;\nmapEnumtoString& init()\n{\n return k;\n}\n\nint main()\n{\n\ninit()\n IDMAP(1)\n IDMAP(2)\n IDMAP(3)\n IDMAP(4)\n IDMAP(5);\nstd::cout<<enToStr[1];\nstd::cout<<enToStr[2];\nstd::cout<<enToStr[3];\nstd::cout<<enToStr[4];\nstd::cout<<enToStr[5];\n}\n" }, { "answer_id": 23402871, "author": "Debdatta Basu", "author_id": 1078703, "author_profile": "https://Stackoverflow.com/users/1078703", "pm_score": 4, "selected": false, "text": "#define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \\\ninline std::ostream& operator<<(std::ostream& os, name value) { \\\nstd::string enumName = #name; \\\nstd::string str = #__VA_ARGS__; \\\nint len = str.length(); \\\nstd::vector<std::string> strings; \\\nstd::ostringstream temp; \\\nfor(int i = 0; i < len; i ++) { \\\nif(isspace(str[i])) continue; \\\n else if(str[i] == ',') { \\\n strings.push_back(temp.str()); \\\n temp.str(std::string());\\\n } \\\n else temp<< str[i]; \\\n} \\\nstrings.push_back(temp.str()); \\\nos << enumName << \"::\" << strings[static_cast<int>(value)]; \\\nreturn os;} \n AWESOME_MAKE_ENUM(Animal,\n DOG,\n CAT,\n HORSE\n);\n" }, { "answer_id": 23415866, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 2, "selected": false, "text": "MyEnum fromString(const string&) SMART_ENUM(MyEnum, ONE=1, TWO, THREE, TEN=10, ELEVEN)\nMyEnum foo = MyEnum::TWO;\ncout << MyEnum::toString(foo); // static method\ncout << foo.toString(); // member method\ncout << MyEnum::toString(MyEnum::TWO);\ncout << MyEnum::toString(10);\nMyEnum foo = myEnum::fromString(\"TWO\");\n\n// C++11 iteration over all values\nfor( auto x : MyEnum::allValues() )\n{\n cout << x.toString() << endl;\n}\n #define SMART_ENUM(EnumName, ...) \\\nclass EnumName \\\n{ \\\npublic: \\\n EnumName() : value(0) {} \\\n EnumName(int x) : value(x) {} \\\npublic: \\\n enum {__VA_ARGS__}; \\\nprivate: \\\n static void initMap(std::map<int, std::string>& tmp) \\\n { \\\n using namespace std; \\\n \\\n int val = 0; \\\n string buf_1, buf_2, str = #__VA_ARGS__; \\\n replace(str.begin(), str.end(), '=', ' '); \\\n stringstream stream(str); \\\n vector<string> strings; \\\n while (getline(stream, buf_1, ',')) \\\n strings.push_back(buf_1); \\\n for(vector<string>::iterator it = strings.begin(); \\\n it != strings.end(); \\\n ++it) \\\n { \\\n buf_1.clear(); buf_2.clear(); \\\n stringstream localStream(*it); \\\n localStream>> buf_1 >> buf_2; \\\n if(buf_2.size() > 0) \\\n val = atoi(buf_2.c_str()); \\\n tmp[val++] = buf_1; \\\n } \\\n } \\\n int value; \\\npublic: \\\n operator int () const { return value; } \\\n std::string toString(void) const { \\\n return toString(value); \\\n } \\\n static std::string toString(int aInt) \\\n { \\\n return nameMap()[aInt]; \\\n } \\\n static EnumName fromString(const std::string& s) \\\n { \\\n auto it = find_if(nameMap().begin(), nameMap().end(), [s](const std::pair<int,std::string>& p) { \\\n return p.second == s; \\\n }); \\\n if (it == nameMap().end()) { \\\n /*value not found*/ \\\n throw EnumName::Exception(); \\\n } else { \\\n return EnumName(it->first); \\\n } \\\n } \\\n class Exception : public std::exception {}; \\\n static std::map<int,std::string>& nameMap() { \\\n static std::map<int,std::string> nameMap0; \\\n if (nameMap0.size() ==0) initMap(nameMap0); \\\n return nameMap0; \\\n } \\\n static std::vector<EnumName> allValues() { \\\n std::vector<EnumName> x{ __VA_ARGS__ }; \\\n return x; \\\n } \\\n bool operator<(const EnumName a) const { return (int)*this < (int)a; } \\\n}; \n" }, { "answer_id": 24296298, "author": "serge", "author_id": 3754427, "author_profile": "https://Stackoverflow.com/users/3754427", "pm_score": 3, "selected": false, "text": "#include <map>\nenum MyEnum { AA, BB, CC, DD };\n\nstatic std::map< MyEnum, const char * > info = {\n {AA, \"This is an apple\"},\n {BB, \"This is a book\"},\n {CC, \"This is a coffee\"},\n {DD, \"This is a door\"}\n};\n\nvoid main()\n{\n std::cout << info[AA] << endl\n << info[BB] << endl\n << info[CC] << endl\n << info[DD] << endl;\n}\n" }, { "answer_id": 25415021, "author": "FractalSpace", "author_id": 175169, "author_profile": "https://Stackoverflow.com/users/175169", "pm_score": 2, "selected": false, "text": "#include <iostream>\n\n#define ENUM_TXT \\\nX(Red) \\\nX(Green) \\\nX(Blue) \\\nX(Cyan) \\\nX(Yellow) \\\nX(Magenta) \\\n\nenum Colours {\n# define X(a) a,\nENUM_TXT\n# undef X\n ColoursCount\n};\n\nchar const* const colours_str[] = {\n# define X(a) #a,\nENUM_TXT\n# undef X\n 0\n};\n\nstd::ostream& operator<<(std::ostream& os, enum Colours c)\n{\n if (c >= ColoursCount || c < 0) return os << \"???\";\n return os << colours_str[c] << std::endl;\n}\n\nint main()\n{\n std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;\n}\n" }, { "answer_id": 25554855, "author": "lopes", "author_id": 2777927, "author_profile": "https://Stackoverflow.com/users/2777927", "pm_score": 2, "selected": false, "text": "#include <boost/preprocessor.hpp>\n\n#define X_STR_ENUM_TOSTRING_CASE(r, data, elem) \\\n case elem : return BOOST_PP_STRINGIZE(elem);\n\n#define X_ENUM_STR_TOENUM_IF(r, data, elem) \\\n else if(data == BOOST_PP_STRINGIZE(elem)) return elem;\n\n#define STR_ENUM(name, enumerators) \\\n enum name { \\\n BOOST_PP_SEQ_ENUM(enumerators) \\\n }; \\\n \\\n inline const QString enumToStr(name v) \\\n { \\\n switch (v) \\\n { \\\n BOOST_PP_SEQ_FOR_EACH( \\\n X_STR_ENUM_TOSTRING_CASE, \\\n name, \\\n enumerators \\\n ) \\\n \\\n default: \\\n return \"[Unknown \" BOOST_PP_STRINGIZE(name) \"]\"; \\\n } \\\n } \\\n \\\n template <typename T> \\\n inline const T strToEnum(QString v); \\\n \\\n template <> \\\n inline const name strToEnum(QString v) \\\n { \\\n if(v==\"\") \\\n throw std::runtime_error(\"Empty enum value\"); \\\n \\\n BOOST_PP_SEQ_FOR_EACH( \\\n X_ENUM_STR_TOENUM_IF, \\\n v, \\\n enumerators \\\n ) \\\n \\\n else \\\n throw std::runtime_error( \\\n QString(\"[Unknown value %1 for enum %2]\") \\\n .arg(v) \\\n .arg(BOOST_PP_STRINGIZE(name)) \\\n .toStdString().c_str()); \\\n }\n STR_ENUM\n(\n SERVICE_RELOAD,\n (reload_log)\n (reload_settings)\n (reload_qxml_server)\n)\n SERVICE_RELOAD serviceReloadEnum = strToEnum<SERVICE_RELOAD>(\"reload_log\");\nQString serviceReloadStr = enumToStr(reload_log);\n" }, { "answer_id": 40370302, "author": "Alexandru Irimiea", "author_id": 4806882, "author_profile": "https://Stackoverflow.com/users/4806882", "pm_score": 2, "selected": false, "text": "ToString() FromString() .hpp .cpp .cpp # This script is used to generate strings from C++ enums\n\nimport re\nimport sys\nimport os\n\nfileName = sys.argv[1]\nenumName = os.path.basename(os.path.splitext(fileName)[0])\n\nwith open(fileName, 'r') as f:\n content = f.read().replace('\\n', '')\n\nsearchResult = re.search('enum(.*)\\{(.*?)\\};', content)\ntokens = searchResult.group(2)\ntokens = tokens.split(',')\ntokens = map(str.strip, tokens)\ntokens = map(lambda token: re.search('([a-zA-Z0-9_]*)', token).group(1), tokens)\n\ntextOut = ''\ntextOut += '\\n#include \"' + enumName + '.hpp\"\\n\\n'\ntextOut += 'namespace myns\\n'\ntextOut += '{\\n'\ntextOut += ' std::string ToString(ErrorCode errorCode)\\n'\ntextOut += ' {\\n'\ntextOut += ' switch (errorCode)\\n'\ntextOut += ' {\\n'\n\nfor token in tokens:\n textOut += ' case ' + enumName + '::' + token + ':\\n'\n textOut += ' return \"' + token + '\";\\n'\n\ntextOut += ' default:\\n'\ntextOut += ' return \"Last\";\\n'\ntextOut += ' }\\n'\ntextOut += ' }\\n'\ntextOut += '\\n'\ntextOut += ' ' + enumName + ' FromString(const std::string &errorCode)\\n'\ntextOut += ' {\\n'\ntextOut += ' if (\"' + tokens[0] + '\" == errorCode)\\n'\ntextOut += ' {\\n'\ntextOut += ' return ' + enumName + '::' + tokens[0] + ';\\n'\ntextOut += ' }\\n'\n\nfor token in tokens[1:]:\n textOut += ' else if(\"' + token + '\" == errorCode)\\n'\n textOut += ' {\\n'\n textOut += ' return ' + enumName + '::' + token + ';\\n'\n textOut += ' }\\n'\n\ntextOut += '\\n'\ntextOut += ' return ' + enumName + '::Last;\\n'\ntextOut += ' }\\n'\ntextOut += '}\\n'\n\nfileOut = open(enumName + '.cpp', 'w')\nfileOut.write(textOut)\n #pragma once\n\n#include <string>\n#include <cstdint>\n\nnamespace myns\n{\n enum class ErrorCode : uint32_t\n {\n OK = 0,\n OutOfSpace,\n ConnectionFailure,\n InvalidJson,\n DatabaseFailure,\n HttpError,\n FileSystemError,\n FailedToEncrypt,\n FailedToDecrypt,\n EndOfFile,\n FailedToOpenFileForRead,\n FailedToOpenFileForWrite,\n FailedToLaunchProcess,\n\n Last\n };\n\n std::string ToString(ErrorCode errorCode);\n ErrorCode FromString(const std::string &errorCode);\n}\n python generate_enum_strings.py ErrorCode.hpp #include \"ErrorCode.hpp\"\n\nnamespace myns\n{\n std::string ToString(ErrorCode errorCode)\n {\n switch (errorCode)\n {\n case ErrorCode::OK:\n return \"OK\";\n case ErrorCode::OutOfSpace:\n return \"OutOfSpace\";\n case ErrorCode::ConnectionFailure:\n return \"ConnectionFailure\";\n case ErrorCode::InvalidJson:\n return \"InvalidJson\";\n case ErrorCode::DatabaseFailure:\n return \"DatabaseFailure\";\n case ErrorCode::HttpError:\n return \"HttpError\";\n case ErrorCode::FileSystemError:\n return \"FileSystemError\";\n case ErrorCode::FailedToEncrypt:\n return \"FailedToEncrypt\";\n case ErrorCode::FailedToDecrypt:\n return \"FailedToDecrypt\";\n case ErrorCode::EndOfFile:\n return \"EndOfFile\";\n case ErrorCode::FailedToOpenFileForRead:\n return \"FailedToOpenFileForRead\";\n case ErrorCode::FailedToOpenFileForWrite:\n return \"FailedToOpenFileForWrite\";\n case ErrorCode::FailedToLaunchProcess:\n return \"FailedToLaunchProcess\";\n case ErrorCode::Last:\n return \"Last\";\n default:\n return \"Last\";\n }\n }\n\n ErrorCode FromString(const std::string &errorCode)\n {\n if (\"OK\" == errorCode)\n {\n return ErrorCode::OK;\n }\n else if(\"OutOfSpace\" == errorCode)\n {\n return ErrorCode::OutOfSpace;\n }\n else if(\"ConnectionFailure\" == errorCode)\n {\n return ErrorCode::ConnectionFailure;\n }\n else if(\"InvalidJson\" == errorCode)\n {\n return ErrorCode::InvalidJson;\n }\n else if(\"DatabaseFailure\" == errorCode)\n {\n return ErrorCode::DatabaseFailure;\n }\n else if(\"HttpError\" == errorCode)\n {\n return ErrorCode::HttpError;\n }\n else if(\"FileSystemError\" == errorCode)\n {\n return ErrorCode::FileSystemError;\n }\n else if(\"FailedToEncrypt\" == errorCode)\n {\n return ErrorCode::FailedToEncrypt;\n }\n else if(\"FailedToDecrypt\" == errorCode)\n {\n return ErrorCode::FailedToDecrypt;\n }\n else if(\"EndOfFile\" == errorCode)\n {\n return ErrorCode::EndOfFile;\n }\n else if(\"FailedToOpenFileForRead\" == errorCode)\n {\n return ErrorCode::FailedToOpenFileForRead;\n }\n else if(\"FailedToOpenFileForWrite\" == errorCode)\n {\n return ErrorCode::FailedToOpenFileForWrite;\n }\n else if(\"FailedToLaunchProcess\" == errorCode)\n {\n return ErrorCode::FailedToLaunchProcess;\n }\n else if(\"Last\" == errorCode)\n {\n return ErrorCode::Last;\n }\n\n return ErrorCode::Last;\n }\n}\n" }, { "answer_id": 43415137, "author": "cibercitizen1", "author_id": 286335, "author_profile": "https://Stackoverflow.com/users/286335", "pm_score": 0, "selected": false, "text": "int main () {\n\n VERB a = VERB::GET;\n VERB b = VERB::GET;\n VERB c = VERB::POST;\n VERB d = VERB::PUT;\n VERB e = VERB::DELETE;\n\n\n std::cout << a.toString() << std::endl;\n\n std::cout << a << std::endl;\n\n if ( a == VERB::GET ) {\n std::cout << \"yes\" << std::endl;\n }\n\n if ( a == b ) {\n std::cout << \"yes\" << std::endl;\n }\n\n if ( a != c ) {\n std::cout << \"no\" << std::endl;\n }\n\n}\n // -----------------------------------------------------------\n// -----------------------------------------------------------\nclass VERB {\n\nprivate:\n\n // private constants\n enum Verb {GET_=0, POST_, PUT_, DELETE_};\n\n // private string values\n static const std::string theStrings[];\n\n // private value\n const Verb value;\n const std::string text;\n\n // private constructor\n VERB (Verb v) :\n value(v), text (theStrings[v])\n {\n // std::cout << \" constructor \\n\";\n }\n\npublic:\n\n operator const char * () const { return text.c_str(); }\n\n operator const std::string () const { return text; }\n\n const std::string toString () const { return text; }\n\n bool operator == (const VERB & other) const { return (*this).value == other.value; }\n\n bool operator != (const VERB & other) const { return ! ( (*this) == other); }\n\n // ---\n\n static const VERB GET;\n static const VERB POST;\n static const VERB PUT;\n static const VERB DELETE;\n\n};\n\nconst std::string VERB::theStrings[] = {\"GET\", \"POST\", \"PUT\", \"DELETE\"};\n\nconst VERB VERB::GET = VERB ( VERB::Verb::GET_ );\nconst VERB VERB::POST = VERB ( VERB::Verb::POST_ );\nconst VERB VERB::PUT = VERB ( VERB::Verb::PUT_ );\nconst VERB VERB::DELETE = VERB ( VERB::Verb::DELETE_ );\n// end of file\n" }, { "answer_id": 45175792, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "enum log_level {INFO, WARNING, ERROR};\n...\nvoid logger::write(const std::string log, const log_level l) {\n ...\n std::string s = (l == INFO) ? \"INFO\" : \n (l == WARNING) ? \"WARNING\" : \n (l == ERROR) ? \"ERROR\" : \"UNKNOWN\";\n ...\n}\n...\n" }, { "answer_id": 51255099, "author": "Joe C", "author_id": 9344166, "author_profile": "https://Stackoverflow.com/users/9344166", "pm_score": 0, "selected": false, "text": "enum class genre { Fiction, NonFiction, Periodical, Biography, Children };\n\nvector<string>genre_tbl { \"Fiction\", \"NonFiction\", \"Periodical\", \"Biography\", \"Children\" };\n Fiction = 0\nNonFiction = 1\nPeriodical = 2\nBiography = 3\nChildren = 4\n string s1 = genre_tbl[int(genre::fiction)];\n class book {...};\nostream& operator<<(ostream& os, genre g) { return os << genre_tbl[int(g)]; }\n\nbook b1;\nb1.Gen = genre(0)\ncout << b1.Gen;\n" }, { "answer_id": 52264973, "author": "Francois Bertrand", "author_id": 5669529, "author_profile": "https://Stackoverflow.com/users/5669529", "pm_score": 2, "selected": false, "text": "#define MAKE_ENUM(VAR) VAR,\n#define MAKE_STRINGS(VAR) #VAR,\n#define MAKE_ENUM_AND_STRINGS(source, enumName, enumStringName) \\\n enum enumName { \\\n source(MAKE_ENUM) \\\n };\\\nconst char* const enumStringName[] = { \\\n source(MAKE_STRINGS) \\\n };\n #define SOME_ENUM(DO) \\\n DO(Foo) \\\n DO(Bar) \\\n DO(Baz)\n...\nMAKE_ENUM_AND_STRINGS(SOME_ENUM, someEnum, someEnumNames)\n" }, { "answer_id": 52669478, "author": "Nick", "author_id": 3233, "author_profile": "https://Stackoverflow.com/users/3233", "pm_score": 2, "selected": false, "text": "enum class MyEnum\n{\n Zero = 0,\n One = 1,\n Two = 2\n};\n\nponder::Enum::declare<MyEnum>()\n .value(\"Zero\", MyEnum::Zero)\n .value(\"One\", MyEnum::One)\n .value(\"Two\", MyEnum::Two);\n\nponder::EnumObject zero(MyEnum::Zero);\n\nzero.name(); // -> \"Zero\"\n" }, { "answer_id": 72580429, "author": "cppguy", "author_id": 1325084, "author_profile": "https://Stackoverflow.com/users/1325084", "pm_score": 2, "selected": false, "text": "constexpr // Create a mapping between the enum value and the string\n#define MY_ENUM_LIST(DECLARE) \\\nDECLARE(foo, \"This is a foo!\") \\\nDECLARE(bar, \"This is a bar!\") \\\nDECLARE(bam, \"This is a bam!\")\n\n// Define the enum officially\nenum class MyEnum {\n#define ENUM_ENTRY(NAME, TEXT) NAME, // TEXT expressly not used here\n MY_ENUM_LIST(ENUM_ENTRY)\n#undef ENUM_ENTRY // Always undef as a good citizen ;)\n};\n\n// Create a template function that would fail to compile if called\ntemplate <MyEnum KEY> constexpr const char* MyEnumText() {}\n\n// Specialize that bad function with versions that map the enum value to the string declared above\n#define ENUM_FUNC(NAME, TEXT) template <> constexpr const char* MyEnumText<MyEnum::NAME>() { return TEXT; }\nMY_ENUM_LIST(ENUM_FUNC)\n#undef ENUM_FUNC\n MyEnumText const auto text{::MyEnumText<MyEnum::foo>()}; // inlines beautifully\n constexpr const char* MyEnumText(MyEnum key) {\n switch (key) {\n#define ENUM_CASE(NAME, TEXT) case MyEnum::NAME: return MyEnumText<MyEnum::NAME>();\n MY_ENUM_LIST(ENUM_CASE)\n#undef ENUM_CASE\n }\n return nullptr;\n}\n const auto text{::MyEnumText(MyEnum::foo)}; // inlines beautifully\n const MyEnum e{GetTheEnumValue()};\nconst auto text{::MyEnumText(e)};\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21648/" ]
201,602
<p>I am using wordpress and use custom permalink structure: /%category%/%postname%/</p> <p>My problem is that a decent number of people link to the site without including the trailing slash in the URL, so users get a 404 page.</p> <p>I'm using the default .htaccess file that comes with wordpress because no solution I've tried has worked. I've tried using the Redirection plugin, with no success. </p> <p>I'd gladly link to the site, but I don't want it to be construed as self-promotion. If you ask, I'll provide a link.</p> <p>Could anyone help me find a plugin or provide some .htaccess entries to help resolve this?</p> <p>Thanks very much!</p>
[ { "answer_id": 201618, "author": "Dominic Rodger", "author_id": 20972, "author_profile": "https://Stackoverflow.com/users/20972", "pm_score": 2, "selected": false, "text": "/%category%/%postname%(/?)\n" }, { "answer_id": 214564, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "RewriteRule ^(([^\\/]+\\/)*[^\\/\\.]+)$ $1/\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25066/" ]
201,607
<p>I'd like to do something like this:</p> <pre><code>Dim Foo as String = "a,b,c,d,e" Dim Boo as List(of String) = Foo.Split(","c) </code></pre> <p>Of course <code>Foo.Split</code> returns a one-dimensional array of <code>String</code>, not a generic <code>List</code>. Is there a way to do this without iterating through the array to turn it into a generic <code>List</code>?</p>
[ { "answer_id": 201622, "author": "IAmCodeMonkey", "author_id": 27613, "author_profile": "https://Stackoverflow.com/users/27613", "pm_score": 0, "selected": false, "text": "Dim strings As List<string> = string_variable.Split().ToList<string>();\n" }, { "answer_id": 201627, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 3, "selected": false, "text": "String foo = \"a,b,c,d,e\";\nList<String> boo = new List<String>(foo.Split(\",\"));\n" }, { "answer_id": 201633, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 6, "selected": true, "text": "Dim foo As String = \"a,b,c,d,e\"\nDim boo As New List(Of String)(foo.Split(\",\"c))\n" }, { "answer_id": 201642, "author": "amcoder", "author_id": 26898, "author_profile": "https://Stackoverflow.com/users/26898", "pm_score": 2, "selected": false, "text": "Dim Foo as String = \"a,b,c,d,e\"\nDim Boo as List(of String)\n\nBoo.AddRange(Foo.Split(\",\"c))\n" }, { "answer_id": 320699, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 0, "selected": false, "text": "var values = labels.Split(\" \"[0]).ToList<string>();\n" }, { "answer_id": 33397537, "author": "Gopher", "author_id": 2317134, "author_profile": "https://Stackoverflow.com/users/2317134", "pm_score": 0, "selected": false, "text": "Return New List(Of String)(IO.File.ReadAllLines(sFileName))\n" }, { "answer_id": 52590547, "author": "Tim Makins", "author_id": 3750058, "author_profile": "https://Stackoverflow.com/users/3750058", "pm_score": 0, "selected": false, "text": "Dim Foo as String = \"a,b,c,d,e\"\nDim Boo as List(of String)\nBoo = Split(Foo, \",\").ToList\n Dim Foo as String = \"a<blah>b<blah>c<blah>d<blah>e\"\nDim Boo as List(of String)\nBoo = Split(Foo, \"<blah>\").ToList\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
201,615
<p>Can some one post an example of using syslog outputter for log4r, I am currently using stdout but want to log to syslog.</p> <pre><code>mylog = Logger.new 'mylog' mylog.outputters = Outputter.stdout mylog.info "Starting up." </code></pre> <p>raj</p> <hr> <p>Thanks also to the following blog posts.<br> </p> <p><a href="http://angrez.blogspot.com/2006/12/log4r-usage-and-examples.html" rel="nofollow noreferrer">Angrez's blog: Log4r - Usage and Examples</a></p> <p><a href="http://programmingstuff.wikidot.com/log4r" rel="nofollow noreferrer">ProgrammingStuff: Log4r</a></p>
[ { "answer_id": 203848, "author": "Rajkumar S", "author_id": 25453, "author_profile": "https://Stackoverflow.com/users/25453", "pm_score": 4, "selected": true, "text": "require 'rubygems'\nrequire 'log4r'\nrequire 'log4r/outputter/syslogoutputter'\nmylog = Logger.new 'mylog'\nmylog.outputters = SyslogOutputter.new(\"f1\", :ident => \"myscript\")\nmylog.info \"Starting up.\"\n" }, { "answer_id": 887063, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 1, "selected": false, "text": "require 'rubygems'\nrequire 'log4r'\nrequire 'log4r/outputter/syslogoutputter'\n\n# The outputter needs some love to avoid attempts to reopen syslog. Most of this is cargo-culted from source.\nclass Log4r::SyslogOutputter\n def initialize(_name, hash={})\n super(_name, hash)\n ident = (hash[:ident] or hash['ident'] or _name)\n logopt = (hash[:logopt] or hash['logopt'] or LOG_PID | LOG_CONS).to_i\n facility = (hash[:facility] or hash['facility'] or LOG_USER).to_i\n if Syslog.opened? then\n @syslog = Syslog\n else\n @syslog = Syslog.open(ident, logopt, facility)\n end\n end\nend\n\nRAILS_DEFAULT_LOGGER = Log4r::Logger.new 'mylog'\nconfig.logger = RAILS_DEFAULT_LOGGER\nconfig.logger.outputters = Log4r::SyslogOutputter.new(\"f1\", :ident=>\"RoR\")\nconfig.logger.info \"Starting up.\"\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25453/" ]
201,616
<p>We have a C# service that is deployed to a remote customer system. The application writes a substantial amount of "diagnostic" information to the console (i.e. Console.WriteLine()). The service isn't "doing what it should." How can we capture the console output from the service in another application?</p> <p>A WinForm version the application can be loaded at the customer location. It, unfortunately, functions correctly.</p> <p>Update:</p> <p>We are able to change the change the service, but would prefer not to make major changes at this time.</p> <p>We are also logging to MSMQ, but only for "important" events. This service does interact with MSMQ for its normal operations. Or, at least, it should. The service doesn't seem to be pulling items from MSMQ when the WinForm version does. So, writing the messages that are going to the console could be problematic.</p>
[ { "answer_id": 201810, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 3, "selected": false, "text": "EventLog log;\nstring logsource = \"MyService\";\n\n// execute once per invocation\nif (!System.Diagnostics.EventLog.SourceExists(logsource))\n{\n System.Diagnostics.EventLog.CreateEventSource(\n logsource, \"Application\");\n}\nlog = new EventLog();\nlog.Source = logsource;\nlog.Log = \"Application\";\n\n// replace console logging with this\nlog.WriteEntry(message, EventLogEntryType.Information);\n" }, { "answer_id": 201965, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": false, "text": "<configuration>\n <system.diagnostics>\n <trace autoflush=\"false\" indentsize=\"4\">\n <listeners>\n <add name=\"configConsoleListener\"\n type=\"System.Diagnostics.ConsoleTraceListener\" />\n </listeners>\n </trace>\n </system.diagnostics>\n </configuration>\n" }, { "answer_id": 33809685, "author": "Mike E", "author_id": 5582300, "author_profile": "https://Stackoverflow.com/users/5582300", "pm_score": 1, "selected": false, "text": "cmd.exe /c c:\\myService\\myservice.exe cmd.exe /c c:\\myService\\myservice.exe" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27887/" ]
201,621
<p>In MySQL, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as <a href="https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships">this Oracle question</a>, but for MySQL.</p>
[ { "answer_id": 201647, "author": "Node", "author_id": 7190, "author_profile": "https://Stackoverflow.com/users/7190", "pm_score": 7, "selected": false, "text": "SELECT * FROM information_schema.TABLE_CONSTRAINTS \nWHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' \nAND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'\nAND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';\n" }, { "answer_id": 201676, "author": "Christian Oudard", "author_id": 3757, "author_profile": "https://Stackoverflow.com/users/3757", "pm_score": 2, "selected": false, "text": "USE information_schema;\ntee mysql_output\nSELECT * FROM TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_SCHEMA = 'database_name';\nnotee\n grep 'refs_tablename_id' mysql_output\n" }, { "answer_id": 201678, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 11, "selected": true, "text": "SELECT \n TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME\nFROM\n INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE\n REFERENCED_TABLE_SCHEMA = '<database>' AND\n REFERENCED_TABLE_NAME = '<table>';\n SELECT \n TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME\nFROM\n INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE\n REFERENCED_TABLE_SCHEMA = '<database>' AND\n REFERENCED_TABLE_NAME = '<table>' AND\n REFERENCED_COLUMN_NAME = '<column>';\n" }, { "answer_id": 11302791, "author": "Andy", "author_id": 850977, "author_profile": "https://Stackoverflow.com/users/850977", "pm_score": 6, "selected": false, "text": "USE '<yourschema>';\n\nSELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME \nFROM information_schema.TABLE_CONSTRAINTS i \nLEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME \nWHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' \nAND i.TABLE_SCHEMA = DATABASE()\nAND i.TABLE_NAME = '<yourtable>';\n USE '<yourschema>';\n\nSELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME \nFROM information_schema.TABLE_CONSTRAINTS i \nLEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME \nWHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' \nAND i.TABLE_SCHEMA = DATABASE();\n SELECT i.TABLE_SCHEMA, i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME \nFROM information_schema.TABLE_CONSTRAINTS i \nLEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME \nWHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY';\n SELECT * TABLE_NAME, ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = '<yourschema>';\n ALTER TABLE `<yourtable>` ENGINE=InnoDB;\n" }, { "answer_id": 17049173, "author": "CenterOrbit", "author_id": 663058, "author_profile": "https://Stackoverflow.com/users/663058", "pm_score": 8, "selected": false, "text": "SHOW CREATE TABLE `<yourtable>`;\n" }, { "answer_id": 17078317, "author": "Daniel Rodas", "author_id": 1609645, "author_profile": "https://Stackoverflow.com/users/1609645", "pm_score": 3, "selected": false, "text": "KEY_COLUMN_USAGE view:\n\nSELECT CONCAT( table_name, '.',\ncolumn_name, ' -> ',\nreferenced_table_name, '.',\nreferenced_column_name ) AS list_of_fks\nFROM information_schema.KEY_COLUMN_USAGE\nWHERE REFERENCED_TABLE_SCHEMA = (your schema name here)\nAND REFERENCED_TABLE_NAME is not null\nORDER BY TABLE_NAME, COLUMN_NAME;\n" }, { "answer_id": 18825955, "author": "Panayotis", "author_id": 339146, "author_profile": "https://Stackoverflow.com/users/339146", "pm_score": 4, "selected": false, "text": "select\n concat(table_name, '.', column_name) as 'foreign key',\n concat(referenced_table_name, '.', referenced_column_name) as 'references',\n constraint_name as 'constraint name'\nfrom\n information_schema.key_column_usage\nwhere\n referenced_table_name is not null;\n select\n concat(table_name, '.', column_name) as 'foreign key',\n concat(referenced_table_name, '.', referenced_column_name) as 'references',\n constraint_name as 'constraint name'\nfrom\n information_schema.key_column_usage\nwhere\n referenced_table_name is not null\n and table_schema = 'database_name';\n" }, { "answer_id": 20543002, "author": "ChrisV", "author_id": 342943, "author_profile": "https://Stackoverflow.com/users/342943", "pm_score": 5, "selected": false, "text": "SELECT CONSTRAINT_NAME, TABLE_NAME, REFERENCED_TABLE_NAME\nFROM information_schema.REFERENTIAL_CONSTRAINTS\nWHERE CONSTRAINT_SCHEMA = '<schema>'\nAND TABLE_NAME = '<table>'\n SELECT CONSTRAINT_NAME, TABLE_NAME, REFERENCED_TABLE_NAME\nFROM information_schema.REFERENTIAL_CONSTRAINTS\nWHERE CONSTRAINT_SCHEMA = '<schema>'\nAND REFERENCED_TABLE_NAME = '<table>'\n" }, { "answer_id": 27476989, "author": "Anthony Vipond", "author_id": 1002324, "author_profile": "https://Stackoverflow.com/users/1002324", "pm_score": 1, "selected": false, "text": "employee_id SELECT DISTINCT TABLE_NAME \nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE COLUMN_NAME IN ('employee_id')\nAND TABLE_SCHEMA='table_name';\n" }, { "answer_id": 28356242, "author": "Hazok", "author_id": 644035, "author_profile": "https://Stackoverflow.com/users/644035", "pm_score": 3, "selected": false, "text": "select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = '<table>';\n" }, { "answer_id": 45598345, "author": "omarjebari", "author_id": 2867894, "author_profile": "https://Stackoverflow.com/users/2867894", "pm_score": 2, "selected": false, "text": "SELECT i.TABLE_SCHEMA, i.TABLE_NAME, \n i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, \n k.COLUMN_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME \n FROM information_schema.TABLE_CONSTRAINTS i \n LEFT JOIN information_schema.KEY_COLUMN_USAGE k \n ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME \n WHERE i.TABLE_SCHEMA = '<TABLE_NAME>' AND i.CONSTRAINT_TYPE = 'FOREIGN KEY' \n ORDER BY i.TABLE_NAME;\n" }, { "answer_id": 63050074, "author": "DJDave", "author_id": 1280840, "author_profile": "https://Stackoverflow.com/users/1280840", "pm_score": 3, "selected": false, "text": "SELECT DISTINCT KCU.TABLE_NAME, KCU.COLUMN_NAME, REFERENCED_TABLE_SCHEMA, KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, UPDATE_RULE, DELETE_RULE #, KCU.*, RC.*\nFROM information_schema.KEY_COLUMN_USAGE KCU\nINNER JOIN information_schema.referential_constraints RC ON KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME\nWHERE TABLE_SCHEMA = (your schema name)\nAND KCU.REFERENCED_TABLE_NAME IS NOT NULL\nORDER BY KCU.TABLE_NAME, KCU.COLUMN_NAME;\n" }, { "answer_id": 63376922, "author": "imatwork", "author_id": 13013884, "author_profile": "https://Stackoverflow.com/users/13013884", "pm_score": 4, "selected": false, "text": "select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY';\n select * from information_schema.table_constraints; show create table tableName;\n" }, { "answer_id": 67779853, "author": "akinuri", "author_id": 2202732, "author_profile": "https://Stackoverflow.com/users/2202732", "pm_score": 1, "selected": false, "text": "SELECT\n KCU.CONSTRAINT_NAME,\n KCU.TABLE_NAME,\n KCU.COLUMN_NAME,\n KCU.REFERENCED_TABLE_NAME,\n KCU.REFERENCED_COLUMN_NAME\nFROM\n INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU\n JOIN INFORMATION_SCHEMA.COLUMNS AS COLS\n ON\n COLS.TABLE_SCHEMA = KCU.TABLE_SCHEMA\n AND COLS.TABLE_NAME = KCU.TABLE_NAME\n AND COLS.COLUMN_NAME = KCU.COLUMN_NAME\nWHERE\n KCU.CONSTRAINT_SCHEMA = {YOUR_SCHEMA_NAME}\n AND KCU.REFERENCED_TABLE_NAME IS NOT NULL\nORDER BY\n KCU.TABLE_NAME,\n COLS.ORDINAL_POSITION\n" }, { "answer_id": 71882817, "author": "John Muraguri", "author_id": 2742117, "author_profile": "https://Stackoverflow.com/users/2742117", "pm_score": 2, "selected": false, "text": "SELECT cu.table_name,\n cu.column_name,\n cu.constraint_name,\n cu.referenced_table_name,\n cu.referenced_column_name,\n IF(rc.update_rule = 'NO ACTION', 'RESTRICT', rc.update_rule) AS update_rule,-- See: https://stackoverflow.com/a/1498015/2742117\n IF(rc.delete_rule = 'NO ACTION', 'RESTRICT', rc.delete_rule) AS delete_rule -- See: https://stackoverflow.com/a/1498015/2742117\nFROM information_schema.key_column_usage cu\nINNER JOIN information_schema.referential_constraints rc ON rc.constraint_schema = cu.table_schema\nAND rc.table_name = cu.table_name\nAND rc.constraint_name = cu.constraint_name\nWHERE cu.referenced_table_schema = '<your schema>'\n AND cu.referenced_table_name = '<your table>';\n" }, { "answer_id": 72682357, "author": "M Shafaei N", "author_id": 11583351, "author_profile": "https://Stackoverflow.com/users/11583351", "pm_score": 1, "selected": false, "text": "select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_SCHEMA = 'myprodb' AND CONSTRAINT_TYPE = 'FOREIGN KEY';\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3757/" ]
201,636
<p>We are using Linq To SQL with our own data context logic that executes the one linq query across multiple databases. When we get the results back, we need the database for each of the rows. So...</p> <p>I want to have a property on my class that will return the database name (SQL Server, so DB_NAME()). How can I do this in Linq To Sql?</p> <p><strong>NOTE: We have hundreds of databases and do not want to put views in each db. The return should come back as just another property on each row of the return result set.</strong></p>
[ { "answer_id": 231477, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 0, "selected": false, "text": "Dim results = _\n From x In myContext.MyTables _\n Select x, info = myContext.Connection.ConnectionString\n" }, { "answer_id": 231817, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": true, "text": " <Column Name=\"Table1.DBName\" \n DbType=\"nvarahcar(128)\" \n Type=\"System.String\" \n Expression=\"DB_NAME()\" />\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
201,660
<p>I have some code which returns InnerXML for a XMLNode.</p> <p>The node can contain just some text (with HTML) or XML.</p> <p>For example:</p> <pre><code>&lt;XMLNode&gt; Here is some &amp;lt;strong&amp;gt;HTML&amp;lt;/strong&amp;gt; &lt;XMLNode&gt; </code></pre> <p>or</p> <pre><code>&lt;XMLNode&gt; &lt;XMLContent&gt;Here is some content&lt;/XMLContnet&gt; &lt;/XMLNode&gt; </code></pre> <p>if I get the InnerXML for <code>&lt;XmlNode&gt;</code> the HTML tags are returned as XML entities.</p> <p>I cannot use InnerText because I need to be able to get the XML contents. So all I really need is a way to un-escape the HTML tags, because I can detect if it's XML or not and act accordingly.</p> <p>I guess I could use HTMLDecode, but will this decode all the XML encoded entities?</p> <p><strong>Update:</strong> I guess I'm rambling a bit above so here is a clarified scenario:</p> <p>I have a XML document that looks like this:</p> <pre><code>&lt;content id="1"&gt; &lt;data&gt;&amp;lt;p&amp;gt;A Test&amp;lt;/p&amp;gt;&lt;/data&gt; &lt;/content id="2"&gt; &lt;content&gt; &lt;data&gt; &lt;dataitem&gt;A test&lt;/dataitem&gt; &lt;/data&gt; &lt;/content&gt; </code></pre> <p>If I do:</p> <pre><code>XmlNode xn1 = document.SelectSingleNode("/content[@id=1]/data"); XmlNode xn2 = document.SelectSingleNode("/content[@id=2]/data"); Console.WriteLine(xn1.InnerXml); Console.WriteLine(xn2.InnerXml); </code></pre> <p>xn1 will return </p> <pre><code> &amp;lt;p&amp;gt;A Test&amp;lt;/p&amp;gt; </code></pre> <p>xn2 will return <code>&lt;dataitem&gt;A test&lt;/dataitem&gt;</code></p> <p>I am already checking to see if what is returned is XML (in the case of xn2) so all I need to do is un-escape the <code>&amp;lt;</code> etc in xn1.</p> <p>HTMLDecode does this, but I'm not sure it would work for everything. So the question remains would HTMLDecode handle all the possible entities or is there a class somewhere that will do it for me.</p>
[ { "answer_id": 201790, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "\"<p>A Test</p>\" xn1 \"A test\" xn2 InnerXml xn1 InnerText xn2 dataitem XmlNode xn = document.SelectSingleNode(\"/content[@id=1]/data\");\n\nif (xn.SelectSingleNode(\"dataitem\") == null)\n Console.WriteLine(xn.InnerXml);\nelse\n Console.WriteLine(xn.InnerText);\n HttpUtility.HtmlDecode InnerXml" }, { "answer_id": 205962, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": true, "text": " XmlNode xn = document.SelectSingleNode(\"/content[@id=1]/data\");\n if (xn.ChildNodes.Count != 1)\n {\n throw new InvalidOperationException(\"I don't know what to do if there's not exactly one child node.\");\n }\n XmlNode child = xn.ChildNodes[0];\n switch (child.NodeType)\n {\n case XmlNodeType.Element:\n Console.WriteLine(xn.InnerXml);\n break;\n case XmlNodeType.Text:\n Console.WriteLine(xn.Value);\n break;\n default:\n throw new InvalidOperationException(\"I can only handle elements and text nodes.\");\n }\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1970/" ]
201,671
<p>When I refer to nested set model I mean what is described <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="nofollow noreferrer">here.</a></p> <p>I need to build a new system for storing "categories" (I can't think of better word for it) in a user defined hierarchy. Since the nested set model is optimized for reads instead of writes, I decided to use that. Unfortunately during my research and testing of nested sets, I ran into the problem of how do I display the hierarchical tree with sorted nodes. For example if I have the hierarchy:</p> <pre><code>root finances budgeting fy08 projects research fabrication release trash </code></pre> <p>I want that to be sorted so that it displays as:</p> <pre><code>root finances budgeting fy08 projects fabrication release research trash </code></pre> <p>Notice that the fabrication appears before research.</p> <p>Anyway, after a long search I saw answer such as "store the tree in a multi-dimensional array and sort it" and "resort the tree and serialized back into your nested set model" (I'm paraphrazing...). Either way, the first solution is a horrible waste of RAM and CPU, which are both very finite resources... The second solution just looks like a lot of painful code.</p> <p>Regardless, I was able to figure out how to (using the nested set model):</p> <ol> <li>Start a new tree in SQL</li> <li>Insert a node as a child of another node in tree</li> <li>Insert a node after a sibling node in the tree</li> <li>Pull the entire tree with the hierarchy structure from SQL</li> <li>Pull a subtree from a specific node (including root) in the hierarchy with or without a depth limit</li> <li>Find the parent of any node in the tree</li> </ol> <p>So I figured #5 and #6 could be used to do the sorting I wanted, and it could also be used to rebuild the tree in sorted order as well.</p> <p>However, now that I've looked at all of these things I've learned to do I see that #3, #5, and #6 could be used together to perform sorted inserts. If I did sorted inserts it always be sorted. However, if I ever change the sort criteria or I want a different sort order I'm back to square one.</p> <p>Could this just be the limitation of the nested set model? Does its use inhibit in query sorting of the output?</p>
[ { "answer_id": 202735, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 3, "selected": false, "text": "ORDER BY node.rgt DESC ORDER BY node.lft ASC lft rgt" }, { "answer_id": 457424, "author": "Justin Wignall", "author_id": 42774, "author_profile": "https://Stackoverflow.com/users/42774", "pm_score": 2, "selected": false, "text": "CREATE VIEW dbo.tree_view\n\nAS\n\nSELECT t2.NodeID,t2.lft,t2.rgt ,t2.Name, COUNT(t1.NodeID) AS level \nFROM dbo.tree t1,dbo.tree t2\nWHERE t2.lft BETWEEN t1.lft AND t1.rgt\nGROUP BY t2.NodeID,t2.lft,t2.rgt,t2.Name\n\nGO\n\n----------------------------------------------\n\n DECLARE @CurrentNodeID int\nDECLARE @CurrentActualOrder int\nDECLARE @CurrentRequiredOrder int\nDECLARE @DestinationNodeID int\nDECLARE @i0 int\nDECLARE @i1 int\nDECLARE @i2 int\nDECLARE @i3 int\n\nDECLARE @t TABLE (TopLft int,NodeID int NOT NULL,lft int NOT NULL,rgt int NOT NULL,Name varchar(50),RequiredOrder int NOT NULL,ActualOrder int NOT NULL)\n\n\nINSERT INTO @t (toplft,NodeID,lft,rgt,Name,RequiredOrder,ActualOrder)\n SELECT tv2.lft,tv1.NodeID,tv1.lft,tv1.rgt,tv1.Name,ROW_NUMBER() OVER(PARTITION BY tv2.lft ORDER BY tv1.ColumnToSort),ROW_NUMBER() OVER(PARTITION BY tv2.lft ORDER BY tv1.lft ASC)\n FROM dbo.tree_view tv1 \n LEFT OUTER JOIN dbo.tree_view tv2 ON tv1.lft > tv2.lft and tv1.lft < tv2.rgt and tv1.level = tv2.level+1\n WHERE tv2.rgt > tv2.lft+1\n\n DELETE FROM @t where ActualOrder = RequiredOrder\n\n\nWHILE EXISTS(SELECT * FROM @t WHERE ActualOrder <> RequiredOrder)\nBEGIN\n\n\n SELECT Top 1 @CurrentNodeID = NodeID,@CurrentActualOrder = ActualOrder,@CurrentRequiredOrder = RequiredOrder\n FROM @t \n WHERE ActualOrder <> RequiredOrder\n ORDER BY toplft,requiredorder\n\n SELECT @DestinationNodeID = NodeID\n FROM @t WHERE ActualOrder = @CurrentRequiredOrder AND TopLft = (SELECT TopLft FROM @t WHERE NodeID = @CurrentNodeID) \n\n SELECT @i0 = CASE WHEN c.lft < d.lft THEN c.lft ELSE d.lft END,\n @i1 = CASE WHEN c.lft < d.lft THEN c.rgt ELSE d.rgt END,\n @i2 = CASE WHEN c.lft < d.lft THEN d.lft ELSE c.lft END,\n @i3 = CASE WHEN c.lft < d.lft THEN d.rgt ELSE c.rgt END\n FROM dbo.tree c\n CROSS JOIN dbo.tree d\n WHERE c.NodeID = @CurrentNodeID AND d.NodeID = @DestinationNodeID\n\n UPDATE dbo.tree\n SET lft = CASE WHEN lft BETWEEN @i0 AND @i1 THEN @i3 + lft - @i1\n WHEN lft BETWEEN @i2 AND @i3 THEN @i0 + lft - @i2\n ELSE @i0 + @i3 + lft - @i1 - @i2\n END,\n rgt = CASE WHEN rgt BETWEEN @i0 AND @i1 THEN @i3 + rgt - @i1\n WHEN rgt BETWEEN @i2 AND @i3 THEN @i0 + rgt - @i2\n ELSE @i0 + @i3 + rgt - @i1 - @i2\n END\n WHERE lft BETWEEN @i0 AND @i3 \n AND @i0 < @i1\n AND @i1 < @i2\n AND @i2 < @i3\n\n UPDATE @t SET actualorder = @CurrentRequiredOrder where NodeID = @CurrentNodeID\n UPDATE @t SET actualorder = @CurrentActualOrder where NodeID = @DestinationNodeID\n\n DELETE FROM @t where ActualOrder = RequiredOrder\n\nEND\n" }, { "answer_id": 2199228, "author": "FrontierPsycho", "author_id": 190833, "author_profile": "https://Stackoverflow.com/users/190833", "pm_score": 0, "selected": false, "text": " A\n / \\\nB C\n / \\\n D E\n 1 A 10 \n2 B 3 \n4 C 9\n5 D 6\n7 E 8\n 1 A 10\n2 B 3 \n4 C 9 \n7 D 8\n5 E 6 \n" }, { "answer_id": 20448404, "author": "pj.cz", "author_id": 3078846, "author_profile": "https://Stackoverflow.com/users/3078846", "pm_score": 0, "selected": false, "text": "$tree = Array();\n$parents = Array();\n$nodes = $this->table->order('depth ASC, parent_id ASC, name ASC');\n$i = 0;\n$depth = 0;\n$parent_id = 0;\n\nforeach($nodes as $node) {\n if($depth < $node->depth || $parent_id < $node->parent_id) {\n $i = $parents[\"{$node->parent_id}\"] + 1;\n }\n $tree[$i] = $node;\n $parents[\"{$node->id}\"] = $i;\n $depth = $node->depth;\n $parent_id = $node->parent_id;\n $i += (($node->rgt - $node->lft - 1) / 2) + 1;\n}\nksort($tree);\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
201,680
<p>Does Geronimo provides a standalone transaction manager? And if it does, is it possible to use it in Tomcat?</p>
[ { "answer_id": 1991439, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 2, "selected": false, "text": "DataSource" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27762/" ]
201,696
<p>In ASP.NET, I'm looking for a way to audit a user leaving my application. To be specific, I'd like to insert a 'logout' record in an audit table in SQL Server when the user's session is abandoned/destroyed for any reason (not necessarily because of a call to session.abandon)</p> <p>I have a 'SessionHelper' class that manages the session setters/getters.</p> <p>I've tried posting back in Session_End in Global.asax, but it never fired this event even after the timeout expired.</p> <p>I've tried overriding 'finalize' in the SessionHelper class and doing it there when the class is destroyed, but it did not fire that event either.</p> <p>I'd try implementing IDisposable in the SessionHelper, but I don't know where to call it so that it always gets called.</p> <p>What is the proper way to audit a user leaving your ASP.NET application?</p> <p>Thank you!</p>
[ { "answer_id": 201755, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 1, "selected": false, "text": "[Id] [Uid] [LoginInOn] [ExpiresOn] \n 1 johndoe 10/14/2008 10:47 10/14/2008 11:07 \n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6624/" ]
201,699
<p>I have a Java applet that runs inside a forms-authenticated aspx page. In the .NET 1.1 version of my site, the applet has access to the session cookie and is able to retrieve a file from the server, but in the .NET 2.0 version it fails to authenticate.</p> <p>I have seen a couple of forum posts elsewhere that state that 2.0 sets cookies to HttpOnly by default, but the solutions given haven't worked for me so far. I also read somewhere that 2.0 may be discriminating based on user-agent.</p> <p>Does anyone have any experience or insight into this?</p>
[ { "answer_id": 656465, "author": "Aidan Black", "author_id": 8211, "author_profile": "https://Stackoverflow.com/users/8211", "pm_score": 0, "selected": false, "text": "<httpCookies httpOnlyCookies=\"false\" />" }, { "answer_id": 7314616, "author": "Trevor Lohrbeer", "author_id": 929862, "author_profile": "https://Stackoverflow.com/users/929862", "pm_score": 4, "selected": true, "text": "protected void Application_EndRequest(object sender, EventArgs e)\n{\n /**\n * @note Remove the HttpOnly attribute from session cookies, otherwise the \n * Java applet won't have access to the session. This solution taken\n * from\n * http://blogs.msdn.com/jorman/archive/2006/03/05/session-loss-after-migrating-to-asp-net-2-0.aspx\n *\n * For more information on the HttpOnly attribute see:\n *\n * http://msdn.microsoft.com/netframework/programming/breakingchanges/runtime/aspnet.aspx\n * http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx\n */\n if (Response.Cookies.Count > 0)\n {\n foreach (string lName in Response.Cookies.AllKeys)\n {\n if (lName == FormsAuthentication.FormsCookieName || \n lName.ToLower() == \"asp.net_sessionid\")\n {\n Response.Cookies[lName].HttpOnly = false;\n }\n }\n }\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8211/" ]
201,700
<p>I'm currently logging via the simplest of methods within my servlet using Tomcat. I use the ServletConfig.getServletContext().log to record activity. This writes to the localhost.YYYY-MM-DD.log in $TOMCAT_HOME/logs.</p> <p>I don't want to get away from the simplicity of this logging mechanism unless absolutely necessary. But I would like to name my log file. Rather than "localhost".YYYY-MM-DD.log, is there a way to have it write to "myAppName".YYYY-MM-DD.log. I know I could create my own mechanism, but again, I looking for simplicity here.</p> <p>I'm hoping to stay away from a complete framework like Log4j.</p>
[ { "answer_id": 656465, "author": "Aidan Black", "author_id": 8211, "author_profile": "https://Stackoverflow.com/users/8211", "pm_score": 0, "selected": false, "text": "<httpCookies httpOnlyCookies=\"false\" />" }, { "answer_id": 7314616, "author": "Trevor Lohrbeer", "author_id": 929862, "author_profile": "https://Stackoverflow.com/users/929862", "pm_score": 4, "selected": true, "text": "protected void Application_EndRequest(object sender, EventArgs e)\n{\n /**\n * @note Remove the HttpOnly attribute from session cookies, otherwise the \n * Java applet won't have access to the session. This solution taken\n * from\n * http://blogs.msdn.com/jorman/archive/2006/03/05/session-loss-after-migrating-to-asp-net-2-0.aspx\n *\n * For more information on the HttpOnly attribute see:\n *\n * http://msdn.microsoft.com/netframework/programming/breakingchanges/runtime/aspnet.aspx\n * http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx\n */\n if (Response.Cookies.Count > 0)\n {\n foreach (string lName in Response.Cookies.AllKeys)\n {\n if (lName == FormsAuthentication.FormsCookieName || \n lName.ToLower() == \"asp.net_sessionid\")\n {\n Response.Cookies[lName].HttpOnly = false;\n }\n }\n }\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
201,705
<p>I've got an image library on Amazon S3. For each image, I md5 the source URL on my server plus a timestamp to get a unique filename. Since S3 can't have subdirectories, I need to store all of these images in a single flat folder.</p> <p>Do I need to worry about collisions in the MD5 hash value that gets produced?</p> <p>Bonus: How many files could I have before I'd start seeing collisions in the hash value that MD5 produces?</p>
[ { "answer_id": 201725, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 4, "selected": false, "text": "md5(filename) + timestamp\n md5(filename + timestamp)\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27899/" ]
201,706
<p>I have an SQL Server DB with a table with these fields:</p> <ol> <li>A <code>bit</code> with the default value 1, <code>NOT NULL</code>.</li> <li>A <code>smalldatetime</code> with the default value <code>gettime()</code>, <code>NOT NULL</code>.</li> <li>An <code>int</code> with no default value, <code>IDENTITY</code>, <code>NOT NULL</code>.</li> </ol> <p>When I generate Linq to SQL for this table, the following happens:</p> <ol> <li>The <code>bit</code> is given no special treatment.</li> <li>The <code>smalldatetime</code> is given no special treatment.</li> <li>The <code>int</code> is marked as <code>IsDbGenerated</code>.</li> </ol> <p>This means that when I make inserts using Linq to SQL, the following will happen:</p> <ol> <li>The <code>bit</code> will be sent as 0, overriding the default value. <strong>Right?</strong></li> <li>The <code>smalldatetime</code> will be sent as an uninitialized <code>System.DateTime</code>, producing an error in SQL server since it doesn't fall with the SQL Server smalldatetime range. <strong>Right?</strong></li> <li>The <code>IsDbGenerated</code> <code>int</code> will not be sent; the DB will generate a value which Linq to SQL will then read back.</li> </ol> <p><strong>What changes do I have to make to make this scenario work?</strong> </p> <p>To summarize: I want non-nullable fields with DB-assigned default values, but I don't want them <code>IsDbGenerated</code> if it means I cannot provide values for them when making updates or inserts using Linq to SQL. I also do not want them <code>IsDbGenerated</code> if it means I have to hand-modify the code generated by Linq to SQL.</p> <p><em>EDIT: The answer seems to be this is a limitation in the current Linq to SQL.</em></p>
[ { "answer_id": 206710, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 4, "selected": true, "text": "GetDate()" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724/" ]
201,718
<p>How do I concatenate two <code>std::vector</code>s?</p>
[ { "answer_id": 201727, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 8, "selected": false, "text": "vector<int> a, b;\n//fill with data\nb.insert(b.end(), a.begin(), a.end());\n" }, { "answer_id": 201729, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 10, "selected": false, "text": "vector1.insert( vector1.end(), vector2.begin(), vector2.end() );\n" }, { "answer_id": 201731, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": "std::vector<int> first;\nstd::vector<int> second;\n\nfirst.insert(first.end(), second.begin(), second.end());\n" }, { "answer_id": 201859, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 7, "selected": false, "text": "std::copy(source.begin(), source.end(), std::back_inserter(destination));\n std::back_inserter" }, { "answer_id": 21972296, "author": "Alex", "author_id": 2918069, "author_profile": "https://Stackoverflow.com/users/2918069", "pm_score": 8, "selected": false, "text": "std::move_iterator #include <vector>\n#include <iostream>\n#include <iterator>\n\nint main(int argc, char** argv) {\n std::vector<int> dest{1,2,3,4,5};\n std::vector<int> src{6,7,8,9,10};\n\n // Move elements from src to dest.\n // src is left in undefined but safe-to-destruct state.\n dest.insert(\n dest.end(),\n std::make_move_iterator(src.begin()),\n std::make_move_iterator(src.end())\n );\n\n // Print out concatenated vector.\n std::copy(\n dest.begin(),\n dest.end(),\n std::ostream_iterator<int>(std::cout, \"\\n\")\n );\n\n return 0;\n}\n #include <vector>\n#include <iostream>\n#include <iterator>\n\nint main(int argc, char** argv) {\n std::vector<std::vector<int>> dest{{1,2,3,4,5}, {3,4}};\n std::vector<std::vector<int>> src{{6,7,8,9,10}};\n\n // Move elements from src to dest.\n // src is left in undefined but safe-to-destruct state.\n dest.insert(\n dest.end(),\n std::make_move_iterator(src.begin()),\n std::make_move_iterator(src.end())\n );\n\n return 0;\n}\n" }, { "answer_id": 23489497, "author": "AlexT", "author_id": 834552, "author_profile": "https://Stackoverflow.com/users/834552", "pm_score": 3, "selected": false, "text": "template<typename T>\ninline void append_copy(std::vector<T>& v1, const std::vector<T>& v2)\n{\n const auto orig_v1_size = v1.size();\n v1.reserve(orig_v1_size + v2.size());\n try\n {\n v1.insert(v1.end(), v2.begin(), v2.end());\n }\n catch(...)\n {\n v1.erase(v1.begin() + orig_v1_size, v1.end());\n throw;\n }\n}\n append_move" }, { "answer_id": 30798014, "author": "Deqing", "author_id": 558892, "author_profile": "https://Stackoverflow.com/users/558892", "pm_score": 6, "selected": false, "text": "std::move(b.begin(), b.end(), std::back_inserter(a));\n a b b std::move <algorithm> std::move <utility>" }, { "answer_id": 33649647, "author": "Stepan Yakovenko", "author_id": 517073, "author_profile": "https://Stackoverflow.com/users/517073", "pm_score": 3, "selected": false, "text": "template <typename T> vector<T> concat(vector<T> &a, vector<T> &b) {\n vector<T> ret = vector<T>();\n copy(a.begin(), a.end(), back_inserter(ret));\n copy(b.begin(), b.end(), back_inserter(ret));\n return ret;\n}\n vector<int> a = vector<int>();\nvector<int> b = vector<int>();\n\na.push_back(1);\na.push_back(2);\nb.push_back(62);\n\nvector<int> r = concat(a, b);\n" }, { "answer_id": 35561577, "author": "Jonathan Mee", "author_id": 2642059, "author_profile": "https://Stackoverflow.com/users/2642059", "pm_score": 0, "selected": false, "text": "vector::insert vector<int> first = {13};\nconst vector<int> second = {42};\n\nfirst.insert(first.end(), second.cbegin(), second.cend());\n const vector<int> insert vector<int> vector const basic_string char_type vector static_assert static_assert(sizeof(char32_t) == sizeof(int));\n const u32string concatenation = u32string(first.cbegin(), first.cend()) + u32string(second.cbegin(), second.cend());\n string vector" }, { "answer_id": 37744652, "author": "ST3", "author_id": 1237747, "author_profile": "https://Stackoverflow.com/users/1237747", "pm_score": 5, "selected": false, "text": "a.insert(a.end(), b.begin(), b.end());\n a.insert(std::end(a), std::begin(b), std::end(b));\n reserve reserve template <typename T>\nvoid Append(std::vector<T>& a, const std::vector<T>& b)\n{\n a.reserve(a.size() + b.size());\n a.insert(a.end(), b.begin(), b.end());\n}\n" }, { "answer_id": 41183892, "author": "instance", "author_id": 3312772, "author_profile": "https://Stackoverflow.com/users/3312772", "pm_score": 2, "selected": false, "text": "vector<int> v1 = {1, 2, 3, 4, 5};\nvector<int> v2 = {11, 12, 13, 14, 15};\ncopy(v2.begin(), v2.end(), back_inserter(v1));\n" }, { "answer_id": 41340227, "author": "nvnhcmus", "author_id": 5697579, "author_profile": "https://Stackoverflow.com/users/5697579", "pm_score": -1, "selected": false, "text": "vector<int> concat_vector = vector<int>();\nconcat_vector.setcapacity(vector_A.size() + vector_B.size());\n// Loop for copy elements in two vectors into concat_vector\n // Loop for insert elements of vector_B into vector_A with insert() \nfunction: vector_A.insert(vector_A .end(), vector_B.cbegin(), vector_B.cend());\n" }, { "answer_id": 45563644, "author": "Jarod42", "author_id": 2684539, "author_profile": "https://Stackoverflow.com/users/2684539", "pm_score": 5, "selected": false, "text": "ranges::view::concat(v1, v2)\n" }, { "answer_id": 45564780, "author": "Boris", "author_id": 7739417, "author_profile": "https://Stackoverflow.com/users/7739417", "pm_score": 3, "selected": false, "text": "v1.insert(v1.end(), v2.begin(), v2.end());\n" }, { "answer_id": 49174699, "author": "Daniel", "author_id": 2970186, "author_profile": "https://Stackoverflow.com/users/2970186", "pm_score": 2, "selected": false, "text": "template <typename T>\nstd::vector<T> concat(const std::vector<T>& lhs, const std::vector<T>& rhs)\n{\n if (lhs.empty()) return rhs;\n if (rhs.empty()) return lhs;\n std::vector<T> result {};\n result.reserve(lhs.size() + rhs.size());\n result.insert(result.cend(), lhs.cbegin(), lhs.cend());\n result.insert(result.cend(), rhs.cbegin(), rhs.cend());\n return result;\n}\n\ntemplate <typename T>\nstd::vector<T> concat(std::vector<T>&& lhs, const std::vector<T>& rhs)\n{\n lhs.insert(lhs.cend(), rhs.cbegin(), rhs.cend());\n return std::move(lhs);\n}\n\ntemplate <typename T>\nstd::vector<T> concat(const std::vector<T>& lhs, std::vector<T>&& rhs)\n{\n rhs.insert(rhs.cbegin(), lhs.cbegin(), lhs.cend());\n return std::move(rhs);\n}\n\ntemplate <typename T>\nstd::vector<T> concat(std::vector<T>&& lhs, std::vector<T>&& rhs)\n{\n if (lhs.empty()) return std::move(rhs);\n lhs.insert(lhs.cend(), std::make_move_iterator(rhs.begin()), std::make_move_iterator(rhs.end()));\n return std::move(lhs);\n}\n append vector" }, { "answer_id": 50231136, "author": "Vikramjit Roy", "author_id": 5402524, "author_profile": "https://Stackoverflow.com/users/5402524", "pm_score": 4, "selected": false, "text": "//vector<int> v1,v2;\nif(v1.size()>v2.size()) {\n v1.insert(v1.end(),v2.begin(),v2.end());\n} else {\n v2.insert(v2.end(),v1.begin(),v1.end());\n}\n" }, { "answer_id": 51613711, "author": "Vladimir U.", "author_id": 7759292, "author_profile": "https://Stackoverflow.com/users/7759292", "pm_score": 2, "selected": false, "text": "template <typename T> \ninline T operator+(const T & a, const T & b)\n{\n T res = a;\n res.insert(res.end(), b.begin(), b.end());\n return res;\n}\n vector<int> a{1, 2, 3, 4};\nvector<int> b{5, 6, 7, 8};\nfor (auto x: a + b)\n cout << x << \" \";\ncout << endl;\n" }, { "answer_id": 53652797, "author": "Aleph0", "author_id": 5762796, "author_profile": "https://Stackoverflow.com/users/5762796", "pm_score": 1, "selected": false, "text": "boost-range #include <iostream>\n#include <vector>\n#include <boost/range/algorithm/copy.hpp>\n\nint main(int, char**) {\n std::vector<int> a = { 1,2,3 };\n std::vector<int> b = { 4,5,6 };\n boost::copy(b, std::back_inserter(a));\n for (auto& iter : a) {\n std::cout << iter << \" \";\n }\n return EXIT_SUCCESS;\n}\n a b join #include <iostream>\n#include <vector>\n#include <boost/range/join.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\nint main(int, char**) {\n std::vector<int> a = { 1,2,3 };\n std::vector<int> b = { 4,5,6 };\n std::vector<int> c = { 7,8,9 };\n // Just creates an iterator\n for (auto& iter : boost::join(a, boost::join(b, c))) {\n std::cout << iter << \" \";\n }\n std::cout << \"\\n\";\n // Can also be used to create a copy\n std::vector<int> d;\n boost::copy(boost::join(a, boost::join(b, c)), std::back_inserter(d));\n for (auto& iter : d) {\n std::cout << iter << \" \";\n }\n return EXIT_SUCCESS;\n}\n boost::join(a,b,c)" }, { "answer_id": 56781594, "author": "Daniel Giger", "author_id": 6338179, "author_profile": "https://Stackoverflow.com/users/6338179", "pm_score": 4, "selected": false, "text": "+= template <typename T>\nstd::vector<T>& operator +=(std::vector<T>& vector1, const std::vector<T>& vector2) {\n vector1.insert(vector1.end(), vector2.begin(), vector2.end());\n return vector1;\n}\n vector1 += vector2;\n" }, { "answer_id": 56997340, "author": "Drew", "author_id": 595605, "author_profile": "https://Stackoverflow.com/users/595605", "pm_score": 2, "selected": false, "text": "namespace internal {\n\n// Implementation detail of Concatenate, appends to a pre-reserved vector, copying or moving if\n// appropriate\ntemplate<typename Target, typename Head, typename... Tail>\nvoid AppendNoReserve(Target* target, Head&& head, Tail&&... tail) {\n // Currently, require each homogenous inputs. If there is demand, we could probably implement a\n // version that outputs a vector whose value_type is the common_type of all the containers\n // passed to it, and call it ConvertingConcatenate.\n static_assert(\n std::is_same_v<\n typename std::decay_t<Target>::value_type,\n typename std::decay_t<Head>::value_type>,\n \"Concatenate requires each container passed to it to have the same value_type\");\n if constexpr (std::is_lvalue_reference_v<Head>) {\n std::copy(head.begin(), head.end(), std::back_inserter(*target));\n } else {\n std::move(head.begin(), head.end(), std::back_inserter(*target));\n }\n if constexpr (sizeof...(Tail) > 0) {\n AppendNoReserve(target, std::forward<Tail>(tail)...);\n }\n}\n\ntemplate<typename Head, typename... Tail>\nsize_t TotalSize(const Head& head, const Tail&... tail) {\n if constexpr (sizeof...(Tail) > 0) {\n return head.size() + TotalSize(tail...);\n } else {\n return head.size();\n }\n}\n\n} // namespace internal\n\n/// Concatenate the provided containers into a single vector. Moves from rvalue references, copies\n/// otherwise.\ntemplate<typename Head, typename... Tail>\nauto Concatenate(Head&& head, Tail&&... tail) {\n size_t totalSize = internal::TotalSize(head, tail...);\n std::vector<typename std::decay_t<Head>::value_type> result;\n result.reserve(totalSize);\n internal::AppendNoReserve(&result, std::forward<Head>(head), std::forward<Tail>(tail)...);\n return result;\n}\n" }, { "answer_id": 57533671, "author": "Pavan Chandaka", "author_id": 6866309, "author_profile": "https://Stackoverflow.com/users/6866309", "pm_score": 4, "selected": false, "text": "std::merge #include <iostream>\n#include <vector>\n#include <algorithm>\n\nint main()\n{\n //DATA\n std::vector<int> v1{2,4,6,8};\n std::vector<int> v2{12,14,16,18};\n\n //MERGE\n std::vector<int> dst;\n std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dst));\n\n //PRINT\n for(auto item:dst)\n std::cout<<item<<\" \";\n\n return 0;\n}\n" }, { "answer_id": 58492880, "author": "Ronald Souza", "author_id": 2379625, "author_profile": "https://Stackoverflow.com/users/2379625", "pm_score": 3, "selected": false, "text": "std::vector<int> A{ 1, 2, 3, 4, 5};\nstd::vector<int> B{ 10, 20, 30 };\n\nVecProxy<int> AB(A, B); // ----> O(1)!\n\nfor (size_t i = 0; i < AB.size(); i++)\n std::cout << AB[i] << \" \"; // ----> 1 2 3 4 5 10 20 30\n" }, { "answer_id": 61988198, "author": "rekkalmd", "author_id": 9694134, "author_profile": "https://Stackoverflow.com/users/9694134", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\ntemplate<typename T>\n\nvoid concat(std::vector<T>& valuesa, std::vector<T>& valuesb){\n\n for_each(valuesb.begin(), valuesb.end(), [&](int value){ valuesa.push_back(value);});\n}\n\nint main()\n{\n std::vector<int> values_p={1,2,3,4,5};\n std::vector<int> values_s={6,7};\n\n concat(values_p, values_s);\n\n for(auto& it : values_p){\n\n std::cout<<it<<std::endl;\n }\n\n return 0;\n}\n clear()" }, { "answer_id": 62255226, "author": "GobeRadJem32", "author_id": 10903517, "author_profile": "https://Stackoverflow.com/users/10903517", "pm_score": -1, "selected": false, "text": "std::vector-s for std::vector std::vector <int> v1 {1, 2, 3}; //declare vector1\n std::vector <int> v2 {4, 5}; //declare vector2\n std::vector <int> suma; //declare vector suma\n\n for(int i = 0; i < v1.size(); i++) //for loop 1\n {\n suma.push_back(v1[i]);\n }\n\n for(int i = 0; i< v2.size(); i++) //for loop 2\n {\n suma.push_back(v2[i]);\n }\n\n for(int i = 0; i < suma.size(); i++) //for loop 3-output\n {\n std::cout << suma[i];\n }\n" }, { "answer_id": 62582258, "author": "GobeRadJem32", "author_id": 10903517, "author_profile": "https://Stackoverflow.com/users/10903517", "pm_score": -1, "selected": false, "text": "std::vector<int> v1{1,2,3};\nstd::vector<int> v2{4,5};\n\nfor(int i = 0; i<v2.size();i++)\n{\n v1.push_back(v2[i]);\n}\n" }, { "answer_id": 68109876, "author": "Aroonalok", "author_id": 3258380, "author_profile": "https://Stackoverflow.com/users/3258380", "pm_score": 1, "selected": false, "text": "push_back std::copy(std::begin(input), std::end(input), std::back_inserter(output)) insert std::copy(std::begin(input), std::end(input), std::inserter(output, output.end()))" }, { "answer_id": 72288186, "author": "Olppah", "author_id": 2021579, "author_profile": "https://Stackoverflow.com/users/2021579", "pm_score": 2, "selected": false, "text": "#include <ranges>\n\nstd::ranges::copy(vec2, std::back_inserter(vec1));\n std::ranges::move(vec2, std::back_inserter(vec1));\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
201,724
<p>I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)</p>
[ { "answer_id": 201733, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 11, "selected": true, "text": "var arr = [\"Zero\", \"One\", \"Two\"];\n\ndocument.write(arr.join(\", \"));" }, { "answer_id": 202247, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 7, "selected": false, "text": "toString() var arr = [ 42, 55 ];\nvar str1 = arr.toString(); // Gives you \"42,55\"\nvar str2 = String(arr); // Ditto\n" }, { "answer_id": 22184713, "author": "skibulk", "author_id": 1017480, "author_profile": "https://Stackoverflow.com/users/1017480", "pm_score": 4, "selected": false, "text": "// Example\nvar csv = new csvWriter();\ncsv.del = '\\t';\ncsv.enc = \"'\";\n\nvar nullVar;\nvar testStr = \"The comma (,) pipe (|) single quote (') double quote (\\\") and tab (\\t) are commonly used to tabulate data in plain-text formats.\";\nvar testArr = [\n false,\n 0,\n nullVar,\n // undefinedVar,\n '',\n {key:'value'},\n];\n\nconsole.log(csv.escapeCol(testStr));\nconsole.log(csv.arrayToRow(testArr));\nconsole.log(csv.arrayToCSV([testArr, testArr, testArr]));\n\n/**\n * Class for creating csv strings\n * Handles multiple data types\n * Objects are cast to Strings\n **/\n\nfunction csvWriter(del, enc) {\n this.del = del || ','; // CSV Delimiter\n this.enc = enc || '\"'; // CSV Enclosure\n\n // Convert Object to CSV column\n this.escapeCol = function (col) {\n if(isNaN(col)) {\n // is not boolean or numeric\n if (!col) {\n // is null or undefined\n col = '';\n } else {\n // is string or object\n col = String(col);\n if (col.length > 0) {\n // use regex to test for del, enc, \\r or \\n\n // if(new RegExp( '[' + this.del + this.enc + '\\r\\n]' ).test(col)) {\n\n // escape inline enclosure\n col = col.split( this.enc ).join( this.enc + this.enc );\n\n // wrap with enclosure\n col = this.enc + col + this.enc;\n }\n }\n }\n return col;\n };\n\n // Convert an Array of columns into an escaped CSV row\n this.arrayToRow = function (arr) {\n var arr2 = arr.slice(0);\n\n var i, ii = arr2.length;\n for(i = 0; i < ii; i++) {\n arr2[i] = this.escapeCol(arr2[i]);\n }\n return arr2.join(this.del);\n };\n\n // Convert a two-dimensional Array into an escaped multi-row CSV \n this.arrayToCSV = function (arr) {\n var arr2 = arr.slice(0);\n\n var i, ii = arr2.length;\n for(i = 0; i < ii; i++) {\n arr2[i] = this.arrayToRow(arr2[i]);\n }\n return arr2.join(\"\\r\\n\");\n };\n}\n" }, { "answer_id": 22313674, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 4, "selected": false, "text": "var arr = ['contains,comma', 3.14, 'contains\"quote', \"more'quotes\"]\nvar item, i;\nvar line = [];\n\nfor (i = 0; i < arr.length; ++i) {\n item = arr[i];\n if (item.indexOf && (item.indexOf(',') !== -1 || item.indexOf('\"') !== -1)) {\n item = '\"' + item.replace(/\"/g, '\"\"') + '\"';\n }\n line.push(item);\n}\n\ndocument.getElementById('out').innerHTML = line.join(',');\n" }, { "answer_id": 31013271, "author": "E Roberts", "author_id": 4945400, "author_profile": "https://Stackoverflow.com/users/4945400", "pm_score": 1, "selected": false, "text": "var arr = new Array(3);\narr[0] = \"Zero\";\narr[1] = \"One\";\narr[2] = \"Two\";\n arr.join(\",\")\n=> \"Zero,One,Two\"\n arr.join(\"|\")\n=> \"Zero|One|Two\"\n\nvar url = 'http://www.yoursitehere.com/do/something/to/' + arr.join(\"|\");\n=> \"http://www.yoursitehere.com/do/something/to/Zero|One|Two\"\n" }, { "answer_id": 34250056, "author": "Avijit Gupta", "author_id": 4135178, "author_profile": "https://Stackoverflow.com/users/4135178", "pm_score": 3, "selected": false, "text": "Array.toString var arr = ['one', 'two', 'three'];\narr.toString(); // 'one,two,three'\n" }, { "answer_id": 35597142, "author": "Dawson B", "author_id": 3855197, "author_profile": "https://Stackoverflow.com/users/3855197", "pm_score": 1, "selected": false, "text": "const arrford = require('arrford');\n\narrford(['run', 'climb', 'jump!']);\n//=> 'run, climb, and jump!'\n\narrford(['run', 'climb', 'jump!'], false);\n//=> 'run, climb and jump!'\n\narrford(['run', 'climb!']);\n//=> 'run and climb!'\n\narrford(['run!']);\n//=> 'run!'\n npm install --save arrford\n" }, { "answer_id": 40460413, "author": "Akash", "author_id": 4218672, "author_profile": "https://Stackoverflow.com/users/4218672", "pm_score": -1, "selected": false, "text": "var arr = [\"Pro1\", \"Pro2\", \"Pro3\"];\nconsole.log(arr.join());// Pro1,Pro2,Pro3\nconsole.log(arr.join(', '));// Pro1, Pro2, Pro3\n" }, { "answer_id": 43015176, "author": "Andrew Downes", "author_id": 1409410, "author_profile": "https://Stackoverflow.com/users/1409410", "pm_score": 4, "selected": false, "text": "function arrayToList(array){\n return array\n .join(\", \")\n .replace(/, ((?:.(?!, ))+)$/, ' and $1');\n}\n" }, { "answer_id": 44299490, "author": "alejandro", "author_id": 505002, "author_profile": "https://Stackoverflow.com/users/505002", "pm_score": -1, "selected": false, "text": "var array = [\"Zero\", \"One\", \"Two\"];\nvar s = array + [];\nconsole.log(s); // => Zero,One,Two\n" }, { "answer_id": 44844082, "author": "knowbody", "author_id": 1957849, "author_profile": "https://Stackoverflow.com/users/1957849", "pm_score": 2, "selected": false, "text": "null undefined // Example 1\nconst arr1 = ['apple', null, 'banana', '', undefined, 'pear'];\nconst commaSeparated1 = arr1.filter(item => item).join(', ');\nconsole.log(commaSeparated1); // 'apple, banana, pear'\n\n// Example 2\nconst arr2 = [null, 'apple'];\nconst commaSeparated2 = arr2.filter(item => item).join(', ');\nconsole.log(commaSeparated2); // 'apple'\n ', apple'" }, { "answer_id": 44988398, "author": "Bob", "author_id": 4779501, "author_profile": "https://Stackoverflow.com/users/4779501", "pm_score": 2, "selected": false, "text": "const csvParser = require('papaparse'); // previously you might have used babyparse\nvar arr = [1,null,\"a,b\"] ;\nvar csv = csvParser.unparse([arr]) ;\nconsole.log(csv) ;\n" }, { "answer_id": 45161169, "author": "Sagar V", "author_id": 2427065, "author_profile": "https://Stackoverflow.com/users/2427065", "pm_score": 3, "selected": false, "text": "var arr = [\"this\",\"is\",\"a\",\"comma\",\"separated\",\"list\"];\narr = arr.join(\",\");\n var arr = [\"this\", \"is\", \"a\", \"comma\", \"separated\", \"list\"];\narr = arr.join(\",\");\nconsole.log(arr); var arr = [\"this\",\"is\",\"a\",\"comma\",\"separated\",\"list\"];\narr = arr.toString();\n var arr = [\"this\", \"is\", \"a\", \"comma\", \"separated\", \"list\"];\narr = arr.toString();\nconsole.log(arr); ([]+[] === [].toString())\n console.log([]+[] === [].toString()); var arr = [\"this\",\"is\",\"a\",\"comma\",\"separated\",\"list\"];\narr = []+arr;\n var arr = [\"this\", \"is\", \"a\", \"comma\", \"separated\", \"list\"];\narr = []+arr;\nconsole.log(arr); var arr = [\"this\",\"is\",\"a\",\"comma\",\"separated\",\"list\"];\narr = arr+[];\n var arr = [\"this\", \"is\", \"a\", \"comma\", \"separated\", \"list\"];\narr = arr + [];\nconsole.log(arr);" }, { "answer_id": 52081537, "author": "Jaime Montoya", "author_id": 4242086, "author_profile": "https://Stackoverflow.com/users/4242086", "pm_score": 1, "selected": false, "text": "array = [\"test\",\"test2\",\"test3\"]\narray = array.toString();\narray = array.replace(/,/g, \", \");\nalert(array);\n array.join(', ');\n" }, { "answer_id": 54442843, "author": "Eliya Cohen", "author_id": 1860540, "author_profile": "https://Stackoverflow.com/users/1860540", "pm_score": 2, "selected": false, "text": "const vehicles = ['Motorcycle', 'Bus', 'Car'];\n\nconst formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });\nconsole.log(formatter.format(vehicles));\n// expected output: \"Motorcycle, Bus, and Car\"\n\nconst formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });\nconsole.log(formatter2.format(vehicles));\n// expected output: \"Motorcycle, Bus oder Car\"\n\nconst formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });\nconsole.log(formatter3.format(vehicles));\n// expected output: \"Motorcycle Bus Car\"" }, { "answer_id": 57397123, "author": "Yorkshireman", "author_id": 4111480, "author_profile": "https://Stackoverflow.com/users/4111480", "pm_score": -1, "selected": false, "text": "\" \" const result = ['', null, 'foo', ' ', undefined, 'bar'].filter(el => {\n return Boolean(el) && el.trim() !== '';\n}).join(', ');\n\nconsole.log(result); // => foo, bar\n" }, { "answer_id": 64129307, "author": "gildniy", "author_id": 1992866, "author_profile": "https://Stackoverflow.com/users/1992866", "pm_score": 2, "selected": false, "text": "const arr = [1, 2, 3];\nconsole.log(`${arr}`)\n" }, { "answer_id": 65460835, "author": "Jafar Karuthedath", "author_id": 2668564, "author_profile": "https://Stackoverflow.com/users/2668564", "pm_score": 5, "selected": false, "text": "let simpleArray = [1,2,3,4]\nlet commaSeperated = simpleArray.join(\",\");\nconsole.log(commaSeperated); let arrayOfObjects = [\n{\nid : 1,\nname : \"Name 1\",\naddress : \"Address 1\"\n},\n{\nid : 2,\nname : \"Name 2\",\naddress : \"Address 2\"\n},\n{\nid : 3,\nname : \"Name 3\",\naddress : \"Address 3\"\n}]\nlet names = arrayOfObjects.map(x => x.name).join(\", \");\nconsole.log(names); Name 1, Name 2, Name 3\n" }, { "answer_id": 69657454, "author": "Ali Akram", "author_id": 8652059, "author_profile": "https://Stackoverflow.com/users/8652059", "pm_score": 1, "selected": false, "text": "let taskIds: string = ''; \nthis.checkedTaskList.forEach(res => {\n taskIds = taskIds + res.taskId.toString() + ','\n});\nif (taskIds) {\n taskIds.substring(0, taskIds.length - 1),**\n}\n" }, { "answer_id": 72925744, "author": "roel", "author_id": 627794, "author_profile": "https://Stackoverflow.com/users/627794", "pm_score": 2, "selected": false, "text": "let arr = [\"Hello, there\", \"How's there\", 'the \"best\"']\nlet csv = arr.map(e => JSON.stringify(e)).join(\",\")\nconsole.log(csv)\n \"Hello, there\",\"How's there\",\"the \\\\\"best\\\\\"\"\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
201,734
<p>I have an HttpHandler on my webserver that takes a URL in the form of "<a href="https://servername/myhandler?op=get&amp;k=Internal&amp;m=jdahug1" rel="nofollow noreferrer">https://servername/myhandler?op=get&amp;k=Internal&amp;m=jdahug1</a>". I need to call this URL from my .NET app and capture whatever the output is. Does anyone know how I can do that? I want it to be simple so that I just get back a string with the output, and that I can specify my own timeout.</p> <ul> <li>Thanks!</li> </ul>
[ { "answer_id": 201759, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 2, "selected": true, "text": "using System.Net;\n\nusing System.IO;\n\nHttpWebRequest req = (HttpWebRequest) WebRequest.Create(WebPageUrl);\n\nWebResponse resp = req.GetResponse();\n\nStream stream = resp.GetResponseStream();\n\nStreamReader reader = new StreamReader(stream);\n\noutput.Write(reader.ReadToEnd());\n" }, { "answer_id": 201769, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "string handlerResponse = new System.Net.WebClient().DownloadString(\"https://servername/myhandler?op=get&k=Internal&m=jdahug1\");\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
201,776
<p>I have an ASP.NET web page with a Login control on it. When I hit Enter, the Login button doesn't fire; instead the page submits, doing nothing.</p> <p>The standard solution to this that I've found online is to enclose the Login control in a Panel, then set the Panel default button. But apparently that doesn't work so well if the page has a master page. I've tried setting the default button in code with <em>control</em>.ID, <em>control</em>.ClientID, and <em>control</em>.UniqueID, and in each case I get:</p> <blockquote> <p>The DefaultButton of panelName must be the ID of a control of type IButtonControl.</p> </blockquote> <p>I'm sure there's a way to do this with JavaScript, but I'd really like to do it with plain old C# code if possible. Is it possible?</p>
[ { "answer_id": 201822, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "txtPassword.Attributes.Add(\"onKeyPress\", \"javascript:if (event.keyCode == 13) __doPostBack('\" + lnkSubmit.UniqueID + \"','')\")\n" }, { "answer_id": 201879, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 2, "selected": false, "text": "<input type=\"button\"> <input type=\"submit\">" }, { "answer_id": 201889, "author": "Vassili Altynikov", "author_id": 22205, "author_profile": "https://Stackoverflow.com/users/22205", "pm_score": 6, "selected": true, "text": "DefaultButton=\"Login$LoginButton\"\n" }, { "answer_id": 434218, "author": "EMP", "author_id": 20336, "author_profile": "https://Stackoverflow.com/users/20336", "pm_score": 3, "selected": false, "text": "void SetDefaultButton(Panel panel, IButtonControl button)\n{\n string uniqueId = ((Control)button).UniqueID;\n string panelIdPrefix = panel.NamingContainer.UniqueID + Page.IdSeparator;\n\n if (uniqueId.StartsWith(panelIdPrefix))\n {\n uniqueId = uniqueId.Substring(panelIdPrefix.Length);\n }\n\n panel.DefaultButton = uniqueId;\n}\n" }, { "answer_id": 893478, "author": "Kb.", "author_id": 49544, "author_profile": "https://Stackoverflow.com/users/49544", "pm_score": 1, "selected": false, "text": "public class DefaultButtonPanel:Panel\n{\n protected override void OnLoad(EventArgs e)\n {\n if(!string.IsNullOrEmpty(DefaultButton))\n {\n LinkButton btn = FindControl(DefaultButton) as LinkButton;\n if(btn != null)\n {\n Button defaultButton = new Button {ID = DefaultButton.Replace(Page.IdSeparator.ToString(), \"_\") + \"_Default\", Text = \" \"};\n defaultButton.Style.Add(\"display\", \"none\");\n PostBackOptions p = new PostBackOptions(btn, \"\", null, false, true, true, true, true, btn.ValidationGroup);\n defaultButton.OnClientClick = Page.ClientScript.GetPostBackEventReference(p) + \"; return false;\";\n Controls.Add(defaultButton);\n DefaultButton = defaultButton.ID;\n }\n }\n base.OnLoad(e);\n }\n\n /// <summary>\n /// Set the default button in a Panel.\n /// The UniqueID of the button, must be relative to the Panel's naming container UniqueID. \n /// \n /// For example:\n /// Panel UniqueID is \"Body$Content$pnlLogin\" \n /// Button's UniqueID is \"Body$Content$ucLogin$btnLogin\" \n /// (because it's inside a control called \"ucLogin\") \n /// Set Panel.DefaultButton to \"ucLogin$btnLogin\".\n /// </summary>\n /// <param name=\"panel\"></param>\n /// <param name=\"button\"></param>\n public override string DefaultButton\n {\n get\n {\n return base.DefaultButton;\n }\n\n set\n {\n string uniqueId = value;\n string panelIdPrefix = this.NamingContainer.UniqueID + Page.IdSeparator;\n if (uniqueId.StartsWith(panelIdPrefix))\n {\n uniqueId = uniqueId.Substring(panelIdPrefix.Length);\n }\n base.DefaultButton = uniqueId;\n }\n } \n}\n" }, { "answer_id": 3014829, "author": "qwebek", "author_id": 345052, "author_profile": "https://Stackoverflow.com/users/345052", "pm_score": 2, "selected": false, "text": " <asp:Panel ID=\"panelLogin\" runat=\"server\" DefaultButton=\"Login1$LoginButton\">\n <asp:Login ID=\"Login1\" runat=\"server\" >\n <LayoutTemplate>\n ...\n <asp:Button ID=\"LoginButton\" .../>\n </LayoutTemplate>\n </asp:Login>\n </asp:Panel>\n" }, { "answer_id": 3419311, "author": "David Eison", "author_id": 72670, "author_profile": "https://Stackoverflow.com/users/72670", "pm_score": 2, "selected": false, "text": "protected void Page_Init(object sender, EventArgs e)\n{\n this.Form.DefaultButton = Login1.FindControl(\"LoginButton\").UniqueID;\n}\n DefaultButton=\"Login1$LoginButton\"" }, { "answer_id": 4524232, "author": "samuel", "author_id": 510340, "author_profile": "https://Stackoverflow.com/users/510340", "pm_score": 1, "selected": false, "text": "defaultbutton Parent$ID <asp:Panel id=\"panel1\" runat=\"server\" DefaultButton=\"Login1$LoginButton\">\n<asp:Login ID=\"Login1\" runat=\"server\" BackColor=\"#F7F6F3\">\n<LayoutTemplate>\n<table>\n...\n<tr>\n<td><asp:Button ID=\"LoginButton\" runat=\"server\" /></td>\n</tr>\n</table>\n</LayoutTemplate>\n</asp:Login>\n</asp:Panel>\n" }, { "answer_id": 6833891, "author": "Jason Marsell", "author_id": 429825, "author_profile": "https://Stackoverflow.com/users/429825", "pm_score": 1, "selected": false, "text": "<form id=\"form1\" runat=\"server\" defaultbutton=\"ucLogin$btnSubmit\">\n <!-- Login Control - use a panel so we can set the default button -->\n<asp:Panel runat=\"server\" ID=\"loginControlPanel\" DefaultButton=\"ucLogin$btnSubmit\"> \n <uc:Login runat=\"server\" ID=\"ucLogin\"/> \n</asp:Panel>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
201,778
<p>I have a user interface that requires placing some round buttons in a C# project with some data behind them. The buttons are System.Windows.Forms.buttons and I have used a GIF image with transparency to create them. However, the transparent areas aren't transparent. I've looked for references online but haven't found any suggestions for how to do this properly. There's some mention of doing it in Visual Studio 2008 but I need to keep this project in 2005. Any help or suggestion is appreciated.</p>
[ { "answer_id": 825833, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " protected override CreateParams CreateParams\n {\n get\n {\n const int WS_EX_TRANSPARENT = 0x20;\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= WS_EX_TRANSPARENT;\n return cp;\n }\n }\n SetStyle(ControlStyles.SupportsTransparentBackColor, true);\n SetStyle(ControlStyles.Opaque, true);\n this.BackColor = Color.Transparent;\n" }, { "answer_id": 1436588, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Drawing;\n\npublic class TransparentControl : Control\n{\n public TransparentControl()\n {\n SetStyle(ControlStyles.SupportsTransparentBackColor, true);\n SetStyle(ControlStyles.Opaque, true);\n SetStyle(ControlStyles.ResizeRedraw, true);\n this.BackColor = Color.Transparent;\n }\n\n protected override void OnPaint(PaintEventArgs pevent)\n {\n Graphics g = pevent.Graphics;\n g.DrawRectangle(Pens.Black, this.ClientRectangle);\n }\n\n\n protected override void OnPaintBackground(PaintEventArgs pevent)\n {\n // don't call the base class\n //base.OnPaintBackground(pevent);\n }\n\n\n protected override CreateParams CreateParams\n {\n get\n {\n const int WS_EX_TRANSPARENT = 0x20;\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= WS_EX_TRANSPARENT;\n return cp;\n }\n }\n\n // rest of class here...\n}\n" }, { "answer_id": 4182875, "author": "Bert", "author_id": 508041, "author_profile": "https://Stackoverflow.com/users/508041", "pm_score": 1, "selected": false, "text": " Bitmap temp = new Bitmap(button1.Image);\n\n temp.MakeTransparent(Color.Black); //your transparent color, in this case black\n\n button1.Image = (Image) Logo;\n\n temp.Dispose();\n\n temp = null;\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27906/" ]
201,782
<p>When manually generating a JSON object or array, it's often easier to leave a trailing comma on the last item in the object or array. For example, code to output from an array of strings might look like (in a C++ like pseudocode):</p> <pre><code>s.append("["); for (i = 0; i &lt; 5; ++i) { s.appendF("\"%d\",", i); } s.append("]"); </code></pre> <p>giving you a string like</p> <pre><code>[0,1,2,3,4,5,] </code></pre> <p>Is this allowed?</p>
[ { "answer_id": 201856, "author": "brianb", "author_id": 27892, "author_profile": "https://Stackoverflow.com/users/27892", "pm_score": 9, "selected": true, "text": "s.append(\"[\");\nfor (i = 0; i < 5; ++i) {\n if (i) s.append(\",\"); // add the comma only if this isn't the first entry\n s.appendF(\"\\\"%d\\\"\", i);\n}\ns.append(\"]\");\n" }, { "answer_id": 207681, "author": "Rik Heywood", "author_id": 4012, "author_profile": "https://Stackoverflow.com/users/4012", "pm_score": 4, "selected": false, "text": "$array = array('lastname', 'email', 'phone');\necho implode(\",\", $array); // lastname,email,phone\n" }, { "answer_id": 8531175, "author": "Overflowee", "author_id": 1101474, "author_profile": "https://Stackoverflow.com/users/1101474", "pm_score": 7, "selected": false, "text": "$delimiter = '';\nfor .... {\n print $delimiter.$whatever\n $delimiter = ',';\n}\n" }, { "answer_id": 23033546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "s.append(\"[\");\n// MAX == 5 here. if it's constant, you can inline it below and get rid of the comparison\nif ( MAX > 0 ) {\n s.appendF(\"\\\"%d\\\"\", 0); // 0-th iteration\n for( int i = 1; i < MAX; ++i ) {\n s.appendF(\",\\\"%d\\\"\", i); // i-th iteration\n }\n}\ns.append(\"]\");\n" }, { "answer_id": 29792864, "author": "Timoty Weis", "author_id": 2416998, "author_profile": "https://Stackoverflow.com/users/2416998", "pm_score": 2, "selected": false, "text": "[0,1,2,3,4,5,]\n array = begin-array [ value *( value-separator value ) ] end-array\n" }, { "answer_id": 47064069, "author": "feibing", "author_id": 2529677, "author_profile": "https://Stackoverflow.com/users/2529677", "pm_score": 1, "selected": false, "text": "jsonStr = '[0,1,2,3,4,5,]';\nlet data;\neval('data = ' + jsonStr);\nconsole.log(data)" }, { "answer_id": 53362255, "author": "Zhang Boyang", "author_id": 1953809, "author_profile": "https://Stackoverflow.com/users/1953809", "pm_score": 2, "selected": false, "text": "s.append(\"[ \"); // there is a space after the left bracket\nfor (i = 0; i < 5; ++i) {\n s.appendF(\"\\\"%d\\\",\", i); // always add comma\n}\ns.back() = ']'; // modify last comma (or the space) to right bracket\n" }, { "answer_id": 54937553, "author": "Gregory Horne 07AD", "author_id": 11039908, "author_profile": "https://Stackoverflow.com/users/11039908", "pm_score": 0, "selected": false, "text": "awk -v header=\"FirstName,LastName,DOB\" '\n BEGIN {\n FS = \",\";\n print(\"[\");\n columns = split(header, column_names, \",\");\n }\n { print(\" {\");\n for (i = 1; i < columns; i++) {\n printf(\" \\\"%s\\\":\\\"%s\\\",\\n\", column_names[i], $(i));\n }\n printf(\" \\\"%s\\\":\\\"%s\\\"\\n\", column_names[i], $(i));\n print(\" }\");\n }\n END { print(\"]\"); } ' datafile.txt\n Angela,Baker,2010-05-23\n Betty,Crockett,1990-12-07\n David,Done,2003-10-31\n" }, { "answer_id": 58878371, "author": "theking2", "author_id": 718960, "author_profile": "https://Stackoverflow.com/users/718960", "pm_score": 1, "selected": false, "text": "var a = Array()\nfor(let i=1; i<=5; i++) {\n a.push(i)\n}\nvar s = \"[\" + a.join(\",\") + \"]\"\n" }, { "answer_id": 62909779, "author": "Beni Cherniavsky-Paskin", "author_id": 239657, "author_profile": "https://Stackoverflow.com/users/239657", "pm_score": 2, "selected": false, "text": ", value ] }" }, { "answer_id": 64065832, "author": "Roland", "author_id": 1845672, "author_profile": "https://Stackoverflow.com/users/1845672", "pm_score": 3, "selected": false, "text": "Defensive Programming" }, { "answer_id": 72644879, "author": "Prudhvik Chirunomula", "author_id": 9733388, "author_profile": "https://Stackoverflow.com/users/9733388", "pm_score": 0, "selected": false, "text": "String l = \"[\" + List<int>.generate(5, (i) => i + 1).join(\",\") + \"]\";\n" }, { "answer_id": 74167082, "author": "Qwert Yuiop", "author_id": 10135157, "author_profile": "https://Stackoverflow.com/users/10135157", "pm_score": 0, "selected": false, "text": " char* str = readFile(\"myConfig.json\");\n char* chr = strrchr(str, '}') - 1;\n int i = 0;\n while( chr[i] == ' ' || chr[i] == '\\n' ){\n i--;\n }\n if( chr[i] == ',' ) chr[i] = ' ';\n JsonParser parser;\n parser.parse(str);\n\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1323/" ]
201,791
<p>I am currently coding a simple Data Access Layer, and I was wondering which type I should expose to the other layers.</p> <p>I am going to internally implement the Data as a List&lt;>, but I remember reading something about not exposing the List type to the consumers if not needed.</p> <pre><code>public List&lt;User&gt; GetAllUsers() // non C# users: that means List of User :) </code></pre> <p>Do you know why (google didn't help)? What do you usually expose for that kind of stuff? IList? IEnumerable?</p>
[ { "answer_id": 201805, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "IEnumerable<User> IList<User> IList Values IList" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5789/" ]
201,796
<p>We are using standard asp.net forms authentication. Certain pages require a user to be logged in; and least some of these pages are delivered by https. There is a search control at the top of each page. When this is used, we don't care whether the user's session has expired, even if the current page requires a log in. </p> <p>However, currently, when performing the search, the built-in forms authentication sees that the page being posted to requires authentication and redirects the user to the login page, with the previous page, <em>not the search results page</em> as the referrer.</p> <p>What is the best way of bypassing the security here? I have considered posting to a different page using the PostBackUrl property, but if this is not https you get the "you are posting data to an unsecure connection" message, which users don't like.</p> <p>Thanks for any help.</p> <p>Edit: thanks Nick for your suggestion of using a GET on the search page. We are doing this already, but the query string is constructed by the search input control then redirects. How can we build up the query string without using a postback? (Obviously javascript is an option but I was hoping to find an alternative mechanism.)</p>
[ { "answer_id": 201820, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<form method=\"post\" ...>\n <form method=\"get\" ...>\n <location path=\"my-search-page.aspx\">\n <system.web>\n <authorization>\n <allow users=\"*\" />\n </authorization>\n </system.web>\n</location>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3856/" ]
201,816
<p>I'm trying to run a particular JUnit test by hand on a Windows XP command line, which has an unusually high number of elements in the class path. I've tried several variations, such as:</p> <pre><code>set CLASS_PATH=C:\path\a\b\c;C:\path\e\f\g;.... set CLASS_PATH=%CLASS_PATH%;C:\path2\a\b\c;C:\path2\e\f\g;.... ... C:\apps\jdk1.6.0_07\bin\java.exe -client oracle.jdevimpl.junit.runner.TestRunner com.myco.myClass.MyTest testMethod </code></pre> <p>(Other variations are setting the classpath all on one line, setting the classpath via -classpath as an argument to java"). It always comes down to the console throwing up it's hands with this error:</p> <pre><code>The input line is too long. The syntax of the command is incorrect. </code></pre> <p>This is a JUnit test testing a rather large existing legacy project, so no suggestions about rearranging my directory structure to something more reasonable, those types of solutions are out for now. I was just trying to gen up a quick test against this project and run it on the command line, and the console is stonewalling me. Help!</p>
[ { "answer_id": 201857, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": -1, "selected": false, "text": "set CLASS_PATH = c:\\path\nset ALT_A = %CLASS_PATH%\\a\\b\\c;\nset ALT_B = %CLASS_PATH%\\e\\f\\g;\n...\n\nset ALL_PATHS = %CLASS_PATH%;%ALT_A%;%ALT_B%\n" }, { "answer_id": 201969, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 7, "selected": true, "text": "Manifest.mf Class-Path Manifest.mf Class-Path: this.jar that.jar ../lib/other.jar\n <jar destfile=\"pathing.jar\">\n <manifest>\n <attribute name=\"Class-Path\" value=\"this.jar that.jar ../lib/other.jar\"/>\n </manifest>\n</jar>\n" }, { "answer_id": 202034, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 4, "selected": false, "text": "foo/* foo foo;foo/* foo/*;foo" }, { "answer_id": 202199, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 1, "selected": false, "text": "classpath set CLASS_PATH=C:\\path\\a\\b\\c;C:\\path\\e\\f\\g;\nset CLASS_PATH=%CLASS_PATH%;C:\\path2\\a\\b\\c;C:\\path2\\e\\f\\g;\n set CLASS_PATH=z\\a\\b\\c;z\\e\\f\\g;\nset CLASS_PATH=%CLASS_PATH%;y:\\a\\b\\c;y:\\e\\f\\g;\n classpath" }, { "answer_id": 11416271, "author": "Shivananda Sahu", "author_id": 1515205, "author_profile": "https://Stackoverflow.com/users/1515205", "pm_score": 0, "selected": false, "text": "@echo off\nset A=D:\\jdk1.6.0_23\\bin\nset B=C:\\Documents and Settings\\674205\\Desktop\\JavaProj\nset PATH=\"%PATH%;%A%;\"\nset CLASSPATH=\"%CLASSPATH%;%B%;\"\n" }, { "answer_id": 54270831, "author": "Raman", "author_id": 430128, "author_profile": "https://Stackoverflow.com/users/430128", "pm_score": 4, "selected": false, "text": "java -cp c:\\foo\\bar.jar;c:\\foo\\baz.jar java @c:\\path\\to\\cparg c:\\path\\to\\cparg -cp c:\\foo\\bar.jar;c:\\foo\\baz.jar\n -cp \"\\\nc:\\foo\\bar.jar;\\\nc:\\foo\\baz.jar\"\n" }, { "answer_id": 55300229, "author": "user1921819", "author_id": 1921819, "author_profile": "https://Stackoverflow.com/users/1921819", "pm_score": 2, "selected": false, "text": "bootRun // Fix long path problem on Windows by utilizing java Command-Line Argument Files \n// https://docs.oracle.com/javase/9/tools/java.htm#JSWOR-GUID-4856361B-8BFD-4964-AE84-121F5F6CF111 \n// The task creates the command-line argument file with classpath\n// Then we specify the args parameter with path to command-line argument file and main class\n// Then we clear classpath and main parameters\n// As arguments are applied after applying classpath and main class last step \n// is done to cheat gradle plugin: we will skip classpath and main and manually\n// apply them through args\n// Hopefully at some point gradle will do this automatically \n// https://github.com/gradle/gradle/issues/1989 \n\nif (Os.isFamily(Os.FAMILY_WINDOWS)) {\n bootRun {\n doFirst {\n def argumentFilePath = \"build/javaArguments.txt\"\n def argumentFile = project.file(argumentFilePath)\n def writer = argumentFile.newPrintWriter()\n writer.print('-cp ')\n writer.println(classpath.join(';'))\n writer.close()\n\n args = [\"@${argumentFile.absolutePath}\", main]\n classpath = project.files()\n main = ''\n }\n }\n}\n\n" }, { "answer_id": 59370815, "author": "Trushit Shekhda", "author_id": 12444527, "author_profile": "https://Stackoverflow.com/users/12444527", "pm_score": 0, "selected": false, "text": "plugins {\n id \"com.github.ManifestClasspath\" version \"0.1.0-RELEASE\"\n}\n buildscript {\n repositories {\n maven {\n url \"https://plugins.gradle.org/m2/\"\n }\n }\n dependencies {\n classpath \"gradle.plugin.com.github.viswaramamoorthy:gradle-util-plugins:0.1.0-RELEASE\"\n }\n}\n\napply plugin: \"com.github.ManifestClasspath\"\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13140/" ]
201,829
<p>I have a format file where I want one of the columns to be "group". I'm auto-generating the format file and a client wants to upload a file with "group" as one of the columns. I could restrict it so they can't use SQL keywords, but then I need a function to determine if a column name is a SQL keyword, so I'd like to support the user being able to name their clients however they want. I'm wondering if this is possible. I tried using brackets, but that didn't appear to work. My file looks like:</p> <pre> 8.0 1 1 SQLCHAR 0 0 "\r\n" 1 [group] SQL_Latin1_General_CP1_CI_AS </pre>
[ { "answer_id": 203931, "author": "Ed Harper", "author_id": 27825, "author_profile": "https://Stackoverflow.com/users/27825", "pm_score": 1, "selected": false, "text": "Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'group'.\n C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\binn\\\n C:\\Program Files\\Microsoft SQL Server\\80\\Tools\\BINN\n" }, { "answer_id": 210720, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 0, "selected": false, "text": "SELECT id, \"group\" FROM myTable" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
201,830
<p>I just asked <a href="https://stackoverflow.com/questions/201686/linq-to-sql-select-optimization">this question</a>. Which lead me to a new question :)</p> <p>Up until this point, I have used the following pattern of selecting stuff with Linq to SQL, with the purpose of being able to handle 0 "rows" returned by the query:</p> <pre><code>var person = (from p in [DataContextObject].Persons where p.PersonsID == 1 select new p).FirstOrDefault(); if (person == null) { // handle 0 "rows" returned. } </code></pre> <p>But I can't use <code>FirstOrDefault()</code> when I do:</p> <pre><code>var person = from p in [DataContextObject].Persons where p.PersonsID == 1 select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }; // Under the hood, this pattern generates a query which selects specific // columns which will be faster than selecting all columns as the above // snippet of code does. This results in a performance-boost on large tables. </code></pre> <p>How do I check for 0 "rows" returned by the query, using the second pattern? <br /> <br /> <br /> <br /> <strong>UPDATE:</strong></p> <p>I think my build fails because I am trying to assign the result of the query to a variable (<code>this._user</code>) declared with the type of <code>[DataContext].User</code>.</p> <pre><code>this._user = (from u in [DataContextObject].Users where u.UsersID == [Int32] select new { u.UsersID }).FirstOrDefault(); </code></pre> <p><em>Compilation error: Cannot implicitly convert type "AnonymousType#1" to "[DataContext].User".</em></p> <p>Any thoughts on how I can get around this? Would I have to make my own object?</p>
[ { "answer_id": 201853, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "if (person.Any()) /* ... */;\n if (person.Count() == 0) /* ... */;\n" }, { "answer_id": 201871, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 0, "selected": false, "text": "FirstOrDefault var PersonFields = (...).FirstOrDefault() \n" }, { "answer_id": 201874, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 4, "selected": false, "text": "var person = (from p in [DataContextObject].Persons\n where p.PersonsID == 1\n select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }).FirstOrDefault();\n\nif (person == null) { \n // handle 0 \"rows\" returned.\n}\n" }, { "answer_id": 449107, "author": "Andrew", "author_id": 15127, "author_profile": "https://Stackoverflow.com/users/15127", "pm_score": 2, "selected": false, "text": "string[] names = { \"jim\", \"jane\", \"joe\", \"john\", \"jeremy\", \"jebus\" };\nvar person = (\n from p in names where p.StartsWith(\"notpresent\") select \n new { Name=p, FirstLetter=p.Substring(0,1) } \n )\n .DefaultIfEmpty(null)\n .FirstOrDefault();\n\nMessageBox.Show(person==null?\"person was null\":person.Name + \"/\" + person.FirstLetter);\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20946/" ]
201,832
<p>Hey right now I'm using jQuery and I have some global variables to hold a bit of preloaded ajax stuff (preloaded to make pages come up nice and fast):</p> <pre><code> $.get("content.py?pageName=viewer", function(data) {viewer = data;}); $.get("content.py?pageName=artists", function(data) {artists = data;}); $.get("content.py?pageName=instores", function(data) {instores = data;}); $.get("content.py?pageName=specs", function(data) {specs = data;}); $.get("content.py?pageName=about", function(data) {about = data;}); </code></pre> <p>As you can see, we have a huge violation of the DRY principle, but... I don't really see a way to fix it... any ideas?</p> <p>maybe an array?</p>
[ { "answer_id": 201855, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "var names = ['viewer', 'artists', 'instores', 'specs', 'about'];\nfor (var i = 0; i < names.length; i++)\n $.get(\"content.py?pageName=\" + names[i], new Function('data', names[i] + ' = data;'));\n" }, { "answer_id": 201903, "author": "kentaromiura", "author_id": 27340, "author_profile": "https://Stackoverflow.com/users/27340", "pm_score": 0, "selected": false, "text": "{\nviewer:'me',\nartists:'you',\ninstores:'instores',\nspecs:'specs',\nabout:'about'\n}\n" }, { "answer_id": 201941, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 3, "selected": false, "text": "jQuery.each(\n [\"viewer\", \"artists\", \"instores\", \"specs\", \"about\"],\n function (page) {\n $.get(\"content.py?pageName=\" + page,\n new Function(\"window[\" + page + \"] = arguments[0]\"));\n }\n);\n jQuery.each(\n [\"viewer\", \"artists\", \"instores\", \"specs\", \"about\"],\n function (page) {\n $.get(\"content.py?pageName=\" + page, function () { window[page] = arguments[0]; });\n }\n);\n" }, { "answer_id": 202004, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "eval() Function() (function() // keep outer scope clean\n{\n // pages to load. Each name is used both for the request and the name\n // of the property to store the result in (so keep them valid identifiers\n // unless you want to use window['my funky page'] to retrieve them)\n var pages = ['viewer', 'artists', 'instores', 'specs', 'about'];\n\n for (var i=0; i<pages.length; ++i)\n {\n // \"this\" refers to the outer scope; likely the window object. \n // And will result in page contents being stored in global variables \n // with the same names as the pages being loaded. We use the with({})\n // construct to create a local scope for each callback with the\n // appropriate context and page name.\n with ({context: this, pageName: pages[i]})\n $.get(\"content.py?pageName=\" + pageName, function(data)\n {context[pageName] = data;});\n }\n\n})(); // close scope, execute anonymous function\n\n// at this point, viewer, artists, etc. are populated with page contents \n// (assuming all requests completed successfully)\n" }, { "answer_id": 202048, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 0, "selected": false, "text": "function get_content(name){\n $.get(\"content.py?pageName=\" + name, function(data){ window[name] = data;});\n}\n\nvar names = ['viewer', 'artists', 'instores', 'specs', 'about'];\nfor (var i = 0; i < names.length; i++)\n get_content(names[i]);\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
201,840
<p>Running <code>rake db:migrate</code> followed by <code>rake test:units</code> yields the following:</p> <pre><code>rake test:functionals (in /projects/my_project) rake aborted! SQLite3::SQLException: index unique_schema_migrations already exists: CREATE UNIQUE INDEX "unique_schema_migrations" ON "ts_schema_migrations" ("version") </code></pre> <p>The relevant part of <code>db/schema.rb</code> is as follows:</p> <pre><code>create_table "ts_schema_migrations", :id =&gt; false, :force =&gt; true do |t| t.string "version", :null =&gt; false end add_index "ts_schema_migrations", ["version"], :name =&gt; "unique_schema_migrations", :unique =&gt; true </code></pre> <p>I'm not manually changing this index anywhere, and I'm using Rails' default SQLite3 adapter with a brand new database. (That is, running <code>rm db/*sqlite3</code> before <code>rake db:migrate</code> doesn't help.)</p> <p>Is the <code>test:units</code> task perhaps trying to re-load the schema? If so, why? Shouldn't it recognize the schema is already up to date?</p>
[ { "answer_id": 201900, "author": "Vitalie", "author_id": 27913, "author_profile": "https://Stackoverflow.com/users/27913", "pm_score": 0, "selected": false, "text": "unique_schema_migrations" }, { "answer_id": 206848, "author": "Tilendor", "author_id": 1470, "author_profile": "https://Stackoverflow.com/users/1470", "pm_score": 2, "selected": false, "text": "development:\n adapter: sqlite3\n database: db/dev.sqlite3\n timeout: 5000\n\ntest:\n adapter: sqlite3\n database: db/test.sqlite3\n timeout: 5000\n" }, { "answer_id": 1982880, "author": "Ian Lesperance", "author_id": 199806, "author_profile": "https://Stackoverflow.com/users/199806", "pm_score": 4, "selected": false, "text": "unique_schema_migrations" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
201,846
<p>i have the following script</p> <pre><code>import getopt, sys opts, args = getopt.getopt(sys.argv[1:], "h:s") for key,value in opts: print key, "=&gt;", value </code></pre> <p>if i name this getopt.py and run it doesn't work as it tries to import itself</p> <p>is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? </p> <p>Solution based on Vinko's answer:</p> <pre><code>import sys sys.path.reverse() from getopt import getopt opts, args = getopt(sys.argv[1:], "h:s") for key,value in opts: print key, "=&gt;", value </code></pre>
[ { "answer_id": 201862, "author": "axblount", "author_id": 1729005, "author_profile": "https://Stackoverflow.com/users/1729005", "pm_score": -1, "selected": false, "text": "import getopt as bettername\n" }, { "answer_id": 201891, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "~# cat getopt.py\nprint \"HI\"\n~# python\nPython 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)\n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> import getopt\nHI\n\n~# python\nPython 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)\n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> sys.path.remove('')\n>>> import getopt\n>>> dir(getopt)\n['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']\n import sys\nsys.path.remove('')\nfrom getopt import getopt\nsys.path.insert(0,'')\nopts, args = getopt(sys.argv[1:], \"h:s\")\nfor key,value in opts:\n print key, \"=>\", value\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
201,848
<p>I'm automating Outlook and I need to control who the email appears to be from. The users will have two or more Accounts set up in Outlook and I need to be able to select which account to send the email from. Any ideas?</p> <p>Needs to be supported on Outlook 2003 and above. I'm using Delphi 2006 to code this, but that doesn't really matter.</p>
[ { "answer_id": 201862, "author": "axblount", "author_id": 1729005, "author_profile": "https://Stackoverflow.com/users/1729005", "pm_score": -1, "selected": false, "text": "import getopt as bettername\n" }, { "answer_id": 201891, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "~# cat getopt.py\nprint \"HI\"\n~# python\nPython 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)\n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> import getopt\nHI\n\n~# python\nPython 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)\n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> sys.path.remove('')\n>>> import getopt\n>>> dir(getopt)\n['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']\n import sys\nsys.path.remove('')\nfrom getopt import getopt\nsys.path.insert(0,'')\nopts, args = getopt(sys.argv[1:], \"h:s\")\nfor key,value in opts:\n print key, \"=>\", value\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008/" ]
201,863
<p>I was wondering if anyone had successfully used DPAPI with a user store in a web farm enviroment?</p> <p>Because our application is a recently converted from 1.1 to 2.0 ASP.NET app, we're using a custom wrapper which directly calls the <code>CryptUnprotect</code> methods. But this should be the same as the <code>ProtectedData</code> method available in the 2.0 framework.</p> <p>Because we are operating in a web farm environment, we can't guarantee that the machine that did the encryption is going to be the one decrypting it. (Also because machine failures shouldn't destroy our encrypted data).</p> <p>So what we have is a serviced component that runs in a service under a particular user account on each one of our web boxes. This user is a set up to have a roaming profile, as per the recomendation.</p> <p>The problem we have is that info encrypted on one machine can not be decrypted on another, this fails with the win32 error: </p> <blockquote> <p>'Key not valid for use in specified state'.</p> </blockquote> <p>I suspect that this is because I've made a mistake by having the encryption service running as the user on multiple machines, hence keeping the user logged in on more than one machine at the same time. </p> <p>If this is the problem, how are other using DPAPI with the User Store in a web farm environment?</p>
[ { "answer_id": 63183019, "author": "codeMonkey", "author_id": 4009972, "author_profile": "https://Stackoverflow.com/users/4009972", "pm_score": 0, "selected": false, "text": "public void ConfigureServices(IServiceCollection services)\n{\n services.AddDataProtection()\n .ProtectKeysWithDpapiNG();\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
201,875
<p>How to hide the default toolbar and to disallow the default context menu of the <code>DocumentViewer</code> control?</p>
[ { "answer_id": 201911, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 2, "selected": true, "text": "ContextMenuOpening ContextMenuEventArgs.Handled" }, { "answer_id": 6098488, "author": "Mo0gles", "author_id": 283512, "author_profile": "https://Stackoverflow.com/users/283512", "pm_score": 3, "selected": false, "text": "<DocumentViewer ContextMenu=\"{x:Null}\"/>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23372/" ]
201,883
<p>I have the same problem as described in the posts listed below. That is, certain keys don't work at all when I type them into my combobox until I first hit the spacebar. One of the keys is ".", but another is the letter "Q", and there are others: "$", "%". </p> <p><a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=659716&amp;SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=659716&amp;SiteID=1</a><br> <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2909173&amp;SiteID=1&amp;pageid=0" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2909173&amp;SiteID=1&amp;pageid=0</a><br> <a href="http://bytes.com/forum/thread548399.html" rel="nofollow noreferrer">http://bytes.com/forum/thread548399.html</a></p> <p>I've tried a lot of things so far. My latest failure was based on the theory that maybe the DataGridView was using WIN32 API wndproc subclassing to intercept messages, so I wrote logic to save the old wndproc and restore it after adding it to the DataGridView's control collection. That didn't work.</p> <p>Messina - thanks for reminding me about Spy++. For the letter "A", the edit window sends an EN_UPDATE to its combobox parent. But, not for the "Q". That's so strange.</p> <p>I have convinced myself that the DataGridView is not subclassing the combo and the edit, because I check the address of the wndprocs just after creation and before adding them to the grid's collection, and then later when I paint. Unless the grid installs some sort of global hooks..</p> <p>I'm thinkin, maybe I can subclass the edit control, and then send the notification to the combobox the way I see the edit control doing here?</p> <p>EDIT: More info here. Windows messages from grid, combobox, and edit control, from Spy++:</p> <p>HWNDs: 122064e &lt; grid 010d0674 &lt; combobox 01360696 &lt; combox's edit control</p> <pre><code>&lt;01402&gt; 01360696 P WM_KEYDOWN nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0 &lt;01403&gt; 010D0674 S WM_GETDLGCODE &lt;01404&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01405&gt; 010D0674 S WM_GETDLGCODE &lt;01406&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01407&gt; 010D0674 S WM_GETDLGCODE &lt;01408&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01409&gt; 010D0674 S WM_GETDLGCODE &lt;01410&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01411&gt; 01360696 P WM_CHAR chCharCode:'0061' (97) cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0 &lt;01412&gt; 010D0674 S WM_GETDLGCODE &lt;01413&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01414&gt; 010D0674 S WM_GETDLGCODE &lt;01415&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01416&gt; 010D0674 S WM_COMMAND wNotifyCode:EN_UPDATE wID:1001 hwndCtl:01360696 &lt;&lt;&lt; edit control sends to combobox &lt;01417&gt; 010D0674 S message:0x2111 [User-defined:WM_USER+7441] wParam:00060674 lParam:010D0674 What do these do? &lt;01418&gt; 010D0674 R message:0x2111 [User-defined:WM_USER+7441] lResult:00000000 &lt;01419&gt; 010D0674 R WM_COMMAND &lt;01420&gt; 010D0674 S WM_CTLCOLOREDIT hdcEdit:C7011AA6 hwndEdit:01360696 &lt;01421&gt; 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0 &lt;01422&gt; 010D0674 S WM_COMMAND wNotifyCode:EN_CHANGE wID:1001 hwndCtl:01360696 &lt;&lt; edit control sends to combobox &lt;01423&gt; 010D0674 S message:0x2111 [User-defined:WM_USER+7441] wParam:00050674 lParam:010D0674 &lt;01424&gt; 0122064E S WM_PAINT hdc:00000000 &lt;&lt;&lt; grid is told to paint &lt;01425&gt; 0122064E S WM_ERASEBKGND hdc:94011D4E &lt;01426&gt; 0122064E R WM_ERASEBKGND fErased:True &lt;01427&gt; 0122064E S WM_GETTEXTLENGTH &lt;01428&gt; 0122064E R WM_GETTEXTLENGTH cch:0 &lt;01429&gt; 0122064E S WM_GETTEXT cchTextMax:2 lpszText:0012D0C0 &lt;01430&gt; 0122064E R WM_GETTEXT cchCopied:0 lpszText:0012D0C0 ("") &lt;01431&gt; 0122064E S WM_GETTEXTLENGTH &lt;01432&gt; 0122064E R WM_GETTEXTLENGTH cch:0 &lt;01433&gt; 0122064E S WM_GETTEXT cchTextMax:2 lpszText:0012D0C0 &lt;01434&gt; 0122064E R WM_GETTEXT cchCopied:0 lpszText:0012D0C0 ("") &lt;01435&gt; 010D0674 S WM_WINDOWPOSCHANGING lpwp:0012D4B0 &lt;01436&gt; 010D0674 R WM_WINDOWPOSCHANGING &lt;01437&gt; 010D0674 S CB_GETCURSEL &lt;01438&gt; 010D0674 R CB_GETCURSEL index:CB_ERR &lt;01439&gt; 010D0674 S WM_GETTEXTLENGTH &lt;01440&gt; 01360696 S WM_GETTEXTLENGTH &lt;01441&gt; 01360696 R WM_GETTEXTLENGTH cch:2 &lt;01442&gt; 010D0674 R WM_GETTEXTLENGTH cch:2 &lt;01443&gt; 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012CC44 &lt;01444&gt; 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012BE64 &lt;01445&gt; 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012BE64 ("a") &lt;01446&gt; 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012CC44 ("a") &lt;01447&gt; 010D0674 S CB_GETCURSEL &lt;01448&gt; 010D0674 R CB_GETCURSEL index:CB_ERR &lt;01449&gt; 010D0674 S WM_GETTEXTLENGTH &lt;01450&gt; 01360696 S WM_GETTEXTLENGTH &lt;01451&gt; 01360696 R WM_GETTEXTLENGTH cch:2 &lt;01452&gt; 010D0674 R WM_GETTEXTLENGTH cch:2 &lt;01453&gt; 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012CC44 &lt;01454&gt; 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012BE64 &lt;01455&gt; 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012BE64 ("a") &lt;01456&gt; 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012CC44 ("a") &lt;01457&gt; 010D0674 S CB_GETCURSEL &lt;01458&gt; 010D0674 R CB_GETCURSEL index:CB_ERR &lt;01531&gt; 0122064E R WM_PAINT &lt;01532&gt; 010D0674 S WM_PAINT hdc:00000000 &lt;01533&gt; 010D0674 S WM_NCPAINT hrgn:00000001 &lt;01534&gt; 010D0674 R WM_NCPAINT &lt;01535&gt; 010D0674 S WM_ERASEBKGND hdc:0F0141ED &lt;01536&gt; 010D0674 R WM_ERASEBKGND fErased:True &lt;01537&gt; 0122064E S WM_CTLCOLOREDIT hdcEdit:840137F1 hwndEdit:010D0674 &lt;01538&gt; 0122064E R WM_CTLCOLOREDIT hBrush:F0103EB0 &lt;01539&gt; 010D0674 R WM_PAINT &lt;01540&gt; 01360696 S WM_PAINT hdc:00000000 &lt;01541&gt; 01360696 S WM_NCPAINT hrgn:00000001 &lt;01542&gt; 01360696 R WM_NCPAINT &lt;01543&gt; 01360696 S WM_ERASEBKGND hdc:C7011AA6 &lt;01544&gt; 01360696 R WM_ERASEBKGND fErased:True &lt;01545&gt; 010D0674 S WM_CTLCOLOREDIT hdcEdit:870137F1 hwndEdit:01360696 &lt;01546&gt; 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0 &lt;01547&gt; 010D0674 S WM_CTLCOLOREDIT hdcEdit:870137F1 hwndEdit:01360696 &lt;01548&gt; 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0 &lt;01549&gt; 01360696 R WM_PAINT &lt;01555&gt; 0122064E S WM_CTLCOLOREDIT hdcEdit:8A0137F1 hwndEdit:010306AC &lt;01556&gt; 0122064E R WM_CTLCOLOREDIT hBrush:78103C5B &lt;01568&gt; 010D0674 S CB_GETCURSEL &lt;01569&gt; 010D0674 R CB_GETCURSEL index:CB_ERR &lt;01570&gt; 010D0674 S WM_GETTEXTLENGTH &lt;01571&gt; 01360696 S WM_GETTEXTLENGTH &lt;01572&gt; 01360696 R WM_GETTEXTLENGTH cch:2 &lt;01573&gt; 010D0674 R WM_GETTEXTLENGTH cch:2 &lt;01574&gt; 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D7A4 &lt;01575&gt; 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C9C4 &lt;01576&gt; 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C9C4 ("a") &lt;01577&gt; 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D7A4 ("a") &lt;01578&gt; 010D0674 S CB_GETCURSEL &lt;01579&gt; 010D0674 R CB_GETCURSEL index:CB_ERR &lt;01580&gt; 010D0674 S WM_GETTEXTLENGTH &lt;01581&gt; 01360696 S WM_GETTEXTLENGTH &lt;01582&gt; 01360696 R WM_GETTEXTLENGTH cch:2 &lt;01583&gt; 010D0674 R WM_GETTEXTLENGTH cch:2 &lt;01584&gt; 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D6E0 &lt;01585&gt; 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C900 &lt;01586&gt; 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C900 ("a") &lt;01587&gt; 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D6E0 ("a") &lt;01588&gt; 010D0674 S CB_GETCURSEL &lt;01589&gt; 010D0674 R CB_GETCURSEL index:CB_ERR &lt;01590&gt; 010D0674 S WM_GETTEXTLENGTH &lt;01591&gt; 01360696 S WM_GETTEXTLENGTH &lt;01592&gt; 01360696 R WM_GETTEXTLENGTH cch:2 &lt;01593&gt; 010D0674 R WM_GETTEXTLENGTH cch:2 &lt;01594&gt; 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D6E0 &lt;01595&gt; 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C900 &lt;01596&gt; 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C900 ("a") &lt;01597&gt; 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D6E0 ("a") &lt;01598&gt; 010D0674 R message:0x2111 [User-defined:WM_USER+7441] lResult:00000000 &lt;01599&gt; 01360696 S WM_GETTEXTLENGTH &lt;01600&gt; 01360696 R WM_GETTEXTLENGTH cch:2 &lt;01601&gt; 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012DF8C &lt;01602&gt; 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012DF8C ("a") &lt;01603&gt; 010D0674 R WM_COMMAND &lt;01604&gt; 01360696 P WM_KEYUP nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:1 </code></pre> <p>Letter q</p> <pre><code>&lt;01625&gt; 01360696 P WM_KEYDOWN nVirtKey:'Q' cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:0 fUp:0 &lt;01626&gt; 010D0674 S WM_GETDLGCODE &lt;01627&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01628&gt; 010D0674 S WM_GETDLGCODE &lt;01629&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01630&gt; 010D0674 S WM_GETDLGCODE &lt;01631&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01632&gt; 010D0674 S WM_GETDLGCODE &lt;01633&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01634&gt; 01360696 P WM_CHAR chCharCode:'0071' (113) cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:0 fUp:0 &lt;01635&gt; 010D0674 S WM_GETDLGCODE &lt;01636&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01637&gt; 010D0674 S WM_GETDLGCODE &lt;01638&gt; 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS &lt;01640&gt; 01360696 P WM_KEYUP nVirtKey:'Q' cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:1 fUp:1 </code></pre>
[ { "answer_id": 454773, "author": "Michael Buen", "author_id": 11432, "author_profile": "https://Stackoverflow.com/users/11432", "pm_score": 2, "selected": true, "text": "public bool EditingControlWantsInputKey(\n Keys key, bool dataGridViewWantsInputKey)\n{\n // Let the DateTimePicker handle the keys listed.\n switch (key & Keys.KeyCode)\n {\n case Keys.Left:\n case Keys.Up:\n case Keys.Down:\n case Keys.Right:\n case Keys.Home:\n case Keys.End:\n case Keys.PageDown:\n case Keys.PageUp:\n return true;\n default:\n return false; // I changed this to: return !dataGridViewWantsInputKey. My usercontrol can now receive Q, period, dollar, etc.\n }\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
201,887
<p>Is there a cross database platform way to get the primary key of the record you have just inserted?</p> <p>I noted that <a href="https://stackoverflow.com/questions/165156/easy-mysql-question-regarding-primary-keys-and-an-insert">this answer</a> says that you can get it by Calling <code>SELECT LAST_INSERT_ID()</code> and I think that you can call <code>SELECT @@IDENTITY AS 'Identity';</code> is there a common way to do this accross databases in jdbc?</p> <p>If not how would you suggest I implement this for a piece of code that could access any of SQL Server, MySQL and Oracle?</p>
[ { "answer_id": 202533, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 7, "selected": true, "text": "pInsertOid = connection.prepareStatement(INSERT_OID_SQL, Statement.RETURN_GENERATED_KEYS);\n // fill in the prepared statement and\npInsertOid.executeUpdate();\nResultSet rs = pInsertOid.getGeneratedKeys();\nif (rs.next()) {\n int newId = rs.getInt(1);\n oid.setId(newId);\n}\n" }, { "answer_id": 13873673, "author": "atripathi", "author_id": 1862828, "author_profile": "https://Stackoverflow.com/users/1862828", "pm_score": 5, "selected": false, "text": "String key[] = {\"ID\"}; //put the name of the primary key column\n\nps = con.prepareStatement(insertQuery, key);\nps.executeUpdate();\n\nrs = ps.getGeneratedKeys();\nif (rs.next()) {\n generatedKey = rs.getLong(1);\n}\n" }, { "answer_id": 31740789, "author": "ANURAG SHARMA", "author_id": 5176873, "author_profile": "https://Stackoverflow.com/users/5176873", "pm_score": -1, "selected": false, "text": "auto_increment ResultSet ds=st.executeQuery(\"select * from user\");\n while(ds.next())\n {\n\n ds.last();\n System.out.println(\"please note down your registration id which is \"+ds.getInt(\"id\"));\n }\n ds.close();\n ds.last()" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
201,893
<p>I'm working to set up Panda on an Amazon EC2 instance. I set up my account and tools last night and had no problem using SSH to interact with my own personal instance, but right now I'm not being allowed permission into Panda's EC2 instance. <a href="http://pandastream.com/docs/getting_started" rel="noreferrer">Getting Started with Panda</a></p> <p>I'm getting the following error:</p> <pre><code>@ WARNING: UNPROTECTED PRIVATE KEY FILE! @ Permissions 0644 for '~/.ec2/id_rsa-gsg-keypair' are too open. It is recommended that your private key files are NOT accessible by others. This private key will be ignored. </code></pre> <p>I've chmoded my keypair to 600 in order to get into my personal instance last night, and experimented at length setting the permissions to 0 and even generating new key strings, but nothing seems to be working.</p> <p>Any help at all would be a great help!</p> <hr> <p>Hm, it seems as though unless permissions are set to 777 on the directory, the ec2-run-instances script is unable to find my keyfiles. I'm new to SSH so I might be overlooking something.</p>
[ { "answer_id": 201898, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 6, "selected": false, "text": "chmod 700 ~/.ec2\n" }, { "answer_id": 25681412, "author": "Alena", "author_id": 989896, "author_profile": "https://Stackoverflow.com/users/989896", "pm_score": 6, "selected": false, "text": "sudo chmod 600 ~/.ssh/id_rsa\nsudo chmod 600 ~/.ssh/id_rsa.pub\n sudo chmod 644 ~/.ssh/known_hosts\n sudo chmod 755 ~/.ssh\n" }, { "answer_id": 29692711, "author": "Sandeep Sasikumar", "author_id": 4341230, "author_profile": "https://Stackoverflow.com/users/4341230", "pm_score": 5, "selected": false, "text": "chmod 700 .ssh\n chmod 600 .ssh/id_rsa\n chmod 644 .ssh/id_rsa.pub\n" }, { "answer_id": 44410255, "author": "Prince Charu", "author_id": 8124996, "author_profile": "https://Stackoverflow.com/users/8124996", "pm_score": 2, "selected": false, "text": "ssh -I(small i) \"hi.pem\" ec2-user@ec2-**-***-**-***.us-west-2.compute.amazonaws.com\n cd /Users/prince/Desktop ls **.pem **.ppk known_hosts ~/.ssh/config Host your.server\nHostName ec2-user@ec2-**-***-**-***.us-west-2.compute.amazonaws.com\nUser ec2-user\nIdentityFile ~/.ec2/id_rsa-gsg-keypair\nIdentitiesOnly yes\n ssh your.server" }, { "answer_id": 44533445, "author": "Abdel Hegazi", "author_id": 2080766, "author_profile": "https://Stackoverflow.com/users/2080766", "pm_score": 0, "selected": false, "text": "ssh -i file.pem centos@public_IP" }, { "answer_id": 51299474, "author": "ANAND SONI", "author_id": 4907956, "author_profile": "https://Stackoverflow.com/users/4907956", "pm_score": 5, "selected": false, "text": "sudo chmod 600 /path/to/my/key.pem" }, { "answer_id": 53799161, "author": "Dheeraj", "author_id": 5985586, "author_profile": "https://Stackoverflow.com/users/5985586", "pm_score": 3, "selected": false, "text": "chmod 400 *****.pem\n\nssh -i \"******.pem\" ubuntu@ec2-11-111-111-111.us-east-2.compute.amazonaws.com\n" }, { "answer_id": 56860192, "author": "Kubie", "author_id": 8422565, "author_profile": "https://Stackoverflow.com/users/8422565", "pm_score": -1, "selected": false, "text": "ssh -i /path/to/keyfile.pem user@some-host keyfile.pem ~/.ssh/ chmod 777" }, { "answer_id": 57288745, "author": "Greenkraftz", "author_id": 9794314, "author_profile": "https://Stackoverflow.com/users/9794314", "pm_score": 3, "selected": false, "text": "sudo chmod 700 keyfile.pem\n" }, { "answer_id": 58452178, "author": "Luc", "author_id": 1201863, "author_profile": "https://Stackoverflow.com/users/1201863", "pm_score": 0, "selected": false, "text": "0400 authfile.c sshkey_perm_ok /*\n * if a key owned by the user is accessed, then we check the\n * permissions of the file. if the key owned by a different user,\n * then we don't care.\n */\nif ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {\n error(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\");\n error(\"@ WARNING: UNPROTECTED PRIVATE KEY FILE! @\");\n error(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\");\n error(\"Permissions 0%3.3o for '%s' are too open.\",\n (u_int)st.st_mode & 0777, filename);\n error(\"It is required that your private key files are NOT accessible by others.\");\n error(\"This private key will be ignored.\");\n return SSH_ERR_KEY_BAD_PERMISSIONS;\n}\n 07 0b111" }, { "answer_id": 74109836, "author": "Sandip Mahato", "author_id": 13913019, "author_profile": "https://Stackoverflow.com/users/13913019", "pm_score": 0, "selected": false, "text": "ssh -i /path/to/keyfile.pem user@some-host\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2293/" ]
201,896
<p>I want something that can check if a string is <code>"SELECT"</code>, <code>"INSERT"</code>, etc. I'm just curious if this exists.</p>
[ { "answer_id": 201902, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 3, "selected": true, "text": " HashSet<String> sqlKeywords =\n new HashSet<String>(Arrays.asList(\n new String[] { ... cut and paste a list of sql keywords here .. }));\n" }, { "answer_id": 202596, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 2, "selected": false, "text": "String selectStatement = \"SELECT * FROM User WHERE userId = ? \";\nPreparedStatement prepStmt = con.prepareStatement(selectStatement);\nprepStmt.setString(1, userId);\nResultSet rs = prepStmt.executeQuery();\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
201,940
<p>This was an job placement interview I faced. They asked whether we can realloc Array, I told yes. Then They asked - then why we need pointers as most of the people give reason that it wastes memory space. I could not able to give satisfactory answer. If any body can give any satisfactory answer, I'll be obliged. Please mention any situation where the above statement can contradict.</p> <p>Thank you.</p>
[ { "answer_id": 202019, "author": "Tarski", "author_id": 27653, "author_profile": "https://Stackoverflow.com/users/27653", "pm_score": 1, "selected": false, "text": "void *realloc(void *ptr, size_t size);\n" }, { "answer_id": 202023, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "int *a = malloc(10 * sizeof(int)); int a[10];" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24813/" ]
201,956
<p>Often times I need a collection of non-sequential objects with numeric identifiers. I like using the KeyedCollection for this, but I think there's a serious drawback. If you use an int for the key, you can no longer access members of the collection by their index (collection[index] is now really collection[key]). Is this a serious enough problem to avoid using the int as the key? What would a preferable alternative be? (maybe int.ToString()?)</p> <p>I've done this before without any major problems, but recently I hit a nasty snag where XML serialization against a KeyedCollection does <em>not</em> work if the key is an int, due to <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=120461" rel="noreferrer">a bug in .NET</a>.</p>
[ { "answer_id": 201968, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "GetById(int) Collection<T> public class FooCollection : Collection<Foo>\n { Dictionary<int,Foo> dict = new Dictionary<int,Foo>();\n\n public Foo GetById(int id) { return dict[id]; }\n\n public bool Contains(int id) { return dict.Containskey(id);}\n\n protected override void InsertItem(Foo f)\n { dict[f.Id] = f;\n base.InsertItem(f);\n }\n\n protected override void ClearItems()\n { dict.Clear();\n base.ClearItems();\n }\n\n protected override void RemoveItem(int index)\n { dict.Remove(base.Items[index].Id);\n base.RemoveItem(index);\n }\n\n protected override void SetItem(int index, Foo item)\n { dict.Remove(base.Items[index].Id);\n dict[item.Id] = item;\n base.SetItem(index, item);\n }\n }\n\n\n\n\n\n\n\n\n\n }\n" }, { "answer_id": 201983, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "int struct struct Id {\n public int Value;\n\n public Id(int value) { Value = value; }\n\n override int GetHashCode() { return Value.GetHashCode(); }\n\n // … Equals method.\n}\n" }, { "answer_id": 202050, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": true, "text": "for(int i=0; i=< myCollection.Count; i++)\n{\n ... myCollection[i] ...\n}\n for(int i=0; i=< myCollection.Count; i++)\n{\n ... ((Collection<MyType>)myCollection)[i] ...\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27414/" ]
201,957
<p>I am attempting to create a Clipboard stack in C#. Clipboard data is stored in <code>System.Windows.Forms.DataObject</code> objects. I wanted to store each clipboard entry (<code>IDataObject</code>) directly in a Generic list. Due to the way Bitmaps (seem to be) stored I am thinking I need to perform a deep copy first before I add it to the list.</p> <p>I attempted to use Binary serialization (see below) to create a deep copy but since <code>System.Windows.Forms.DataObject</code> is not marked as serializable the serialization step fails. Any ideas?</p> <pre><code>public IDataObject GetClipboardData() { MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, Clipboard.GetDataObject()); memoryStream.Position = 0; return (IDataObject) binaryFormatter.Deserialize(memoryStream); } </code></pre>
[ { "answer_id": 202020, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": " public static class GhettoSerializer\n {\n // you could make this a factory method if your type\n // has a constructor that appeals to you (i.e. default \n // parameterless constructor)\n public static void Initialize<T>(T instance, IDictionary<string, object> values)\n {\n var props = typeof(T).GetProperties();\n\n // my approach does nothing to handle rare properties with array indexers\n var matches = props.Join(\n values,\n pi => pi.Name,\n kvp => kvp.Key,\n (property, kvp) =>\n new {\n Set = new Action<object,object,object[]>(property.SetValue), \n kvp.Value\n }\n );\n\n foreach (var match in matches)\n match.Set(instance, match.Value, null);\n }\n public static IDictionary<string, object> Serialize<T>(T instance)\n {\n var props = typeof(T).GetProperties();\n\n var ret = new Dictionary<string, object>();\n\n foreach (var property in props)\n {\n if (!property.CanWrite || !property.CanRead)\n continue;\n ret.Add(property.Name, property.GetValue(instance, null));\n }\n\n return ret;\n }\n }\n" }, { "answer_id": 19837014, "author": "No answer", "author_id": 2696426, "author_profile": "https://Stackoverflow.com/users/2696426", "pm_score": 0, "selected": false, "text": "private void InspectRecursively(object input,\n Dictionary<object, bool> processedObjects)\n{\n if ((input != null) && !processedObjects.ContainsKey(input))\n {\n processedObjects.Add(input, true);\n\n List<FieldInfo> fields = type.GetFields(BindingFlags.Instance |\n BindingFlags.Public | BindingFlags.NonPublic );\n foreach (FieldInfo field in fields)\n {\n object nextInput = field.GetValue(input);\n\n if (nextInput is System.Collections.IEnumerable)\n {\n System.Collections.IEnumerator enumerator = (nextInput as\n System.Collections.IEnumerable).GetEnumerator();\n\n while (enumerator.MoveNext())\n {\n InspectRecursively(enumerator.Current, processedObjects);\n }\n }\n else\n {\n InspectRecursively(nextInput, processedObjects);\n }\n }\n }\n}\n System.Runtime.Serialization.FormatterServices.GetUninitializedObject(Type type) field.SetValue(input, output) [OnDeserialized] ISerializable" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2690646/" ]
201,966
<p>I'm trying to create a QTVR movie via QTKit, and I've got all the frames in the movie. However, setting the attributes necessary doesn't seem to be having any effect. For example:</p> <pre><code>NSNumber *val = [NSNumber numberWithBool:YES]; [fMovie setAttribute:val forKey:QTMovieIsInteractiveAttribute]; val = [NSNumber numberWithBool:NO]; [fMovie setAttribute:val forKey:QTMovieIsLinearAttribute]; </code></pre> <p>If I then get the value of these attributes, they come up as NO and YES, respectively. The movie is editable, so I can't understand what I'm doing wrong here. How can I ensure that the attributes will actually change?</p>
[ { "answer_id": 513584, "author": "Daniel", "author_id": 6852, "author_profile": "https://Stackoverflow.com/users/6852", "pm_score": 1, "selected": false, "text": "NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:\n [NSNumber numberWithBool:YES], QTMovieExport,\n [exportSettings objectForKey: @\"subtype\"], QTMovieExportType,\n [exportSettings objectForKey: @\"manufacturer\"], QTMovieExportManufacturer,\n [exportSettings objectForKey: @\"settings\"], QTMovieExportSettings, \n nil];\n\nBOOL didSucceed = [movie writeToFile: tmpFileName withAttributes:dictionary error: &error];\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830/" ]
201,978
<p>I use Visual Studio to do a lot of my coding. I find the open containing folder feature quite helpful. But I don't want the folder to be "opened" by the windows explorer, instead I want to "explore" the folder -- you know, get the nice little frame showing me all the other folders on the left hand side. Does anyone know how to do this?</p> <p>Thank you, Rohit</p>
[ { "answer_id": 513584, "author": "Daniel", "author_id": 6852, "author_profile": "https://Stackoverflow.com/users/6852", "pm_score": 1, "selected": false, "text": "NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:\n [NSNumber numberWithBool:YES], QTMovieExport,\n [exportSettings objectForKey: @\"subtype\"], QTMovieExportType,\n [exportSettings objectForKey: @\"manufacturer\"], QTMovieExportManufacturer,\n [exportSettings objectForKey: @\"settings\"], QTMovieExportSettings, \n nil];\n\nBOOL didSucceed = [movie writeToFile: tmpFileName withAttributes:dictionary error: &error];\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27928/" ]
201,992
<p>I am coding a program that reads data directly from user input and was wondering how could I (without loops) read all data until EOF from standard input. I was considering using <code>cin.get( input, '\0' )</code> but <code>'\0'</code> is not really the EOF character, that just reads until EOF or <code>'\0'</code>, whichever comes first.</p> <p>Or is using loops the only way to do it? If so, what is the best way?</p>
[ { "answer_id": 202043, "author": "trotterdylan", "author_id": 17695, "author_profile": "https://Stackoverflow.com/users/17695", "pm_score": 7, "selected": false, "text": "stdin std::getline() std::string line;\nwhile (std::getline(std::cin, line))\n{\n std::cout << line << std::endl;\n}\n getline() getline()" }, { "answer_id": 202097, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 6, "selected": false, "text": "#include <string>\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <iterator>\n\nint main()\n{\n// don't skip the whitespace while reading\n std::cin >> std::noskipws;\n\n// use stream iterators to copy the stream to a string\n std::istream_iterator<char> it(std::cin);\n std::istream_iterator<char> end;\n std::string results(it, end);\n\n std::cout << results;\n}\n" }, { "answer_id": 202120, "author": "Degvik", "author_id": 26276, "author_profile": "https://Stackoverflow.com/users/26276", "pm_score": 6, "selected": false, "text": "#include <iostream>\nusing namespace std;\n...\n// numbers\nint n;\nwhile (cin >> n)\n{\n ...\n}\n// lines\nstring line;\nwhile (getline(cin, line))\n{\n ...\n}\n// characters\nchar c;\nwhile (cin.get(c))\n{\n ...\n}\n" }, { "answer_id": 6132182, "author": "Bryan", "author_id": 770491, "author_profile": "https://Stackoverflow.com/users/770491", "pm_score": 0, "selected": false, "text": "while(std::cin) {\n // do something\n}\n" }, { "answer_id": 11793641, "author": "liborm", "author_id": 1496234, "author_profile": "https://Stackoverflow.com/users/1496234", "pm_score": 2, "selected": false, "text": "while (std::getline(std::cin, line)) while (fgets(buf, 100, stdin))" }, { "answer_id": 11906161, "author": "derpface", "author_id": 1578197, "author_profile": "https://Stackoverflow.com/users/1578197", "pm_score": 0, "selected": false, "text": "// Needed headers: iostream\n\nchar buffer[256];\ncin.get( buffer, '\\x1A' );\n // Needed headers: iostream, string, and fstream\n\nstring buffer;\n\n ifstream fin;\n fin.open(\"test.txt\");\n if(fin.is_open()) {\n getline(fin,buffer,'\\x1A');\n\n fin.close();\n }\n" }, { "answer_id": 27557352, "author": "0xbadf00d", "author_id": 547231, "author_profile": "https://Stackoverflow.com/users/547231", "pm_score": 0, "selected": false, "text": "std::vector<char> data;\n EOF std::copy(std::istream_iterator<char>(std::cin),\n std::istream_iterator<char>(),\n std::back_inserter(data));\n std::bad_alloc N data.reserve(N); \nwhile (/*some condition is met*/)\n{\n std::copy_n(std::istream_iterator<char>(std::cin),\n N,\n std::back_inserter(data));\n\n /* process data */\n\n data.clear();\n}\n" }, { "answer_id": 30306694, "author": "FrankHB", "author_id": 2307646, "author_profile": "https://Stackoverflow.com/users/2307646", "pm_score": 3, "selected": false, "text": "#include <iostream>\nint main()\n{\n std::cout << std::cin.rdbuf();\n}\n std::ostringstream" }, { "answer_id": 36978839, "author": "Richard Smith", "author_id": 4862445, "author_profile": "https://Stackoverflow.com/users/4862445", "pm_score": 5, "selected": false, "text": "std::istream_iterator std:istreambuf_iterator #include <iostream>\n#include <iterator>\n#include <string>\n\nint main()\n{\n std::istreambuf_iterator<char> begin(std::cin), end;\n std::string s(begin, end);\n std::cout << s;\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14759/" ]
202,002
<p>I need to open a Microsoft Word 2003 file and change its file properties. Such as changing the Subject in the Summary Tab. <br/> <img src="https://i.stack.imgur.com/FEpJY.gif" alt="alt text"></p>
[ { "answer_id": 202880, "author": "AR.", "author_id": 1354, "author_profile": "https://Stackoverflow.com/users/1354", "pm_score": 4, "selected": true, "text": "Private Sub ProcessOfficeDocument(ByVal fileName As String)\n Dim docDSO As New DSOFile.OleDocumentPropertiesClass\n Dim docTitle, docModified, docAuthor, docKeywords As String\n Try\n docDSO.Open(fileName, True)\n Dim docSummary As DSOFile.SummaryProperties = docDSO.SummaryProperties\n docTitle = docSummary.Title\n docAuthor = docSummary.Author\n docKeywords = docSummary.Keywords\n docModified = CStr(docSummary.DateLastSaved)\n\n If (Not String.IsNullOrEmpty(docTitle)) Then\n _Title = docTitle\n End If\n\n If (Not String.IsNullOrEmpty(docAuthor)) Then\n _Author = docAuthor\n End If\n\n If (Not String.IsNullOrEmpty(docModified)) Then\n _DateModified = DateTime.Parse(docModified)\n End If\n\n Catch ex As Exception\n 'Do whatever you need to do here...'\n Finally\n If (Not docDSO Is Nothing) Then\n docDSO.Close()\n End If\n End Try\nEnd Sub\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
202,009
<p>Required is the true language version of the OS, not the user interface language or the current locale settings.</p> <p>Use case: software installation which has to apply security settings and user account creation. The scripts have to know certain system properties like user group names in the original language of the OS.</p> <p>(Should work with Windows XP, Windows Server 2003, Vista, ...)</p>
[ { "answer_id": 204590, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 3, "selected": true, "text": "WellKnownSidType = 27 (WinBuiltinUsersSid)" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23772/" ]
202,011
<p>How can I encrypt and decrypt a string in C#?</p>
[ { "answer_id": 202075, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 7, "selected": false, "text": "KeySize - MinimumPadding var provider = new System.Security.Cryptography.RSACryptoServiceProvider();\nprovider.ImportParameters(your_rsa_key);\n\nvar encryptedBytes = provider.Encrypt(\n System.Text.Encoding.UTF8.GetBytes(\"Hello World!\"), true);\n\nstring decryptedTest = System.Text.Encoding.UTF8.GetString(\n provider.Decrypt(encryptedBytes, true));\n" }, { "answer_id": 2791259, "author": "Brett", "author_id": 188474, "author_profile": "https://Stackoverflow.com/users/188474", "pm_score": 9, "selected": false, "text": "public class Crypto\n{\n\n //While an app specific salt is not the best practice for\n //password based encryption, it's probably safe enough as long as\n //it is truly uncommon. Also too much work to alter this answer otherwise.\n private static byte[] _salt = __To_Do__(\"Add a app specific salt here\");\n\n /// <summary>\n /// Encrypt the given string using AES. The string can be decrypted using \n /// DecryptStringAES(). The sharedSecret parameters must match.\n /// </summary>\n /// <param name=\"plainText\">The text to encrypt.</param>\n /// <param name=\"sharedSecret\">A password used to generate a key for encryption.</param>\n public static string EncryptStringAES(string plainText, string sharedSecret)\n {\n if (string.IsNullOrEmpty(plainText))\n throw new ArgumentNullException(\"plainText\");\n if (string.IsNullOrEmpty(sharedSecret))\n throw new ArgumentNullException(\"sharedSecret\");\n\n string outStr = null; // Encrypted string to return\n RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.\n\n try\n {\n // generate the key from the shared secret and the salt\n Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);\n\n // Create a RijndaelManaged object\n aesAlg = new RijndaelManaged();\n aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);\n\n // Create a decryptor to perform the stream transform.\n ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);\n\n // Create the streams used for encryption.\n using (MemoryStream msEncrypt = new MemoryStream())\n {\n // prepend the IV\n msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));\n msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n }\n outStr = Convert.ToBase64String(msEncrypt.ToArray());\n }\n }\n finally\n {\n // Clear the RijndaelManaged object.\n if (aesAlg != null)\n aesAlg.Clear();\n }\n\n // Return the encrypted bytes from the memory stream.\n return outStr;\n }\n\n /// <summary>\n /// Decrypt the given string. Assumes the string was encrypted using \n /// EncryptStringAES(), using an identical sharedSecret.\n /// </summary>\n /// <param name=\"cipherText\">The text to decrypt.</param>\n /// <param name=\"sharedSecret\">A password used to generate a key for decryption.</param>\n public static string DecryptStringAES(string cipherText, string sharedSecret)\n {\n if (string.IsNullOrEmpty(cipherText))\n throw new ArgumentNullException(\"cipherText\");\n if (string.IsNullOrEmpty(sharedSecret))\n throw new ArgumentNullException(\"sharedSecret\");\n\n // Declare the RijndaelManaged object\n // used to decrypt the data.\n RijndaelManaged aesAlg = null;\n\n // Declare the string used to hold\n // the decrypted text.\n string plaintext = null;\n\n try\n {\n // generate the key from the shared secret and the salt\n Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);\n\n // Create the streams used for decryption. \n byte[] bytes = Convert.FromBase64String(cipherText);\n using (MemoryStream msDecrypt = new MemoryStream(bytes))\n {\n // Create a RijndaelManaged object\n // with the specified key and IV.\n aesAlg = new RijndaelManaged();\n aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);\n // Get the initialization vector from the encrypted stream\n aesAlg.IV = ReadByteArray(msDecrypt);\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n\n // Read the decrypted bytes from the decrypting stream\n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n finally\n {\n // Clear the RijndaelManaged object.\n if (aesAlg != null)\n aesAlg.Clear();\n }\n\n return plaintext;\n }\n\n private static byte[] ReadByteArray(Stream s)\n {\n byte[] rawLength = new byte[sizeof(int)];\n if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)\n {\n throw new SystemException(\"Stream did not contain properly formatted byte array\");\n }\n\n byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];\n if (s.Read(buffer, 0, buffer.Length) != buffer.Length)\n {\n throw new SystemException(\"Did not read byte array properly\");\n }\n\n return buffer;\n }\n}\n" }, { "answer_id": 5509947, "author": "BPL", "author_id": 666157, "author_profile": "https://Stackoverflow.com/users/666157", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Text;\nusing System.Security.Cryptography;\n\nnamespace Encription\n{\n class CryptorEngine\n {\n public static string Encrypt(string ToEncrypt, bool useHasing)\n {\n byte[] keyArray;\n byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);\n //System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();\n string Key = \"Bhagwati\";\n if (useHasing)\n {\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));\n hashmd5.Clear(); \n }\n else\n {\n keyArray = UTF8Encoding.UTF8.GetBytes(Key);\n }\n TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();\n tDes.Key = keyArray;\n tDes.Mode = CipherMode.ECB;\n tDes.Padding = PaddingMode.PKCS7;\n ICryptoTransform cTransform = tDes.CreateEncryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);\n tDes.Clear();\n return Convert.ToBase64String(resultArray, 0, resultArray.Length);\n }\n public static string Decrypt(string cypherString, bool useHasing)\n {\n byte[] keyArray;\n byte[] toDecryptArray = Convert.FromBase64String(cypherString);\n //byte[] toEncryptArray = Convert.FromBase64String(cypherString);\n //System.Configuration.AppSettingsReader settingReader = new AppSettingsReader();\n string key = \"Bhagwati\";\n if (useHasing)\n {\n MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();\n keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n hashmd.Clear();\n }\n else\n {\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n }\n TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();\n tDes.Key = keyArray;\n tDes.Mode = CipherMode.ECB;\n tDes.Padding = PaddingMode.PKCS7;\n ICryptoTransform cTransform = tDes.CreateDecryptor();\n try\n {\n byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);\n\n tDes.Clear();\n return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);\n }\n catch (Exception ex)\n {\n throw ex;\n }\n }\n }\n}\n" }, { "answer_id": 10366194, "author": "jbtule", "author_id": 637783, "author_profile": "https://Stackoverflow.com/users/637783", "pm_score": 9, "selected": false, "text": "NewKey() byte[] /*\n * This work (Modern Encryption of a String C#, by James Tuley), \n * identified by James Tuley, is free of known copyright restrictions.\n * https://gist.github.com/4336842\n * http://creativecommons.org/publicdomain/mark/1.0/ \n */\n\nusing System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace Encryption\n{\n public static class AESThenHMAC\n {\n private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create();\n\n //Preconfigured Encryption Parameters\n public static readonly int BlockBitSize = 128;\n public static readonly int KeyBitSize = 256;\n\n //Preconfigured Password Key Derivation Parameters\n public static readonly int SaltBitSize = 64;\n public static readonly int Iterations = 10000;\n public static readonly int MinPasswordLength = 12;\n\n /// <summary>\n /// Helper that generates a random key on each call.\n /// </summary>\n /// <returns></returns>\n public static byte[] NewKey()\n {\n var key = new byte[KeyBitSize / 8];\n Random.GetBytes(key);\n return key;\n }\n\n /// <summary>\n /// Simple Encryption (AES) then Authentication (HMAC) for a UTF8 Message.\n /// </summary>\n /// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"cryptKey\">The crypt key.</param>\n /// <param name=\"authKey\">The auth key.</param>\n /// <param name=\"nonSecretPayload\">(Optional) Non-Secret Payload.</param>\n /// <returns>\n /// Encrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Secret Message Required!;secretMessage</exception>\n /// <remarks>\n /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64\n /// </remarks>\n public static string SimpleEncrypt(string secretMessage, byte[] cryptKey, byte[] authKey,\n byte[] nonSecretPayload = null)\n {\n if (string.IsNullOrEmpty(secretMessage))\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var plainText = Encoding.UTF8.GetBytes(secretMessage);\n var cipherText = SimpleEncrypt(plainText, cryptKey, authKey, nonSecretPayload);\n return Convert.ToBase64String(cipherText);\n }\n\n /// <summary>\n /// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message.\n /// </summary>\n /// <param name=\"encryptedMessage\">The encrypted message.</param>\n /// <param name=\"cryptKey\">The crypt key.</param>\n /// <param name=\"authKey\">The auth key.</param>\n /// <param name=\"nonSecretPayloadLength\">Length of the non secret payload.</param>\n /// <returns>\n /// Decrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Encrypted Message Required!;encryptedMessage</exception>\n public static string SimpleDecrypt(string encryptedMessage, byte[] cryptKey, byte[] authKey,\n int nonSecretPayloadLength = 0)\n {\n if (string.IsNullOrWhiteSpace(encryptedMessage))\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cipherText = Convert.FromBase64String(encryptedMessage);\n var plainText = SimpleDecrypt(cipherText, cryptKey, authKey, nonSecretPayloadLength);\n return plainText == null ? null : Encoding.UTF8.GetString(plainText);\n }\n\n /// <summary>\n /// Simple Encryption (AES) then Authentication (HMAC) of a UTF8 message\n /// using Keys derived from a Password (PBKDF2).\n /// </summary>\n /// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"password\">The password.</param>\n /// <param name=\"nonSecretPayload\">The non secret payload.</param>\n /// <returns>\n /// Encrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">password</exception>\n /// <remarks>\n /// Significantly less secure than using random binary keys.\n /// Adds additional non secret payload for key generation parameters.\n /// </remarks>\n public static string SimpleEncryptWithPassword(string secretMessage, string password,\n byte[] nonSecretPayload = null)\n {\n if (string.IsNullOrEmpty(secretMessage))\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var plainText = Encoding.UTF8.GetBytes(secretMessage);\n var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);\n return Convert.ToBase64String(cipherText);\n }\n\n /// <summary>\n /// Simple Authentication (HMAC) and then Descryption (AES) of a UTF8 Message\n /// using keys derived from a password (PBKDF2). \n /// </summary>\n /// <param name=\"encryptedMessage\">The encrypted message.</param>\n /// <param name=\"password\">The password.</param>\n /// <param name=\"nonSecretPayloadLength\">Length of the non secret payload.</param>\n /// <returns>\n /// Decrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Encrypted Message Required!;encryptedMessage</exception>\n /// <remarks>\n /// Significantly less secure than using random binary keys.\n /// </remarks>\n public static string SimpleDecryptWithPassword(string encryptedMessage, string password,\n int nonSecretPayloadLength = 0)\n {\n if (string.IsNullOrWhiteSpace(encryptedMessage))\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cipherText = Convert.FromBase64String(encryptedMessage);\n var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);\n return plainText == null ? null : Encoding.UTF8.GetString(plainText);\n }\n\n public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)\n {\n //User Error Checks\n if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"Key needs to be {0} bit!\", KeyBitSize), \"cryptKey\");\n\n if (authKey == null || authKey.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"Key needs to be {0} bit!\", KeyBitSize), \"authKey\");\n\n if (secretMessage == null || secretMessage.Length < 1)\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n //non-secret payload optional\n nonSecretPayload = nonSecretPayload ?? new byte[] { };\n\n byte[] cipherText;\n byte[] iv;\n\n using (var aes = new AesManaged\n {\n KeySize = KeyBitSize,\n BlockSize = BlockBitSize,\n Mode = CipherMode.CBC,\n Padding = PaddingMode.PKCS7\n })\n {\n\n //Use random IV\n aes.GenerateIV();\n iv = aes.IV;\n\n using (var encrypter = aes.CreateEncryptor(cryptKey, iv))\n using (var cipherStream = new MemoryStream())\n {\n using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))\n using (var binaryWriter = new BinaryWriter(cryptoStream))\n {\n //Encrypt Data\n binaryWriter.Write(secretMessage);\n }\n\n cipherText = cipherStream.ToArray();\n }\n\n }\n\n //Assemble encrypted message and add authentication\n using (var hmac = new HMACSHA256(authKey))\n using (var encryptedStream = new MemoryStream())\n {\n using (var binaryWriter = new BinaryWriter(encryptedStream))\n {\n //Prepend non-secret payload if any\n binaryWriter.Write(nonSecretPayload);\n //Prepend IV\n binaryWriter.Write(iv);\n //Write Ciphertext\n binaryWriter.Write(cipherText);\n binaryWriter.Flush();\n\n //Authenticate all data\n var tag = hmac.ComputeHash(encryptedStream.ToArray());\n //Postpend tag\n binaryWriter.Write(tag);\n }\n return encryptedStream.ToArray();\n }\n\n }\n\n public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)\n {\n\n //Basic Usage Error Checks\n if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"CryptKey needs to be {0} bit!\", KeyBitSize), \"cryptKey\");\n\n if (authKey == null || authKey.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"AuthKey needs to be {0} bit!\", KeyBitSize), \"authKey\");\n\n if (encryptedMessage == null || encryptedMessage.Length == 0)\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n using (var hmac = new HMACSHA256(authKey))\n {\n var sentTag = new byte[hmac.HashSize / 8];\n //Calculate Tag\n var calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);\n var ivLength = (BlockBitSize / 8);\n\n //if message length is to small just return null\n if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)\n return null;\n\n //Grab Sent Tag\n Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);\n\n //Compare Tag with constant time comparison\n var compare = 0;\n for (var i = 0; i < sentTag.Length; i++)\n compare |= sentTag[i] ^ calcTag[i]; \n\n //if message doesn't authenticate return null\n if (compare != 0)\n return null;\n\n using (var aes = new AesManaged\n {\n KeySize = KeyBitSize,\n BlockSize = BlockBitSize,\n Mode = CipherMode.CBC,\n Padding = PaddingMode.PKCS7\n })\n {\n\n //Grab IV from message\n var iv = new byte[ivLength];\n Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);\n\n using (var decrypter = aes.CreateDecryptor(cryptKey, iv))\n using (var plainTextStream = new MemoryStream())\n {\n using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))\n using (var binaryWriter = new BinaryWriter(decrypterStream))\n {\n //Decrypt Cipher Text from Message\n binaryWriter.Write(\n encryptedMessage,\n nonSecretPayloadLength + iv.Length,\n encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length\n );\n }\n //Return Plain Text\n return plainTextStream.ToArray();\n }\n }\n }\n }\n\n public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)\n {\n nonSecretPayload = nonSecretPayload ?? new byte[] {};\n\n //User Error Checks\n if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)\n throw new ArgumentException(String.Format(\"Must have a password of at least {0} characters!\", MinPasswordLength), \"password\");\n\n if (secretMessage == null || secretMessage.Length ==0)\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var payload = new byte[((SaltBitSize / 8) * 2) + nonSecretPayload.Length];\n\n Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);\n int payloadIndex = nonSecretPayload.Length;\n\n byte[] cryptKey;\n byte[] authKey;\n //Use Random Salt to prevent pre-generated weak password attacks.\n using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations))\n {\n var salt = generator.Salt;\n\n //Generate Keys\n cryptKey = generator.GetBytes(KeyBitSize / 8);\n\n //Create Non Secret Payload\n Array.Copy(salt, 0, payload, payloadIndex, salt.Length);\n payloadIndex += salt.Length;\n }\n\n //Deriving separate key, might be less efficient than using HKDF, \n //but now compatible with RNEncryptor which had a very similar wireformat and requires less code than HKDF.\n using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations))\n {\n var salt = generator.Salt;\n\n //Generate Keys\n authKey = generator.GetBytes(KeyBitSize / 8);\n\n //Create Rest of Non Secret Payload\n Array.Copy(salt, 0, payload, payloadIndex, salt.Length);\n }\n\n return SimpleEncrypt(secretMessage, cryptKey, authKey, payload);\n }\n\n public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)\n {\n //User Error Checks\n if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)\n throw new ArgumentException(String.Format(\"Must have a password of at least {0} characters!\", MinPasswordLength), \"password\");\n\n if (encryptedMessage == null || encryptedMessage.Length == 0)\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cryptSalt = new byte[SaltBitSize / 8];\n var authSalt = new byte[SaltBitSize / 8];\n\n //Grab Salt from Non-Secret Payload\n Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length);\n Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length);\n\n byte[] cryptKey;\n byte[] authKey;\n\n //Generate crypt key\n using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations))\n {\n cryptKey = generator.GetBytes(KeyBitSize / 8);\n }\n //Generate auth key\n using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations))\n {\n authKey = generator.GetBytes(KeyBitSize / 8);\n }\n\n return SimpleDecrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength);\n }\n }\n}\n /*\n * This work (Modern Encryption of a String C#, by James Tuley), \n * identified by James Tuley, is free of known copyright restrictions.\n * https://gist.github.com/4336842\n * http://creativecommons.org/publicdomain/mark/1.0/ \n */\n\nusing System;\nusing System.IO;\nusing System.Text;\nusing Org.BouncyCastle.Crypto;\nusing Org.BouncyCastle.Crypto.Engines;\nusing Org.BouncyCastle.Crypto.Generators;\nusing Org.BouncyCastle.Crypto.Modes;\nusing Org.BouncyCastle.Crypto.Parameters;\nusing Org.BouncyCastle.Security;\nnamespace Encryption\n{\n\n public static class AESGCM\n {\n private static readonly SecureRandom Random = new SecureRandom();\n\n //Preconfigured Encryption Parameters\n public static readonly int NonceBitSize = 128;\n public static readonly int MacBitSize = 128;\n public static readonly int KeyBitSize = 256;\n\n //Preconfigured Password Key Derivation Parameters\n public static readonly int SaltBitSize = 128;\n public static readonly int Iterations = 10000;\n public static readonly int MinPasswordLength = 12;\n\n\n /// <summary>\n /// Helper that generates a random new key on each call.\n /// </summary>\n /// <returns></returns>\n public static byte[] NewKey()\n {\n var key = new byte[KeyBitSize / 8];\n Random.NextBytes(key);\n return key;\n }\n\n /// <summary>\n /// Simple Encryption And Authentication (AES-GCM) of a UTF8 string.\n /// </summary>\n /// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"key\">The key.</param>\n /// <param name=\"nonSecretPayload\">Optional non-secret payload.</param>\n /// <returns>\n /// Encrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Secret Message Required!;secretMessage</exception>\n /// <remarks>\n /// Adds overhead of (Optional-Payload + BlockSize(16) + Message + HMac-Tag(16)) * 1.33 Base64\n /// </remarks>\n public static string SimpleEncrypt(string secretMessage, byte[] key, byte[] nonSecretPayload = null)\n {\n if (string.IsNullOrEmpty(secretMessage))\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var plainText = Encoding.UTF8.GetBytes(secretMessage);\n var cipherText = SimpleEncrypt(plainText, key, nonSecretPayload);\n return Convert.ToBase64String(cipherText);\n }\n\n\n /// <summary>\n /// Simple Decryption & Authentication (AES-GCM) of a UTF8 Message\n /// </summary>\n /// <param name=\"encryptedMessage\">The encrypted message.</param>\n /// <param name=\"key\">The key.</param>\n /// <param name=\"nonSecretPayloadLength\">Length of the optional non-secret payload.</param>\n /// <returns>Decrypted Message</returns>\n public static string SimpleDecrypt(string encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)\n {\n if (string.IsNullOrEmpty(encryptedMessage))\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cipherText = Convert.FromBase64String(encryptedMessage);\n var plainText = SimpleDecrypt(cipherText, key, nonSecretPayloadLength);\n return plainText == null ? null : Encoding.UTF8.GetString(plainText);\n }\n\n /// <summary>\n /// Simple Encryption And Authentication (AES-GCM) of a UTF8 String\n /// using key derived from a password (PBKDF2).\n /// </summary>\n /// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"password\">The password.</param>\n /// <param name=\"nonSecretPayload\">The non secret payload.</param>\n /// <returns>\n /// Encrypted Message\n /// </returns>\n /// <remarks>\n /// Significantly less secure than using random binary keys.\n /// Adds additional non secret payload for key generation parameters.\n /// </remarks>\n public static string SimpleEncryptWithPassword(string secretMessage, string password,\n byte[] nonSecretPayload = null)\n {\n if (string.IsNullOrEmpty(secretMessage))\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var plainText = Encoding.UTF8.GetBytes(secretMessage);\n var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);\n return Convert.ToBase64String(cipherText);\n }\n\n\n /// <summary>\n /// Simple Decryption and Authentication (AES-GCM) of a UTF8 message\n /// using a key derived from a password (PBKDF2)\n /// </summary>\n /// <param name=\"encryptedMessage\">The encrypted message.</param>\n /// <param name=\"password\">The password.</param>\n /// <param name=\"nonSecretPayloadLength\">Length of the non secret payload.</param>\n /// <returns>\n /// Decrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Encrypted Message Required!;encryptedMessage</exception>\n /// <remarks>\n /// Significantly less secure than using random binary keys.\n /// </remarks>\n public static string SimpleDecryptWithPassword(string encryptedMessage, string password,\n int nonSecretPayloadLength = 0)\n {\n if (string.IsNullOrWhiteSpace(encryptedMessage))\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cipherText = Convert.FromBase64String(encryptedMessage);\n var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);\n return plainText == null ? null : Encoding.UTF8.GetString(plainText);\n }\n\n public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null)\n {\n //User Error Checks\n if (key == null || key.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"Key needs to be {0} bit!\", KeyBitSize), \"key\");\n\n if (secretMessage == null || secretMessage.Length == 0)\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n //Non-secret Payload Optional\n nonSecretPayload = nonSecretPayload ?? new byte[] { };\n\n //Using random nonce large enough not to repeat\n var nonce = new byte[NonceBitSize / 8];\n Random.NextBytes(nonce, 0, nonce.Length);\n\n var cipher = new GcmBlockCipher(new AesFastEngine());\n var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);\n cipher.Init(true, parameters);\n\n //Generate Cipher Text With Auth Tag\n var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)];\n var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);\n cipher.DoFinal(cipherText, len);\n\n //Assemble Message\n using (var combinedStream = new MemoryStream())\n {\n using (var binaryWriter = new BinaryWriter(combinedStream))\n {\n //Prepend Authenticated Payload\n binaryWriter.Write(nonSecretPayload);\n //Prepend Nonce\n binaryWriter.Write(nonce);\n //Write Cipher Text\n binaryWriter.Write(cipherText);\n }\n return combinedStream.ToArray();\n }\n }\n\n public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)\n {\n //User Error Checks\n if (key == null || key.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"Key needs to be {0} bit!\", KeyBitSize), \"key\");\n\n if (encryptedMessage == null || encryptedMessage.Length == 0)\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n using (var cipherStream = new MemoryStream(encryptedMessage))\n using (var cipherReader = new BinaryReader(cipherStream))\n {\n //Grab Payload\n var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);\n\n //Grab Nonce\n var nonce = cipherReader.ReadBytes(NonceBitSize / 8);\n\n var cipher = new GcmBlockCipher(new AesFastEngine());\n var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);\n cipher.Init(false, parameters);\n\n //Decrypt Cipher Text\n var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);\n var plainText = new byte[cipher.GetOutputSize(cipherText.Length)]; \n\n try\n {\n var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);\n cipher.DoFinal(plainText, len);\n\n }\n catch (InvalidCipherTextException)\n {\n //Return null if it doesn't authenticate\n return null;\n }\n\n return plainText;\n }\n\n }\n\n public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)\n {\n nonSecretPayload = nonSecretPayload ?? new byte[] {};\n\n //User Error Checks\n if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)\n throw new ArgumentException(String.Format(\"Must have a password of at least {0} characters!\", MinPasswordLength), \"password\");\n\n if (secretMessage == null || secretMessage.Length == 0)\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var generator = new Pkcs5S2ParametersGenerator();\n\n //Use Random Salt to minimize pre-generated weak password attacks.\n var salt = new byte[SaltBitSize / 8];\n Random.NextBytes(salt);\n\n generator.Init(\n PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),\n salt,\n Iterations);\n\n //Generate Key\n var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);\n\n //Create Full Non Secret Payload\n var payload = new byte[salt.Length + nonSecretPayload.Length];\n Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);\n Array.Copy(salt,0, payload,nonSecretPayload.Length, salt.Length);\n\n return SimpleEncrypt(secretMessage, key.GetKey(), payload);\n }\n\n public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)\n {\n //User Error Checks\n if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)\n throw new ArgumentException(String.Format(\"Must have a password of at least {0} characters!\", MinPasswordLength), \"password\");\n\n if (encryptedMessage == null || encryptedMessage.Length == 0)\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var generator = new Pkcs5S2ParametersGenerator();\n\n //Grab Salt from Payload\n var salt = new byte[SaltBitSize / 8];\n Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);\n\n generator.Init(\n PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),\n salt,\n Iterations);\n\n //Generate Key\n var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);\n\n return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength);\n }\n }\n}\n" }, { "answer_id": 12122345, "author": "MAXE", "author_id": 833644, "author_profile": "https://Stackoverflow.com/users/833644", "pm_score": -1, "selected": false, "text": "Rfc2898DeriveBytes using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\npublic static class Crypto\n{\n private static readonly byte[] IVa = new byte[] { 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11, 0x11, 0x12, 0x13, 0x14, 0x0e, 0x16, 0x17 };\n\n\n public static string Encrypt(this string text, string salt)\n {\n try\n {\n using (Aes aes = new AesManaged())\n {\n Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));\n aes.Key = deriveBytes.GetBytes(128 / 8);\n aes.IV = aes.Key;\n using (MemoryStream encryptionStream = new MemoryStream())\n {\n using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))\n {\n byte[] cleanText = Encoding.UTF8.GetBytes(text);\n encrypt.Write(cleanText, 0, cleanText.Length);\n encrypt.FlushFinalBlock();\n }\n\n byte[] encryptedData = encryptionStream.ToArray();\n string encryptedText = Convert.ToBase64String(encryptedData);\n\n\n return encryptedText;\n }\n }\n }\n catch\n {\n return String.Empty;\n }\n }\n\n public static string Decrypt(this string text, string salt)\n {\n try\n {\n using (Aes aes = new AesManaged())\n {\n Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));\n aes.Key = deriveBytes.GetBytes(128 / 8);\n aes.IV = aes.Key;\n\n using (MemoryStream decryptionStream = new MemoryStream())\n {\n using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))\n {\n byte[] encryptedData = Convert.FromBase64String(text);\n\n\n decrypt.Write(encryptedData, 0, encryptedData.Length);\n decrypt.Flush();\n }\n\n byte[] decryptedData = decryptionStream.ToArray();\n string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);\n\n\n return decryptedText;\n }\n }\n }\n catch\n {\n return String.Empty;\n }\n }\n }\n}\n" }, { "answer_id": 13511671, "author": "nerdybeardo", "author_id": 1572267, "author_profile": "https://Stackoverflow.com/users/1572267", "pm_score": 6, "selected": false, "text": "using System;\nusing System.Security.Cryptography;\nusing System.Text;\nusing Org.BouncyCastle.Crypto;\nusing Org.BouncyCastle.Crypto.Macs;\nusing Org.BouncyCastle.Crypto.Modes;\nusing Org.BouncyCastle.Crypto.Paddings;\nusing Org.BouncyCastle.Crypto.Parameters;\n\npublic sealed class Encryptor<TBlockCipher, TDigest>\n where TBlockCipher : IBlockCipher, new()\n where TDigest : IDigest, new()\n{\n private Encoding encoding;\n\n private IBlockCipher blockCipher;\n\n private BufferedBlockCipher cipher;\n\n private HMac mac;\n\n private byte[] key;\n\n public Encryptor(Encoding encoding, byte[] key, byte[] macKey)\n {\n this.encoding = encoding;\n this.key = key;\n this.Init(key, macKey, new Pkcs7Padding());\n }\n\n public Encryptor(Encoding encoding, byte[] key, byte[] macKey, IBlockCipherPadding padding)\n {\n this.encoding = encoding;\n this.key = key;\n this.Init(key, macKey, padding);\n }\n\n private void Init(byte[] key, byte[] macKey, IBlockCipherPadding padding)\n {\n this.blockCipher = new CbcBlockCipher(new TBlockCipher());\n this.cipher = new PaddedBufferedBlockCipher(this.blockCipher, padding);\n this.mac = new HMac(new TDigest());\n this.mac.Init(new KeyParameter(macKey));\n }\n\n public string Encrypt(string plain)\n {\n return Convert.ToBase64String(EncryptBytes(plain));\n }\n\n public byte[] EncryptBytes(string plain)\n {\n byte[] input = this.encoding.GetBytes(plain);\n\n var iv = this.GenerateIV();\n\n var cipher = this.BouncyCastleCrypto(true, input, new ParametersWithIV(new KeyParameter(key), iv));\n byte[] message = CombineArrays(iv, cipher);\n\n this.mac.Reset();\n this.mac.BlockUpdate(message, 0, message.Length);\n byte[] digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];\n this.mac.DoFinal(digest, 0);\n\n var result = CombineArrays(digest, message);\n return result;\n }\n\n public byte[] DecryptBytes(byte[] bytes)\n {\n // split the digest into component parts\n var digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];\n var message = new byte[bytes.Length - digest.Length];\n var iv = new byte[this.blockCipher.GetBlockSize()];\n var cipher = new byte[message.Length - iv.Length];\n\n Buffer.BlockCopy(bytes, 0, digest, 0, digest.Length);\n Buffer.BlockCopy(bytes, digest.Length, message, 0, message.Length);\n if (!IsValidHMac(digest, message))\n {\n throw new CryptoException();\n }\n\n Buffer.BlockCopy(message, 0, iv, 0, iv.Length);\n Buffer.BlockCopy(message, iv.Length, cipher, 0, cipher.Length);\n\n byte[] result = this.BouncyCastleCrypto(false, cipher, new ParametersWithIV(new KeyParameter(key), iv));\n return result;\n }\n\n public string Decrypt(byte[] bytes)\n {\n return this.encoding.GetString(DecryptBytes(bytes));\n }\n\n public string Decrypt(string cipher)\n {\n return this.Decrypt(Convert.FromBase64String(cipher));\n }\n\n private bool IsValidHMac(byte[] digest, byte[] message)\n {\n this.mac.Reset();\n this.mac.BlockUpdate(message, 0, message.Length);\n byte[] computed = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];\n this.mac.DoFinal(computed, 0);\n\n return AreEqual(digest,computed);\n }\n\n private static bool AreEqual(byte [] digest, byte[] computed)\n {\n if(digest.Length != computed.Length)\n {\n return false;\n }\n\n int result = 0;\n for (int i = 0; i < digest.Length; i++)\n {\n // compute equality of all bytes before returning.\n // helps prevent timing attacks: \n // https://codahale.com/a-lesson-in-timing-attacks/\n result |= digest[i] ^ computed[i];\n }\n\n return result == 0;\n }\n\n private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, ICipherParameters parameters)\n {\n try\n {\n cipher.Init(forEncrypt, parameters);\n\n return this.cipher.DoFinal(input);\n }\n catch (CryptoException)\n {\n throw;\n }\n }\n\n private byte[] GenerateIV()\n {\n using (var provider = new RNGCryptoServiceProvider())\n {\n // 1st block\n byte[] result = new byte[this.blockCipher.GetBlockSize()];\n provider.GetBytes(result);\n\n return result;\n }\n }\n\n private static byte[] CombineArrays(byte[] source1, byte[] source2)\n {\n byte[] result = new byte[source1.Length + source2.Length];\n Buffer.BlockCopy(source1, 0, result, 0, source1.Length);\n Buffer.BlockCopy(source2, 0, result, source1.Length, source2.Length);\n\n return result;\n }\n}\n var encrypt = new Encryptor<TwofishEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);\n\nstring cipher = encrypt.Encrypt(\"TEST\"); \nstring plainText = encrypt.Decrypt(cipher);\n var des = new Encryptor<DesEdeEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);\n\nstring cipher = des.Encrypt(\"TEST\");\nstring plainText = des.Decrypt(cipher);\n var aes = new Encryptor<AesEngine, Sha256Digest>(Encoding.UTF8, key, hmacKey);\n\ncipher = aes.Encrypt(\"TEST\");\nplainText = aes.Decrypt(cipher);\n" }, { "answer_id": 15407665, "author": "mattmanser", "author_id": 62829, "author_profile": "https://Stackoverflow.com/users/62829", "pm_score": 6, "selected": false, "text": "MachineKey.Protect() MachineKey.Unprotect() MachineKey.Encode() MachineKey.Decode()" }, { "answer_id": 19125021, "author": "Catto", "author_id": 17877, "author_profile": "https://Stackoverflow.com/users/17877", "pm_score": 2, "selected": false, "text": "public class CryptoURL\n{\n private static byte[] _salt = Encoding.ASCII.GetBytes(\"Catto_Salt_Enter_Any_Value99\");\n\n /// <summary>\n /// Encrypt the given string using AES. The string can be decrypted using \n /// DecryptStringAES(). The sharedSecret parameters must match. \n /// The SharedSecret for the Password Reset that is used is in the next line\n /// string sharedSecret = \"OneUpSharedSecret9\";\n /// </summary>\n /// <param name=\"plainText\">The text to encrypt.</param>\n /// <param name=\"sharedSecret\">A password used to generate a key for encryption.</param>\n public static string EncryptString(string plainText, string sharedSecret)\n {\n if (string.IsNullOrEmpty(plainText))\n throw new ArgumentNullException(\"plainText\");\n if (string.IsNullOrEmpty(sharedSecret))\n throw new ArgumentNullException(\"sharedSecret\");\n\n string outStr = null; // Encrypted string to return\n RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.\n\n try\n {\n // generate the key from the shared secret and the salt\n Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);\n\n // Create a RijndaelManaged object\n aesAlg = new RijndaelManaged();\n aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);\n\n // Create a decryptor to perform the stream transform.\n ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);\n\n // Create the streams used for encryption.\n using (MemoryStream msEncrypt = new MemoryStream())\n {\n // prepend the IV\n msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));\n msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n }\n\n outStr = HttpServerUtility.UrlTokenEncode(msEncrypt.ToArray());\n //outStr = Convert.ToBase64String(msEncrypt.ToArray());\n // you may need to add a reference. right click reference in solution explorer => \"add Reference\" => .NET tab => select \"System.Web\"\n }\n }\n finally\n {\n // Clear the RijndaelManaged object.\n if (aesAlg != null)\n aesAlg.Clear();\n }\n\n // Return the encrypted bytes from the memory stream.\n return outStr;\n }\n\n /// <summary>\n /// Decrypt the given string. Assumes the string was encrypted using \n /// EncryptStringAES(), using an identical sharedSecret.\n /// </summary>\n /// <param name=\"cipherText\">The text to decrypt.</param>\n /// <param name=\"sharedSecret\">A password used to generate a key for decryption.</param>\n public static string DecryptString(string cipherText, string sharedSecret)\n {\n if (string.IsNullOrEmpty(cipherText))\n throw new ArgumentNullException(\"cipherText\");\n if (string.IsNullOrEmpty(sharedSecret))\n throw new ArgumentNullException(\"sharedSecret\");\n\n // Declare the RijndaelManaged object\n // used to decrypt the data.\n RijndaelManaged aesAlg = null;\n\n // Declare the string used to hold\n // the decrypted text.\n string plaintext = null;\n\n byte[] inputByteArray;\n\n try\n {\n // generate the key from the shared secret and the salt\n Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);\n\n // Create the streams used for decryption. \n //byte[] bytes = Convert.FromBase64String(cipherText);\n inputByteArray = HttpServerUtility.UrlTokenDecode(cipherText);\n\n using (MemoryStream msDecrypt = new MemoryStream(inputByteArray))\n {\n // Create a RijndaelManaged object\n // with the specified key and IV.\n aesAlg = new RijndaelManaged();\n aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);\n // Get the initialization vector from the encrypted stream\n aesAlg.IV = ReadByteArray(msDecrypt);\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n\n // Read the decrypted bytes from the decrypting stream\n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n catch (System.Exception ex)\n {\n return \"ERROR\";\n //throw ex;\n\n }\n finally\n {\n // Clear the RijndaelManaged object.\n if (aesAlg != null)\n aesAlg.Clear();\n }\n\n return plaintext;\n }\n\n static string ConvertStringArrayToString(string[] array)\n {\n //\n // Concatenate all the elements into a StringBuilder.\n //\n StringBuilder builder = new StringBuilder();\n foreach (string value in array)\n {\n builder.Append(value);\n builder.Append('.');\n }\n return builder.ToString();\n }\n\n private static byte[] ReadByteArray(Stream s)\n {\n byte[] rawLength = new byte[sizeof(int)];\n if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)\n {\n throw new SystemException(\"Stream did not contain properly formatted byte array\");\n }\n\n byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];\n if (s.Read(buffer, 0, buffer.Length) != buffer.Length)\n {\n throw new SystemException(\"Did not read byte array properly\");\n }\n\n return buffer;\n }\n\n}\n" }, { "answer_id": 22934397, "author": "KarthikManoharan", "author_id": 1463105, "author_profile": "https://Stackoverflow.com/users/1463105", "pm_score": -1, "selected": false, "text": " using System;\n using System.Collections.Generic;\n using System.Text;\n using System.Text.RegularExpressions; // This is for password validation\n using System.Security.Cryptography;\n using System.Configuration; // This is where the hash functions reside\n\n namespace BullyTracker.Common\n {\n public class HashEncryption\n {\n //public string GenerateHashvalue(string thisPassword)\n //{\n // MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();\n // byte[] tmpSource;\n // byte[] tmpHash;\n\n // tmpSource = ASCIIEncoding.ASCII.GetBytes(thisPassword); // Turn password into byte array\n // tmpHash = md5.ComputeHash(tmpSource);\n\n // StringBuilder sOutput = new StringBuilder(tmpHash.Length);\n // for (int i = 0; i < tmpHash.Length; i++)\n // {\n // sOutput.Append(tmpHash[i].ToString(\"X2\")); // X2 formats to hexadecimal\n // }\n // return sOutput.ToString();\n //}\n //public Boolean VerifyHashPassword(string thisPassword, string thisHash)\n //{\n // Boolean IsValid = false;\n // string tmpHash = GenerateHashvalue(thisPassword); // Call the routine on user input\n // if (tmpHash == thisHash) IsValid = true; // Compare to previously generated hash\n // return IsValid;\n //}\n public string GenerateHashvalue(string toEncrypt, bool useHashing)\n {\n byte[] keyArray;\n byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);\n\n System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();\n // Get the key from config file\n string key = (string)settingsReader.GetValue(\"SecurityKey\", typeof(String));\n //System.Windows.Forms.MessageBox.Show(key);\n if (useHashing)\n {\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n hashmd5.Clear();\n }\n else\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n\n TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n tdes.Key = keyArray;\n tdes.Mode = CipherMode.ECB;\n tdes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform cTransform = tdes.CreateEncryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);\n tdes.Clear();\n return Convert.ToBase64String(resultArray, 0, resultArray.Length);\n }\n /// <summary>\n /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string\n /// </summary>\n /// <param name=\"cipherString\">encrypted string</param>\n /// <param name=\"useHashing\">Did you use hashing to encrypt this data? pass true is yes</param>\n /// <returns></returns>\n public string Decrypt(string cipherString, bool useHashing)\n {\n byte[] keyArray;\n byte[] toEncryptArray = Convert.FromBase64String(cipherString);\n\n System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();\n //Get your key from config file to open the lock!\n string key = (string)settingsReader.GetValue(\"SecurityKey\", typeof(String));\n\n if (useHashing)\n {\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n hashmd5.Clear();\n }\n else\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n\n TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n tdes.Key = keyArray;\n tdes.Mode = CipherMode.ECB;\n tdes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform cTransform = tdes.CreateDecryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);\n\n tdes.Clear();\n return UTF8Encoding.UTF8.GetString(resultArray);\n }\n\n\n }\n\n }\n" }, { "answer_id": 23245293, "author": "user3556387", "author_id": 3556387, "author_profile": "https://Stackoverflow.com/users/3556387", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Security.Cryptography;\nusing System.IO;\n\n namespace My\n{\n public class strCrypto\n {\n // This constant string is used as a \"salt\" value for the PasswordDeriveBytes function calls.\n // This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256, so the IV must be\n // 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.\n private const string initVector = \"r5dm5fgm24mfhfku\";\n private const string passPhrase = \"yourpassphrase\"; // email password encryption password\n\n // This constant is used to determine the keysize of the encryption algorithm.\n private const int keysize = 256;\n\n public static string encryptString(string plainText)\n {\n //if the plaintext is empty or null string just return an empty string\n if (plainText == \"\" || plainText == null )\n {\n return \"\";\n }\n\n byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);\n byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);\n PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);\n byte[] keyBytes = password.GetBytes(keysize / 8);\n RijndaelManaged symmetricKey = new RijndaelManaged();\n symmetricKey.Mode = CipherMode.CBC;\n ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);\n MemoryStream memoryStream = new MemoryStream();\n CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);\n cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n cryptoStream.FlushFinalBlock();\n byte[] cipherTextBytes = memoryStream.ToArray();\n memoryStream.Close();\n cryptoStream.Close();\n return Convert.ToBase64String(cipherTextBytes);\n }\n\n public static string decryptString(string cipherText)\n {\n //if the ciphertext is empty or null string just return an empty string\n if (cipherText == \"\" || cipherText == null )\n {\n return \"\";\n }\n\n byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);\n byte[] cipherTextBytes = Convert.FromBase64String(cipherText);\n PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);\n byte[] keyBytes = password.GetBytes(keysize / 8);\n RijndaelManaged symmetricKey = new RijndaelManaged();\n symmetricKey.Mode = CipherMode.CBC;\n ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);\n MemoryStream memoryStream = new MemoryStream(cipherTextBytes);\n CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);\n byte[] plainTextBytes = new byte[cipherTextBytes.Length];\n int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n memoryStream.Close();\n cryptoStream.Close();\n return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);\n }\n\n\n}\n" }, { "answer_id": 24401587, "author": "Jim Flood", "author_id": 233596, "author_profile": "https://Stackoverflow.com/users/233596", "pm_score": 2, "selected": false, "text": "private byte[] EncryptBytes(byte[] key, byte[] plaintext)\n{\n using (var cipher = new RijndaelManaged { Key = key })\n {\n using (var encryptor = cipher.CreateEncryptor())\n {\n var ciphertext = encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length);\n\n // IV is prepended to ciphertext\n return cipher.IV.Concat(ciphertext).ToArray();\n }\n }\n}\n\nprivate byte[] DecryptBytes(byte[] key, byte[] packed)\n{\n using (var cipher = new RijndaelManaged { Key = key })\n {\n int ivSize = cipher.BlockSize / 8;\n\n cipher.IV = packed.Take(ivSize).ToArray();\n\n using (var encryptor = cipher.CreateDecryptor())\n {\n return encryptor.TransformFinalBlock(packed, ivSize, packed.Length - ivSize);\n }\n }\n}\n\nprivate byte[] AddMac(byte[] key, byte[] data)\n{\n using (var hmac = new HMACSHA256(key))\n {\n var macBytes = hmac.ComputeHash(data);\n\n // HMAC is appended to data\n return data.Concat(macBytes).ToArray();\n }\n}\n\nprivate bool BadMac(byte[] found, byte[] computed)\n{\n int mismatch = 0;\n\n // Aim for consistent timing regardless of inputs\n for (int i = 0; i < found.Length; i++)\n {\n mismatch += found[i] == computed[i] ? 0 : 1;\n }\n\n return mismatch != 0;\n}\n\nprivate byte[] RemoveMac(byte[] key, byte[] data)\n{\n using (var hmac = new HMACSHA256(key))\n {\n int macSize = hmac.HashSize / 8;\n\n var packed = data.Take(data.Length - macSize).ToArray();\n\n var foundMac = data.Skip(packed.Length).ToArray();\n\n var computedMac = hmac.ComputeHash(packed);\n\n if (this.BadMac(foundMac, computedMac))\n {\n throw new Exception(\"Bad MAC\");\n }\n\n return packed;\n } \n}\n\nprivate List<byte[]> DeriveTwoKeys(string password)\n{\n var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };\n\n var kdf = new Rfc2898DeriveBytes(password, salt, 10000);\n\n var bytes = kdf.GetBytes(32); // Two keys 128 bits each\n\n return new List<byte[]> { bytes.Take(16).ToArray(), bytes.Skip(16).ToArray() };\n}\n\npublic byte[] EncryptString(string password, String message)\n{\n var keys = this.DeriveTwoKeys(password);\n\n var plaintext = Encoding.UTF8.GetBytes(message);\n\n var packed = this.EncryptBytes(keys[0], plaintext);\n\n return this.AddMac(keys[1], packed);\n}\n\npublic String DecryptString(string password, byte[] secret)\n{\n var keys = this.DeriveTwoKeys(password);\n\n var packed = this.RemoveMac(keys[1], secret);\n\n var plaintext = this.DecryptBytes(keys[0], packed);\n\n return Encoding.UTF8.GetString(plaintext);\n}\n\npublic void Example()\n{\n var password = \"correcthorsebatterystaple\";\n\n var secret = this.EncryptString(password, \"Hello World\");\n\n Console.WriteLine(\"secret: \" + BitConverter.ToString(secret));\n\n var recovered = this.DecryptString(password, secret);\n\n Console.WriteLine(recovered);\n}\n" }, { "answer_id": 26518619, "author": "angularsen", "author_id": 134761, "author_profile": "https://Stackoverflow.com/users/134761", "pm_score": 0, "selected": false, "text": "/// <summary>\n/// Simple encryption/decryption using a random initialization vector\n/// and prepending it to the crypto text.\n/// </summary>\n/// <remarks>Based on multiple answers in https://stackoverflow.com/questions/165808/simple-two-way-encryption-for-c-sharp </remarks>\npublic class SimpleAes : IDisposable\n{\n /// <summary>\n /// Initialization vector length in bytes.\n /// </summary>\n private const int IvBytes = 16;\n\n /// <summary>\n /// Must be exactly 16, 24 or 32 characters long.\n /// </summary>\n private static readonly byte[] Key = Convert.FromBase64String(\"FILL ME WITH 16, 24 OR 32 CHARS\");\n\n private readonly UTF8Encoding _encoder;\n private readonly ICryptoTransform _encryptor;\n private readonly RijndaelManaged _rijndael;\n\n public SimpleAes()\n {\n _rijndael = new RijndaelManaged {Key = Key};\n _rijndael.GenerateIV();\n _encryptor = _rijndael.CreateEncryptor();\n _encoder = new UTF8Encoding();\n }\n\n public string Decrypt(string encrypted)\n {\n return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));\n }\n\n public void Dispose()\n {\n _rijndael.Dispose();\n _encryptor.Dispose();\n }\n\n public string Encrypt(string unencrypted)\n {\n return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)));\n }\n\n private byte[] Decrypt(byte[] buffer)\n {\n // IV is prepended to cryptotext\n byte[] iv = buffer.Take(IvBytes).ToArray();\n using (ICryptoTransform decryptor = _rijndael.CreateDecryptor(_rijndael.Key, iv))\n {\n return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes);\n }\n }\n\n private byte[] Encrypt(byte[] buffer)\n {\n // Prepend cryptotext with IV\n byte[] inputBuffer = _rijndael.IV.Concat(buffer).ToArray();\n return _encryptor.TransformFinalBlock(inputBuffer, IvBytes, buffer.Length);\n }\n}\n" }, { "answer_id": 27223411, "author": "Manu Nair", "author_id": 4310461, "author_profile": "https://Stackoverflow.com/users/4310461", "pm_score": -1, "selected": false, "text": "//Encryption\npublic string EncryptText(string toEncrypt, bool useHashing)\n {\n try\n {\n byte[] keyArray;\n byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);\n\n string key = \"String Key Value\"; //Based on this key stirng is encrypting\n //System.Windows.Forms.MessageBox.Show(key);\n //If hashing use get hashcode regards to your key\n if (useHashing)\n {\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n //Always release the resources and flush data\n //of the Cryptographic service provide. Best Practice\n\n hashmd5.Clear();\n }\n else\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n\n TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n //set the secret key for the tripleDES algorithm\n tdes.Key = keyArray;\n //mode of operation. there are other 4 modes. We choose ECB(Electronic code Book)\n tdes.Mode = CipherMode.ECB;\n //padding mode(if any extra byte added)\n tdes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform cTransform = tdes.CreateEncryptor();\n //transform the specified region of bytes array to resultArray\n byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);\n //Release resources held by TripleDes Encryptor\n tdes.Clear();\n //Return the encrypted data into unreadable string format\n return Convert.ToBase64String(resultArray, 0, resultArray.Length);\n }\n catch (Exception e)\n {\n throw e;\n }\n }\n\n //Decryption\n public string DecryptText(string cipherString, bool useHashing)\n {\n\n try\n {\n byte[] keyArray;\n //get the byte code of the string\n\n byte[] toEncryptArray = Convert.FromBase64String(cipherString);\n\n string key = \"String Key Value\"; //Based on this key string is decrypted\n\n if (useHashing)\n {\n //if hashing was used get the hash code with regards to your key\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n //release any resource held by the MD5CryptoServiceProvider\n\n hashmd5.Clear();\n }\n else\n {\n //if hashing was not implemented get the byte code of the key\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n }\n\n TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n //set the secret key for the tripleDES algorithm\n tdes.Key = keyArray;\n //mode of operation. there are other 4 modes.\n //We choose ECB(Electronic code Book)\n\n tdes.Mode = CipherMode.ECB;\n //padding mode(if any extra byte added)\n tdes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform cTransform = tdes.CreateDecryptor();\n byte[] resultArray = cTransform.TransformFinalBlock\n (toEncryptArray, 0, toEncryptArray.Length);\n //Release resources held by TripleDes Encryptor\n tdes.Clear();\n //return the Clear decrypted TEXT\n return UTF8Encoding.UTF8.GetString(resultArray);\n }\n catch (Exception ex)\n {\n throw ex;\n }\n }\n" }, { "answer_id": 27519762, "author": "Vijay Kumbhoje", "author_id": 3583859, "author_profile": "https://Stackoverflow.com/users/3583859", "pm_score": 0, "selected": false, "text": "using System.Text;\nusing System.Security.Cryptography;\nusing System.IO;\n\n\n private string Encrypt(string clearText)\n {\n string EncryptionKey = \"yourkey\";\n byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n cs.Close();\n }\n clearText = Convert.ToBase64String(ms.ToArray());\n }\n }\n return clearText;\n }\n\n private string Decrypt(string cipherText)\n {\n string EncryptionKey = \"yourkey\";\n cipherText = cipherText.Replace(\" \", \"+\");\n byte[] cipherBytes = Convert.FromBase64String(cipherText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n cs.Close();\n }\n cipherText = Encoding.Unicode.GetString(ms.ToArray());\n }\n }\n return cipherText;\n }\n" }, { "answer_id": 28605068, "author": "Gopal Reddy V", "author_id": 4540291, "author_profile": "https://Stackoverflow.com/users/4540291", "pm_score": 4, "selected": false, "text": "public string EncryptString(string inputString)\n{\n MemoryStream memStream = null;\n try\n {\n byte[] key = { };\n byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };\n string encryptKey = \"aXb2uy4z\"; // MUST be 8 characters\n key = Encoding.UTF8.GetBytes(encryptKey);\n byte[] byteInput = Encoding.UTF8.GetBytes(inputString);\n DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n memStream = new MemoryStream();\n ICryptoTransform transform = provider.CreateEncryptor(key, IV);\n CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);\n cryptoStream.Write(byteInput, 0, byteInput.Length);\n cryptoStream.FlushFinalBlock();\n }\n catch (Exception ex)\n {\n Response.Write(ex.Message);\n }\n return Convert.ToBase64String(memStream.ToArray());\n}\n public string DecryptString(string inputString)\n{\n MemoryStream memStream = null;\n try\n {\n byte[] key = { };\n byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };\n string encryptKey = \"aXb2uy4z\"; // MUST be 8 characters\n key = Encoding.UTF8.GetBytes(encryptKey);\n byte[] byteInput = new byte[inputString.Length];\n byteInput = Convert.FromBase64String(inputString);\n DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n memStream = new MemoryStream();\n ICryptoTransform transform = provider.CreateDecryptor(key, IV);\n CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);\n cryptoStream.Write(byteInput, 0, byteInput.Length);\n cryptoStream.FlushFinalBlock();\n }\n catch (Exception ex)\n {\n Response.Write(ex.Message);\n }\n\n Encoding encoding1 = Encoding.UTF8;\n return encoding1.GetString(memStream.ToArray());\n}\n" }, { "answer_id": 30438370, "author": "Gil Cohen", "author_id": 2464918, "author_profile": "https://Stackoverflow.com/users/2464918", "pm_score": 5, "selected": false, "text": "public static string Encrypt(string clearText)\n{ \n byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);\n using (Aes encryptor = Aes.Create())\n {\n byte[] IV = new byte[15];\n rand.NextBytes(IV);\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n cs.Close();\n }\n clearText = Convert.ToBase64String(IV) + Convert.ToBase64String(ms.ToArray());\n }\n }\n return clearText;\n}\n public static string Decrypt(string cipherText)\n{\n byte[] IV = Convert.FromBase64String(cipherText.Substring(0, 20));\n cipherText = cipherText.Substring(20).Replace(\" \", \"+\");\n byte[] cipherBytes = Convert.FromBase64String(cipherText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n cs.Close();\n }\n cipherText = Encoding.Unicode.GetString(ms.ToArray());\n }\n }\n return cipherText;\n}\n protected static string _Key = \"\";\nprotected static string EncryptionKey\n{\n get\n {\n if (String.IsNullOrEmpty(_Key))\n {\n _Key = ConfigurationManager.AppSettings[\"AESKey\"].ToString();\n }\n\n return _Key;\n }\n}\n" }, { "answer_id": 37429667, "author": "Skull", "author_id": 5244641, "author_profile": "https://Stackoverflow.com/users/5244641", "pm_score": 0, "selected": false, "text": "public static class CryptographyProvider\n {\n public static string EncryptString(string plainText, out string Key)\n {\n if (plainText == null || plainText.Length <= 0)\n throw new ArgumentNullException(\"plainText\");\n\n using (Aes _aesAlg = Aes.Create())\n {\n Key = Convert.ToBase64String(_aesAlg.Key);\n ICryptoTransform _encryptor = _aesAlg.CreateEncryptor(_aesAlg.Key, _aesAlg.IV);\n\n using (MemoryStream _memoryStream = new MemoryStream())\n {\n _memoryStream.Write(_aesAlg.IV, 0, 16);\n using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter _streamWriter = new StreamWriter(_cryptoStream))\n {\n _streamWriter.Write(plainText);\n }\n return Convert.ToBase64String(_memoryStream.ToArray());\n }\n }\n }\n }\n public static string DecryptString(string cipherText, string Key)\n {\n\n if (string.IsNullOrEmpty(cipherText))\n throw new ArgumentNullException(\"cipherText\");\n if (string.IsNullOrEmpty(Key))\n throw new ArgumentNullException(\"Key\");\n\n string plaintext = null;\n\n byte[] _initialVector = new byte[16];\n byte[] _Key = Convert.FromBase64String(Key);\n byte[] _cipherTextBytesArray = Convert.FromBase64String(cipherText);\n byte[] _originalString = new byte[_cipherTextBytesArray.Length - 16];\n\n Array.Copy(_cipherTextBytesArray, 0, _initialVector, 0, _initialVector.Length);\n Array.Copy(_cipherTextBytesArray, 16, _originalString, 0, _cipherTextBytesArray.Length - 16);\n\n using (Aes _aesAlg = Aes.Create())\n {\n _aesAlg.Key = _Key;\n _aesAlg.IV = _initialVector;\n ICryptoTransform decryptor = _aesAlg.CreateDecryptor(_aesAlg.Key, _aesAlg.IV);\n\n using (MemoryStream _memoryStream = new MemoryStream(_originalString))\n {\n using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader _streamReader = new StreamReader(_cryptoStream))\n {\n plaintext = _streamReader.ReadToEnd();\n }\n }\n }\n }\n return plaintext;\n }\n }\n" }, { "answer_id": 39034489, "author": "josedbaez", "author_id": 991459, "author_profile": "https://Stackoverflow.com/users/991459", "pm_score": 2, "selected": false, "text": " private static readonly UTF8Encoding Encoder = new UTF8Encoding();\n\n public static string Encrypt(string unencrypted)\n {\n if (string.IsNullOrEmpty(unencrypted)) \n return string.Empty;\n\n try\n {\n var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));\n\n if (encryptedBytes != null && encryptedBytes.Length > 0)\n return HttpServerUtility.UrlTokenEncode(encryptedBytes); \n }\n catch (Exception)\n {\n return string.Empty;\n }\n\n return string.Empty;\n }\n\n public static string Decrypt(string encrypted)\n {\n if (string.IsNullOrEmpty(encrypted)) \n return string.Empty;\n\n try\n {\n var bytes = HttpServerUtility.UrlTokenDecode(encrypted);\n if (bytes != null && bytes.Length > 0)\n {\n var decryptedBytes = MachineKey.Unprotect(bytes);\n if(decryptedBytes != null && decryptedBytes.Length > 0)\n return Encoder.GetString(decryptedBytes);\n }\n\n }\n catch (Exception)\n {\n return string.Empty;\n }\n\n return string.Empty;\n }\n" }, { "answer_id": 40258330, "author": "Ashkan S", "author_id": 6519111, "author_profile": "https://Stackoverflow.com/users/6519111", "pm_score": 2, "selected": false, "text": "<MessageEncryption>\n <EncryptionKey KeySize=\"256\" Key=\"3q2+796tvu/erb7v3q2+796tvu/erb7v3q2+796tvu8=\"/>\n</MessageEncryption>\n" }, { "answer_id": 42043869, "author": "Rahul Modi", "author_id": 5669379, "author_profile": "https://Stackoverflow.com/users/5669379", "pm_score": 3, "selected": false, "text": "static readonly string PasswordHash = \"P@@Sw0rd\";\nstatic readonly string SaltKey = \"S@LT&KEY\";\nstatic readonly string VIKey = \"@1B2c3D4e5F6g7H8\";\n public static string Encrypt(string plainText)\n{\n byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);\n\n byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);\n var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };\n var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));\n\n byte[] cipherTextBytes;\n\n using (var memoryStream = new MemoryStream())\n {\n using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))\n {\n cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n cryptoStream.FlushFinalBlock();\n cipherTextBytes = memoryStream.ToArray();\n cryptoStream.Close();\n }\n memoryStream.Close();\n }\n return Convert.ToBase64String(cipherTextBytes);\n}\n public static string Decrypt(string encryptedText)\n{\n byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);\n byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);\n var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };\n\n var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));\n var memoryStream = new MemoryStream(cipherTextBytes);\n var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);\n byte[] plainTextBytes = new byte[cipherTextBytes.Length];\n\n int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n memoryStream.Close();\n cryptoStream.Close();\n return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd(\"\\0\".ToCharArray());\n}\n" }, { "answer_id": 52748781, "author": "Davit Tvildiani", "author_id": 715224, "author_profile": "https://Stackoverflow.com/users/715224", "pm_score": 2, "selected": false, "text": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\npublic class Program\n{\n public static void Main()\n {\n var key = Encoding.UTF8.GetBytes(\"SUkbqO2ycDo7QwpR25kfgmC7f8CoyrZy\");\n var data = Encoding.UTF8.GetBytes(\"testData\");\n\n //Encrypt data\n var encrypted = CryptoHelper.EncryptData(data,key);\n\n //Decrypt data\n var decrypted = CryptoHelper.DecryptData(encrypted,key);\n\n //Display result\n Console.WriteLine(Encoding.UTF8.GetString(decrypted));\n }\n}\n\npublic static class CryptoHelper\n{\n public static byte[] EncryptData(byte[] data, byte[] key)\n {\n using (var aesAlg = Aes.Create())\n {\n aesAlg.Mode = CipherMode.CBC;\n using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))\n {\n using (var msEncrypt = new MemoryStream())\n {\n msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);\n\n using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n csEncrypt.Write(data, 0, data.Length);\n\n return msEncrypt.ToArray();\n }\n }\n }\n\n }\n\n public static byte[] DecryptData(byte[] encrypted, byte[] key)\n {\n var iv = new byte[16];\n Buffer.BlockCopy(encrypted, 0, iv, 0, iv.Length);\n using (var aesAlg = Aes.Create())\n {\n aesAlg.Mode = CipherMode.CBC;\n using (var decryptor = aesAlg.CreateDecryptor(key, iv))\n {\n using (var msDecrypt = new MemoryStream(encrypted, iv.Length, encrypted.Length - iv.Length))\n {\n using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (var resultStream = new MemoryStream())\n {\n csDecrypt.CopyTo(resultStream);\n return resultStream.ToArray();\n }\n }\n }\n }\n }\n }\n}\n" }, { "answer_id": 52754623, "author": "oleksa", "author_id": 940182, "author_profile": "https://Stackoverflow.com/users/940182", "pm_score": 0, "selected": false, "text": "crypto/aes const (\n gcmBlockSize = 16 // this is key size\n gcmTagSize = 16 // this is mac\n gcmStandardNonceSize = 12 // this is nonce\n)\n\nfunc encrypt(data []byte, passphrase string) []byte {\n block, _ := aes.NewCipher([]byte(createHash(passphrase)))\n gcm, err := cipher.NewGCM(block)\n if err != nil {\n panic(err.Error())\n }\n nonce := make([]byte, gcm.NonceSize())\n if _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n panic(err.Error())\n }\n ciphertext := gcm.Seal(nonce, nonce, data, nil)\n return ciphertext\n}\n" }, { "answer_id": 56023792, "author": "Kolappan N", "author_id": 5407188, "author_profile": "https://Stackoverflow.com/users/5407188", "pm_score": 2, "selected": false, "text": "public class EncryptionHelper\n{\n private Aes aesEncryptor;\n\n public EncryptionHelper()\n {\n }\n\n private void BuildAesEncryptor(string key)\n {\n aesEncryptor = Aes.Create();\n var pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n aesEncryptor.Key = pdb.GetBytes(32);\n aesEncryptor.IV = pdb.GetBytes(16);\n }\n\n public string EncryptString(string clearText, string key)\n {\n BuildAesEncryptor(key);\n var clearBytes = Encoding.Unicode.GetBytes(clearText);\n using (var ms = new MemoryStream())\n {\n using (var cs = new CryptoStream(ms, aesEncryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n }\n var encryptedText = Convert.ToBase64String(ms.ToArray());\n return encryptedText;\n }\n }\n\n public string DecryptString(string cipherText, string key)\n {\n BuildAesEncryptor(key);\n cipherText = cipherText.Replace(\" \", \"+\");\n var cipherBytes = Convert.FromBase64String(cipherText);\n using (var ms = new MemoryStream())\n {\n using (var cs = new CryptoStream(ms, aesEncryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n }\n var clearText = Encoding.Unicode.GetString(ms.ToArray());\n return clearText;\n }\n }\n}\n" }, { "answer_id": 56185068, "author": "reza.Nikmaram", "author_id": 1369854, "author_profile": "https://Stackoverflow.com/users/1369854", "pm_score": 3, "selected": false, "text": " // This constant is used to determine the keysize of the encryption algorithm in bits.\n // We divide this by 8 within the code below to get the equivalent number of bytes.\n private const int Keysize = 128;\n\n // This constant determines the number of iterations for the password bytes generation function.\n private const int DerivationIterations = 1000;\n\n public static string Encrypt(string plainText, string passPhrase)\n {\n // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text\n // so that the same Salt and IV values can be used when decrypting. \n var saltStringBytes = GenerateBitsOfRandomEntropy(16);\n var ivStringBytes = GenerateBitsOfRandomEntropy(16);\n var plainTextBytes = Encoding.UTF8.GetBytes(plainText);\n using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))\n {\n var keyBytes = password.GetBytes(Keysize / 8);\n using (var symmetricKey = new RijndaelManaged())\n {\n symmetricKey.BlockSize = 128;\n symmetricKey.Mode = CipherMode.CBC;\n symmetricKey.Padding = PaddingMode.PKCS7;\n using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))\n {\n using (var memoryStream = new MemoryStream())\n {\n using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))\n {\n cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n cryptoStream.FlushFinalBlock();\n // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.\n var cipherTextBytes = saltStringBytes;\n cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();\n cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();\n memoryStream.Close();\n cryptoStream.Close();\n return Convert.ToBase64String(cipherTextBytes);\n }\n }\n }\n }\n }\n }\n\n public static string Decrypt(string cipherText, string passPhrase)\n {\n // Get the complete stream of bytes that represent:\n // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]\n var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);\n // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.\n var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();\n // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.\n var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();\n // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.\n var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();\n\n using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))\n {\n var keyBytes = password.GetBytes(Keysize / 8);\n using (var symmetricKey = new RijndaelManaged())\n {\n symmetricKey.BlockSize = 128;\n symmetricKey.Mode = CipherMode.CBC;\n symmetricKey.Padding = PaddingMode.PKCS7;\n using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))\n {\n using (var memoryStream = new MemoryStream(cipherTextBytes))\n {\n using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))\n {\n var plainTextBytes = new byte[cipherTextBytes.Length];\n var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n memoryStream.Close();\n cryptoStream.Close();\n return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);\n }\n }\n }\n }\n }\n }\n\n private static byte[] GenerateBitsOfRandomEntropy(int size)\n {\n // 32 Bytes will give us 256 bits.\n // 16 Bytes will give us 128 bits.\n var randomBytes = new byte[size]; \n using (var rngCsp = new RNGCryptoServiceProvider())\n {\n // Fill the array with cryptographically secure random bytes.\n rngCsp.GetBytes(randomBytes);\n }\n return randomBytes;\n }\n" }, { "answer_id": 56424902, "author": "Code", "author_id": 9787173, "author_profile": "https://Stackoverflow.com/users/9787173", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Security.Cryptography;\nusing System.IO;\nusing System.Text; \n\n/// <summary>\n/// Summary description for Encryption\n/// </summary>\npublic class Encryption\n{\n public TripleDES CreateDES(string key)\n {\n MD5 md5 = new MD5CryptoServiceProvider();\n TripleDES des = new TripleDESCryptoServiceProvider();\n des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));\n des.IV = new byte[des.BlockSize / 8];\n return des;\n }\n public byte[] Encryptiondata(string PlainText)\n {\n TripleDES des = CreateDES(\"DreamMLMKey\");\n ICryptoTransform ct = des.CreateEncryptor();\n byte[] input = Encoding.Unicode.GetBytes(PlainText);\n return ct.TransformFinalBlock(input, 0, input.Length);\n }\n\n public string Decryptiondata(string CypherText)\n {\n string stringToDecrypt = CypherText.Replace(\" \", \"+\");\n int len = stringToDecrypt.Length;\n byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); \n\n byte[] b = Convert.FromBase64String(CypherText);\n TripleDES des = CreateDES(\"DreamMLMKey\");\n ICryptoTransform ct = des.CreateDecryptor();\n byte[] output = ct.TransformFinalBlock(b, 0, b.Length);\n return Encoding.Unicode.GetString(output);\n }\n public string Decryptiondataurl(string CypherText)\n {\n string newcyperttext=CypherText.Replace(' ', '+');\n byte[] b = Convert.FromBase64String(newcyperttext);\n TripleDES des = CreateDES(\"DreamMLMKey\");\n ICryptoTransform ct = des.CreateDecryptor();\n byte[] output = ct.TransformFinalBlock(b, 0, b.Length);\n return Encoding.Unicode.GetString(output);\n }\n\n\n #region encryption & Decription\n public string Encrypt(string input, string key)\n {\n byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);\n TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();\n tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);\n tripleDES.Mode = CipherMode.ECB;\n tripleDES.Padding = PaddingMode.PKCS7;\n ICryptoTransform cTransform = tripleDES.CreateEncryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);\n tripleDES.Clear();\n return Convert.ToBase64String(resultArray, 0, resultArray.Length);\n }\n public string Decrypt(string input, string key)\n {\n byte[] inputArray = Convert.FromBase64String(input);\n TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();\n tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);\n tripleDES.Mode = CipherMode.ECB;\n tripleDES.Padding = PaddingMode.PKCS7;\n ICryptoTransform cTransform = tripleDES.CreateDecryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);\n tripleDES.Clear();\n return UTF8Encoding.UTF8.GetString(resultArray);\n }\n\n public string encrypt(string encryptString)\n {\n string EncryptionKey = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {\n 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76\n });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n cs.Close();\n }\n encryptString = Convert.ToBase64String(ms.ToArray());\n }\n }\n return encryptString;\n }\n\n public string Decrypt(string cipherText)\n {\n string EncryptionKey = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n cipherText = cipherText.Replace(\" \", \"+\");\n byte[] cipherBytes = Convert.FromBase64String(cipherText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {\n 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76\n });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n cs.Close();\n }\n cipherText = Encoding.Unicode.GetString(ms.ToArray());\n }\n }\n return cipherText;\n }\n\n #endregion\n}\n" }, { "answer_id": 58418522, "author": "Wieslaw Olborski", "author_id": 3098913, "author_profile": "https://Stackoverflow.com/users/3098913", "pm_score": 2, "selected": false, "text": "using (PGP pgp = new PGP())\n{\n// Generate keys\npgp.GenerateKey(@\"C:\\TEMP\\keys\\public.asc\", @\"C:\\TEMP\\keys\\private.asc\", \"email@email.com\", \"password\");\n// Encrypt file\npgp.EncryptFile(@\"C:\\TEMP\\keys\\content.txt\", @\"C:\\TEMP\\keys\\content__encrypted.pgp\", @\"C:\\TEMP\\keys\\public.asc\", true, true);\n// Encrypt and sign file\npgp.EncryptFileAndSign(@\"C:\\TEMP\\keys\\content.txt\", @\"C:\\TEMP\\keys\\content__encrypted_signed.pgp\", @\"C:\\TEMP\\keys\\public.asc\", @\"C:\\TEMP\\keys\\private.asc\", \"password\", true, true);\n// Decrypt file\npgp.DecryptFile(@\"C:\\TEMP\\keys\\content__encrypted.pgp\", @\"C:\\TEMP\\keys\\content__decrypted.txt\", @\"C:\\TEMP\\keys\\private.asc\", \"password\");\n// Decrypt signed file\npgp.DecryptFile(@\"C:\\TEMP\\keys\\content__encrypted_signed.pgp\", @\"C:\\TEMP\\keys\\content__decrypted_signed.txt\", @\"C:\\TEMP\\keys\\private.asc\", \"password\");\n\n// Encrypt stream\nusing (FileStream inputFileStream = new FileStream(@\"C:\\TEMP\\keys\\content.txt\", FileMode.Open))\nusing (Stream outputFileStream = File.Create(@\"C:\\TEMP\\keys\\content__encrypted2.pgp\"))\nusing (Stream publicKeyStream = new FileStream(@\"C:\\TEMP\\keys\\public.asc\", FileMode.Open))\n pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);\n\n// Decrypt stream\nusing (FileStream inputFileStream = new FileStream(@\"C:\\TEMP\\keys\\content__encrypted2.pgp\", FileMode.Open))\nusing (Stream outputFileStream = File.Create(@\"C:\\TEMP\\keys\\content__decrypted2.txt\"))\nusing (Stream privateKeyStream = new FileStream(@\"C:\\TEMP\\keys\\private.asc\", FileMode.Open))\n pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, \"password\");\n}\n" }, { "answer_id": 62546530, "author": "Mike Bruno", "author_id": 4664256, "author_profile": "https://Stackoverflow.com/users/4664256", "pm_score": 0, "selected": false, "text": ">x509crypto.exe\nX509Crypto> makecert -context user -keysize medium -alias myvault\n\nCertificate with thumbprint B31FE7E7AE5229F8186782742CF579197FA859FD was added to X509Alias \"myvault\" in the user X509Context\n\nX509Crypto>\n X509Crypto> encrypt -text -alias myvault -context user -secret apikey -in \"80EAF03248965AC2B78090\"\n\nSecret apikey has been added to X509Alias myvault in the user X509Context\n\nX509Crypto>\n using Org.X509Crypto;\n\nnamespace SampleApp\n{\n class Program\n {\n static void Main(string[] args)\n {\n var Alias = new X509Alias(@\"myvault\", X509Context.UserReadOnly);\n var apiKey = Alias.RecoverSecret(@\"apikey\");\n }\n }\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291/" ]
202,013
<p>The Winform application is release with ClickOnce in our Intranet. We store personal preference for the GUI in the Isolated Storage. All works pretty fine :)</p> <p>The problem is when we have a new version of the application, we publish... all preferences are lost! User need to setup their preference over and over each version.</p> <p>Is there a way to freeze the isolation for the whole application instead of the version?</p>
[ { "answer_id": 227218, "author": "codeConcussion", "author_id": 1321, "author_profile": "https://Stackoverflow.com/users/1321", "pm_score": 5, "selected": true, "text": "using System.IO;\nusing System.IO.IsolatedStorage;\n...\n\nIsolatedStorageFile appScope = IsolatedStorageFile.GetUserStoreForApplication(); \nusing(IsolatedStorageFileStream fs = new IsolatedStorageFileStream(\"data.dat\", FileMode.OpenOrCreate, appScope))\n{\n...\n" }, { "answer_id": 47694201, "author": "Florjon", "author_id": 86653, "author_profile": "https://Stackoverflow.com/users/86653", "pm_score": 2, "selected": false, "text": "IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();//for visual studio\nif (System.Deployment.Application.ApplicationDeployment.IsNetwor‌​kDeployed)\n{\n isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();//for click once applications\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
202,031
<p>It's possible, but is it appropriate to use SHFileOperation within a Windows service? All those SHxxx API functions in shell32.dll seem to have been written with user level programs in mind. Can I be certain SHFileOperation won't display GUI ever?</p>
[ { "answer_id": 202519, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": false, "text": "FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR\n FOF_NO_UI ShellAPI.h FOF_NO_UI SHFileOperation" }, { "answer_id": 13196069, "author": "Davide Piras", "author_id": 559144, "author_profile": "https://Stackoverflow.com/users/559144", "pm_score": 0, "selected": false, "text": "SHFileOperation ROBOCOPY" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24898/" ]
202,060
<p>I have a page where search resuts are shown both in a grid and on a map (using KML generated on the fly, overlaid on an embedded Google map). I've wired this up to work as the user types; here's the skeleton of my code, which works:</p> <pre><code>$(function() { // Wire up search textbox $('input.Search').bind("keyup", update); }); update = function(e) { // Get text from search box // Pass to web method and bind to concessions grid $.ajax({ ... success: function(msg) { displayResults(msg, filterParams); }, }); } displayResults = function(msg, filterParams) { // Databind results grid using jTemplates // Show results on map: Pass parameters to KML generator and overlay on map } </code></pre> <p>Depending on the search, there may be hundreds of results; and so the work that happens in <code>displayResults</code> is processor-intensive both on the server (querying the database, building and simplifying the KML on the fly) and on the client (databinding the results grid, overlaying big KML files on the map). </p> <p>I like the immediacy of getting progressively narrower results as I type, but I'd like to minimize the number of times this refreshes. What's the simplest way to introduce an N-second delay after the user stops typing, before running the <code>update</code> function?</p>
[ { "answer_id": 202077, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 0, "selected": false, "text": "$('input.Search').bind(\"keyup\", function() { setTimeout(update, 5) } );\n" }, { "answer_id": 202093, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 3, "selected": true, "text": "update() $('input.Search').bind(\"keyup\", delayedUpdate);\n\nfunction delayedUpdate() {\n if (updatePending) {\n clearTimeout(updatePending);\n }\n\n updatePending = setTimeout(update, 250);\n}\n\nfunction update() {\n updatePending = false;\n\n //$.ajax(...\n}\n $('input.Search').bind(\"blur\", update);\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
202,067
<p>Is there a way to get an ASP.NET textbox to accept only currency values, and when the control is validated, insert a $ sign beforehand?</p> <p>Examples: </p> <p>10.23 becomes $10.23<br> $1.45 stays $1.45<br> 10.a raises error due to not being a valid number </p> <p>I have a RegularExpressionValidator that is verifying the number is valid, but I don't know how to force the $ sign into the text. I suspect JavaScript might work, but was wondering if there was another way to do this.</p>
[ { "answer_id": 202128, "author": "Anjisan", "author_id": 25304, "author_profile": "https://Stackoverflow.com/users/25304", "pm_score": 0, "selected": false, "text": "string value = text_box_to_validate.Text;\n\nstring myPattern = @\"^\\$(\\d{1,3},?(\\d{3},?)*\\d{3}(\\.\\d{0,2})|\\d{1,3}(\\.\\d{2})|\\.\\d{2})$\";\nRegex r = new Regex(myPattern);\nMatch m = r.Match(value);\n\nif (m.Success)\n{\n //do something -- everything passed\n}\nelse\n{\n //did not match\n //could check if number is good, but is just missing $ in front\n}\n" }, { "answer_id": 258321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "string sValue = Convert.ToString(txtboxValue.Text.Trim());\n// Put Code to check whether the $ sign already exist or not.\n//Try making a function returning boolean\n//if Dollar sign not available do this\n{ string LableText = string.Format(\"{0:c}\", \"sValue\"); }\nelse\n{ string LableText = Convert.ToString(sValue); }\n" }, { "answer_id": 1968161, "author": "andrew0081", "author_id": 239415, "author_profile": "https://Stackoverflow.com/users/239415", "pm_score": 2, "selected": false, "text": "decimal sValue = decimal.Parse(txtboxValue.Text.Trim());\n// Put Code to check whether the $ sign already exist or not.\n//Try making a function returning boolean\n//if Dollar sign not available do this\n{ string LableText = string.Format(\"{0:c}\", sValue); }\nelse\n{ string LableText = Convert.ToString(sValue); }\n" }, { "answer_id": 1969583, "author": "Jim Schubert", "author_id": 151445, "author_profile": "https://Stackoverflow.com/users/151445", "pm_score": 3, "selected": false, "text": "// directive\nusing System.Globalization;\n\n// code\ndecimal input = -1;\nif (decimal.TryParse(txtUserInput.Text, NumberStyles.Currency, \n CultureInfo.InvariantCulture, out input))\n{\n parameter = input.ToString();\n}\n decimalValue.ToString(\"{0:c}\") $0.00 decimal input = -1 decimal input = 0" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
202,068
<p>I'm looking at setting up a small company that hosts flash-based websites for artist portfolios. The customer control panel would be django-powered, and would provide the interface for uploading their images, managing galleries, selling prints, etc.</p> <p>Seeing as the majority of traffic to the hosted sites would end up at their top level domain, this would result in only static media hits (the HTML page with the embedded flash movie), I could set up lighttpd or nginx to handle those requests, and pass the django stuff back to apache/mod_whatever.</p> <p>Seems as if I could set this all up on one box, with the django sites framework keeping each site's admin separate.</p> <p>I'm not much of a server admin. Are there any gotchas I'm not seeing?</p>
[ { "answer_id": 220711, "author": "Justin Voss", "author_id": 5616, "author_profile": "https://Stackoverflow.com/users/5616", "pm_score": 2, "selected": false, "text": "sites" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3912/" ]
202,073
<p>I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display:</p> <pre><code>Display(BasePage page) { ResourceManager manager = new ResourceManager(page.GetType()); } </code></pre> <p>In my project structure I have a default resource file and a psuedo-translation resource file. If I set try something like this:</p> <pre><code>Display(BasePage page) { ResourceManager manager = new ResourceManager(typeof(Login)); } </code></pre> <p>it returns the translated page. After some research I found that page.GetType().ToString() returned something to the effect of "ASP_login.aspx" How can I get the actual code behind class type, such that I get an object of type "Login" that is derived from "BasePage"? </p> <p>Thanks in advance!</p>
[ { "answer_id": 202099, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "public partial class _Login : BasePage \n { /* ... */ \n }\n Type typeof(_Login) Type GetCodeBehindType()\n { return getCodeBehindTypeRecursive(this.GetType());\n }\n\nType getCodeBehindTypeRecursive(Type t)\n { var baseType = t.BaseType;\n if (baseType == typeof(BasePage)) return t;\n else return getCodeBehindTypeRecursive(baseType);\n }\n" }, { "answer_id": 202228, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 1, "selected": false, "text": "...\nPage\nBasePage\nLogin\nASP_Login\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ]
202,084
<p>Cells in DataGridViewComboBoxColumn have ComboBoxStyle DropDownList. It means the user can only select values from the dropdown. The underlying control is ComboBox, so it can have style DropDown. How do I change the style of the underlying combo box in DataGridViewComboBoxColumn. Or, more general, can I have a column in DataGridView with dropdown where user can type?</p>
[ { "answer_id": 202478, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 3, "selected": false, "text": "void dataGridView1_EditingControlShowing(object sender, \n DataGridViewEditingControlShowingEventArgs e)\n{\n if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))\n {\n DataGridViewComboBoxEditingControl cbo = \n e.Control as DataGridViewComboBoxEditingControl;\n cbo.DropDownStyle = ComboBoxStyle.DropDown;\n }\n}\n" }, { "answer_id": 203491, "author": "chgman", "author_id": 14727, "author_profile": "https://Stackoverflow.com/users/14727", "pm_score": 2, "selected": false, "text": "private void dataGridView1_CellValidating(object sender, \n DataGridViewCellValidatingEventArgs e) \n{\n if (e.ColumnIndex == Column1.Index) \n {\n // Add the value to column's Items to pass validation\n if (!Column1.Items.Contains(e.FormattedValue.ToString())) \n {\n Column1.Items.Add(e.FormattedValue);\n dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = \n e.FormattedValue;\n }\n }\n}\n\nprivate void dataGridView1_EditingControlShowing(object sender, \n DataGridViewEditingControlShowingEventArgs e) \n{\n if (dataGridView1.CurrentCell.ColumnIndex == Column1.Index) \n {\n ComboBox cb = (ComboBox)e.Control;\n if (cb != null) \n {\n cb.Items.Clear();\n // Customize content of the dropdown list\n cb.Items.AddRange(appropriateCollectionOfStrings);\n cb.DropDownStyle = ComboBoxStyle.DropDown;\n }\n }\n}\n" }, { "answer_id": 6867121, "author": "Jamie Pate", "author_id": 193232, "author_profile": "https://Stackoverflow.com/users/193232", "pm_score": 1, "selected": false, "text": "if (!Column1.Items.Contains(e.FormattedValue.ToString())) { \n Column1.Items.Add(e.FormattedValue); \n dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue; \n} \n Column1.Items.Contains() String e.FormattedValue String if (!Column1.Items.Contains(e.FormattedValue.ToString())) { \n Column1.Items.Add(e.FormattedValue.ToString()); \n dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue.ToString(); \n}\n if (!Column1.Items.Contains(e.FormattedValue)) { \n Column1.Items.Add(e.FormattedValue); \n dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue; \n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14727/" ]
202,107
<p>This question is to seek out good examples of Hungarian Notation, so we can bring together a collection of these. </p> <p><strong>Edit:</strong> I agree that Hungarian for types isn't that necessary, I'm hoping for more specific examples where it increases readability and maintainability, like Joel gives in his article (as per my answer).</p>
[ { "answer_id": 202135, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": false, "text": "ix _" }, { "answer_id": 202179, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 1, "selected": false, "text": "MyClass myClass;\nMyClass* pMyClass;\n class\n{\nprivate:\nbool m_myVar;\n}\n" }, { "answer_id": 328508, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "dxHighlight = xStart - xEnd yHighlight = yLocation + 3 yEnd = yStart + dyHeight dyCode = dyField * 2 yTop = dyText + xButton" }, { "answer_id": 918582, "author": "Stobor", "author_id": 43452, "author_profile": "https://Stackoverflow.com/users/43452", "pm_score": 2, "selected": false, "text": "myStart = GetTime();\ndoComplicatedOperations();\nprint (GetTime() - myStart);\n tmpX = X; \ntmpY = Y;\nX = someCalc(tmpX, tmpY);\nY = otherCalc(tmpX, tmpY);\n" }, { "answer_id": 1099401, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 0, "selected": false, "text": "Public Function ArrayFromDJRange(rangename As Range, slots As Integer) As Variant\n\n' this function copies a Disjoint Range of specified size into a Variant Array 7/8/09 ljr\n\nDim j As Integer\nDim wArray As Variant\nDim rCell As Range\n\nwArray = rangename.Value ' to initialize the working Array\nReDim wArray(0, slots - 1) ' set to size of range\nj = 0\n\nFor Each rCell In rangename\n wArray(0, j) = rCell.Value\n j = j + 1\nNext rCell\n\nArrayFromDJRange = wArray\n\nEnd Function\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ]
202,116
<p>Linux provides the stime(2) call to set the system time. However, while this will update the system's time, it does not set the BIOS hardware clock to match the new system time.</p> <p>Linux systems typically sync the hardware clock with the system time at shutdown and at periodic intervals. However, if the machine gets power-cycled before one of these automatic syncs, the time will be incorrect when the machine restarts.</p> <p>How do you ensure that the hardware clock gets updated when you set the system time?</p>
[ { "answer_id": 202118, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 3, "selected": false, "text": "system(\"/sbin/hwclock --systohc\");\n" }, { "answer_id": 202170, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 5, "selected": true, "text": "#include <linux/rtc.h>\n#include <sys/ioctl.h>\n\n\n struct rtc_time {\n int tm_sec; \n int tm_min; \n int tm_hour; \n int tm_mday; \n int tm_mon; \n int tm_year; \n int tm_wday; /* unused */\n int tm_yday; /* unused */\n int tm_isdst;/* unused */\n };\n\nint fd;\nstruct rtc_time rt;\n/* set your values here */\nfd = open(\"/dev/rtc\", O_RDONLY);\nioctl(fd, RTC_SET_TIME, &rt);\nclose(fd);\n" }, { "answer_id": 4057822, "author": "brian carr", "author_id": 492022, "author_profile": "https://Stackoverflow.com/users/492022", "pm_score": -1, "selected": false, "text": "sudo sudo kate /etc/default/rcS UTC=yes UTC=no" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
202,124
<p>I´m trying to expose services using jax-ws but the first surprise i got was that Weblogic does not support inner classes for request/response objects. After get over this situation <a href="https://stackoverflow.com/questions/144118/jaxb-binding-customization">here</a>, i´m facing another challenge:</p> <p>Generate <code>getXXX()</code> rather than/additionally to the <code>isXXX()</code> Method.</p> <p>I need to generate this methods cause when i start the service i get the message:</p> <pre><code>&lt;WS data binding error&gt;could not find getter for property 'IsXXX' on com.foo.MyClass </code></pre> <p>Tried a customization:</p> <pre><code>&lt;jaxb:globalBindings generateIsSetMethod=&quot;false&quot; enableJavaNamingConventions=&quot;false&quot;&gt; </code></pre> <p>without effect. :(</p> <p>Any help?</p>
[ { "answer_id": 1009590, "author": "AlanG", "author_id": 11645, "author_profile": "https://Stackoverflow.com/users/11645", "pm_score": 2, "selected": true, "text": " <taskdef name=\"xjc\" classname=\"com.sun.tools.xjc.XJCTask\" classpathref=\"development.classpath\"/>\n\n <xjc schema=\"some.xsd\" package=\"com.acme.jaxb\" destdir=\"gen-src\">\n <arg value=\"-Xcollection-setter-injector\"/> \n <arg value=\"-Xboolean-getter\"/>\n </xjc> \n" }, { "answer_id": 11139042, "author": "rainer198", "author_id": 602856, "author_profile": "https://Stackoverflow.com/users/602856", "pm_score": 2, "selected": false, "text": "getXXX() isXXX()" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21370/" ]
202,136
<p>Hello fellow stackoverflowers!</p> <p>I have a word list of 200.000 string entries, average string length is around 30 characters. This list of words are the key and to each key i have a domain object. I would like to find the domain objects in this collection by only knowing a part of the key. I.E. the search string "kov" would for example match the key "stackoverflow". </p> <p>Currently I am using a Ternary Search Tree (TST), which usually will find the items within 100 milliseconds. This is however too slow for my requirements. The TST implementation could be improved with some minor optimizations and I could try to balance the tree. But i figured that these things would not give me the 5x - 10x speed improvement I am aiming at. I am assuming that the reason for being so slow is that i basically have to visit most nodes in the tree.</p> <p>Any ideas on how to improve the speed of the algorithm? Are there any other algorithms that I should be looking at?</p> <p>Thanks in advance, Oskar</p>
[ { "answer_id": 202195, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "SubString m_Data SubString class QGramIndex {\n private readonly int m_Maxlen;\n private readonly string m_Data;\n private readonly int m_Q;\n private int[] m_SA;\n private Dictionary<string, int> m_Dir = new Dictionary<string, int>();\n\n private struct StrCmp : IComparer<int> {\n public readonly String Data;\n public StrCmp(string data) { Data = data; }\n public int Compare(int x, int y) {\n return string.CompareOrdinal(Data.Substring(x), Data.Substring(y));\n }\n }\n\n private readonly StrCmp cmp;\n\n public QGramIndex(IList<string> strings, int maxlen, int q) {\n m_Maxlen = maxlen;\n m_Q = q;\n\n var sb = new StringBuilder(strings.Count * maxlen);\n foreach (string str in strings)\n sb.AppendFormat(str.PadRight(maxlen, '\\u0000'));\n m_Data = sb.ToString();\n cmp = new StrCmp(m_Data);\n MakeSuffixArray();\n MakeIndex();\n }\n\n public int this[string s] { get { return FindInIndex(s); } }\n\n private void MakeSuffixArray() {\n // Approx. runtime: n^3 * log n!!!\n // But I claim the shortest ever implementation of a suffix array!\n m_SA = Enumerable.Range(0, m_Data.Length).ToArray();\n Array.Sort(m_SA, cmp);\n }\n\n private int FindInArray(int ith) {\n return Array.BinarySearch(m_SA, ith, cmp);\n }\n\n private int FindInIndex(string s) {\n int idx;\n if (!m_Dir.TryGetValue(s, out idx))\n return -1;\n return m_SA[idx] / m_Maxlen;\n }\n\n private string QGram(int i) {\n return i > m_Data.Length - m_Q ?\n m_Data.Substring(i) :\n m_Data.Substring(i, m_Q);\n }\n\n private void MakeIndex() {\n for (int i = 0; i < m_Data.Length; ++i) {\n int pos = FindInArray(i);\n if (pos < 0) continue;\n m_Dir[QGram(i)] = pos;\n }\n }\n}\n static void Main(string[] args) {\n var strings = new [] { \"hello\", \"world\", \"this\", \"is\", \"a\",\n \"funny\", \"test\", \"which\", \"i\", \"have\",\n \"taken\", \"much\", \"too\", \"far\", \"already\" };\n\n var index = new QGramIndex(strings, 10, 3);\n\n var tests = new [] { \"xyz\", \"aki\", \"ake\", \"muc\", \"uch\", \"too\", \"fun\", \"est\",\n \"hic\", \"ell\", \"llo\", \"his\" };\n\n foreach (var str in tests) {\n int pos = index[str];\n if (pos > -1)\n Console.WriteLine(\"\\\"{0}\\\" found in \\\"{1}\\\".\", str, strings[pos]);\n else\n Console.WriteLine(\"\\\"{0}\\\" not found.\", str);\n }\n}\n" }, { "answer_id": 202250, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "(root)->f->fo->foo" }, { "answer_id": 204977, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "SubString using Position = System.Collections.Generic.KeyValuePair<int, int>;\n\nclass QGramIndex {\n private readonly int m_Q;\n private readonly IList<string> m_Data;\n private Position[] m_SA;\n private Dictionary<string, int> m_Dir;\n\n public QGramIndex(IList<string> strings, int q) {\n m_Q = q;\n m_Data = strings;\n MakeSuffixArray();\n MakeIndex();\n }\n\n public int this[string s] { get { return FindInIndex(s); } }\n\n private int FindInIndex(string s) {\n int idx;\n if (!m_Dir.TryGetValue(s, out idx))\n return -1;\n return m_SA[idx].Key;\n }\n\n private void MakeSuffixArray() {\n int size = m_Data.Sum(str => str.Length < m_Q ? 0 : str.Length - m_Q + 1);\n m_SA = new Position[size];\n int pos = 0;\n for (int i = 0; i < m_Data.Count; ++i)\n for (int j = 0; j <= m_Data[i].Length - m_Q; ++j)\n m_SA[pos++] = new Position(i, j);\n\n Array.Sort(\n m_SA,\n (x, y) => string.CompareOrdinal(\n m_Data[x.Key].Substring(x.Value),\n m_Data[y.Key].Substring(y.Value)\n )\n );\n }\n\n private void MakeIndex() {\n m_Dir = new Dictionary<string, int>(m_SA.Length);\n\n // Every q-gram is a prefix in the suffix table.\n for (int i = 0; i < m_SA.Length; ++i) {\n var pos = m_SA[i];\n m_Dir[m_Data[pos.Key].Substring(pos.Value, 5)] = i;\n }\n }\n}\n maxlen" }, { "answer_id": 43089193, "author": "Baxter", "author_id": 2254421, "author_profile": "https://Stackoverflow.com/users/2254421", "pm_score": 0, "selected": false, "text": "Example: x = HILLARY, y = HILARI(query term)\nQgrams\n$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$\n$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$\nnumber of q-grams in common = 4\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
202,142
<p>I can connect with a user who has permissions to set passwords. I'm able to change attributes, but I can't set the password.</p> <p>Found some instructions to set the attribute <code>unicodePwd</code> to <code>\UNC:"*password*"</code>, but it says:</p> <blockquote> <p>Error: Modify: Unwilling To Perform. &lt;53></p> </blockquote> <p>Setting LDAP_OPT_ENCRYPT to 1 didn't work either. The port I'm using is 389.</p>
[ { "answer_id": 202195, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "SubString m_Data SubString class QGramIndex {\n private readonly int m_Maxlen;\n private readonly string m_Data;\n private readonly int m_Q;\n private int[] m_SA;\n private Dictionary<string, int> m_Dir = new Dictionary<string, int>();\n\n private struct StrCmp : IComparer<int> {\n public readonly String Data;\n public StrCmp(string data) { Data = data; }\n public int Compare(int x, int y) {\n return string.CompareOrdinal(Data.Substring(x), Data.Substring(y));\n }\n }\n\n private readonly StrCmp cmp;\n\n public QGramIndex(IList<string> strings, int maxlen, int q) {\n m_Maxlen = maxlen;\n m_Q = q;\n\n var sb = new StringBuilder(strings.Count * maxlen);\n foreach (string str in strings)\n sb.AppendFormat(str.PadRight(maxlen, '\\u0000'));\n m_Data = sb.ToString();\n cmp = new StrCmp(m_Data);\n MakeSuffixArray();\n MakeIndex();\n }\n\n public int this[string s] { get { return FindInIndex(s); } }\n\n private void MakeSuffixArray() {\n // Approx. runtime: n^3 * log n!!!\n // But I claim the shortest ever implementation of a suffix array!\n m_SA = Enumerable.Range(0, m_Data.Length).ToArray();\n Array.Sort(m_SA, cmp);\n }\n\n private int FindInArray(int ith) {\n return Array.BinarySearch(m_SA, ith, cmp);\n }\n\n private int FindInIndex(string s) {\n int idx;\n if (!m_Dir.TryGetValue(s, out idx))\n return -1;\n return m_SA[idx] / m_Maxlen;\n }\n\n private string QGram(int i) {\n return i > m_Data.Length - m_Q ?\n m_Data.Substring(i) :\n m_Data.Substring(i, m_Q);\n }\n\n private void MakeIndex() {\n for (int i = 0; i < m_Data.Length; ++i) {\n int pos = FindInArray(i);\n if (pos < 0) continue;\n m_Dir[QGram(i)] = pos;\n }\n }\n}\n static void Main(string[] args) {\n var strings = new [] { \"hello\", \"world\", \"this\", \"is\", \"a\",\n \"funny\", \"test\", \"which\", \"i\", \"have\",\n \"taken\", \"much\", \"too\", \"far\", \"already\" };\n\n var index = new QGramIndex(strings, 10, 3);\n\n var tests = new [] { \"xyz\", \"aki\", \"ake\", \"muc\", \"uch\", \"too\", \"fun\", \"est\",\n \"hic\", \"ell\", \"llo\", \"his\" };\n\n foreach (var str in tests) {\n int pos = index[str];\n if (pos > -1)\n Console.WriteLine(\"\\\"{0}\\\" found in \\\"{1}\\\".\", str, strings[pos]);\n else\n Console.WriteLine(\"\\\"{0}\\\" not found.\", str);\n }\n}\n" }, { "answer_id": 202250, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "(root)->f->fo->foo" }, { "answer_id": 204977, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "SubString using Position = System.Collections.Generic.KeyValuePair<int, int>;\n\nclass QGramIndex {\n private readonly int m_Q;\n private readonly IList<string> m_Data;\n private Position[] m_SA;\n private Dictionary<string, int> m_Dir;\n\n public QGramIndex(IList<string> strings, int q) {\n m_Q = q;\n m_Data = strings;\n MakeSuffixArray();\n MakeIndex();\n }\n\n public int this[string s] { get { return FindInIndex(s); } }\n\n private int FindInIndex(string s) {\n int idx;\n if (!m_Dir.TryGetValue(s, out idx))\n return -1;\n return m_SA[idx].Key;\n }\n\n private void MakeSuffixArray() {\n int size = m_Data.Sum(str => str.Length < m_Q ? 0 : str.Length - m_Q + 1);\n m_SA = new Position[size];\n int pos = 0;\n for (int i = 0; i < m_Data.Count; ++i)\n for (int j = 0; j <= m_Data[i].Length - m_Q; ++j)\n m_SA[pos++] = new Position(i, j);\n\n Array.Sort(\n m_SA,\n (x, y) => string.CompareOrdinal(\n m_Data[x.Key].Substring(x.Value),\n m_Data[y.Key].Substring(y.Value)\n )\n );\n }\n\n private void MakeIndex() {\n m_Dir = new Dictionary<string, int>(m_SA.Length);\n\n // Every q-gram is a prefix in the suffix table.\n for (int i = 0; i < m_SA.Length; ++i) {\n var pos = m_SA[i];\n m_Dir[m_Data[pos.Key].Substring(pos.Value, 5)] = i;\n }\n }\n}\n maxlen" }, { "answer_id": 43089193, "author": "Baxter", "author_id": 2254421, "author_profile": "https://Stackoverflow.com/users/2254421", "pm_score": 0, "selected": false, "text": "Example: x = HILLARY, y = HILARI(query term)\nQgrams\n$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$\n$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$\nnumber of q-grams in common = 4\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533/" ]
202,144
<p>We have a few developers working on the same VS2005 solution, but our source control is very bad. (Our company uses Harvest, which we give a vote of no confidence).</p> <p>Right now, we're all just working off of the files on a shared lan drive. Obviously, this causes some problems. But we think it's better than working locally, and tracking the files we touched in a spreadsheet and merging everything manually. Does anybody have a strategy for merging our changes?</p> <p>Some of the problems exist because of corporate beaurocracy (like mandating Harvest). Those same policies prevent introducing new tools into our environment. So, strategies that avoid buying/downloading new software would work best for us.</p>
[ { "answer_id": 202182, "author": "Frank Schmitt", "author_id": 27951, "author_profile": "https://Stackoverflow.com/users/27951", "pm_score": 2, "selected": false, "text": "merge mine older yours\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
202,147
<p>Is there a way to start another application from within Compact .Net framework 1.0 similar to </p> <pre><code>System.Diagnostics.Process.Start </code></pre> <p>on the Windows side?</p> <p>I need to start a CAB file for installation.</p>
[ { "answer_id": 202182, "author": "Frank Schmitt", "author_id": 27951, "author_profile": "https://Stackoverflow.com/users/27951", "pm_score": 2, "selected": false, "text": "merge mine older yours\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18169/" ]
202,148
<p>I have a text file where I want to change only the first line of the file. The file could be millions of rows long, so I'd rather not have to loop over everything, so I'm wondering if there is another way to do this.</p> <p>I'd also like to apply some rules to the first line so that I replace instances of certain words with other words.</p> <p>Is this possible?</p>
[ { "answer_id": 202185, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "String.replaceFirst(String regex, String replacement) RandomAccessFile" }, { "answer_id": 202192, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 5, "selected": true, "text": "RandomAccessFile BufferedReader BufferedWriter BufferedReader readLine() BufferedWriter char[]" }, { "answer_id": 67764865, "author": "Godwince Owiti Adera", "author_id": 16060341, "author_profile": "https://Stackoverflow.com/users/16060341", "pm_score": 0, "selected": false, "text": "public void main() throws IOException {\n String newString = \"The New String\";\n File myFile = new File(\"PathToFile\");\n // An array to store each line in the file\n ArrayList<String> fileContent = new ArrayList<String>();\n Scanner myReader = new Scanner(myFile);\n while (myReader.hasNextLine()) {\n // Reads the file content into an array\n fileContent.add(myReader.nextLine());\n }\n myReader.close();\n // Removes Original Line\n fileContent.remove(0);\n // Enters New Line\n fileContent.add(0, newString);\n // Writes the new content to file\n FileWriter myWriter = new FileWriter(\"PathToFile\");\n for (String eachLine : fileContent) {\n myWriter.write(eachLine + \"\\n\");\n }\n myWriter.close();\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
202,166
<p>I'm writing a lightweight game engine and while doing some research for it I've come across a number of compelling articles advocating the implementation of Game Objects through a "collection of components" model rather than an "inheiritance from concrete classes" model. There are lots of advantages:</p> <ul> <li>objects can be composed using data driven design techniques, allowing designers to come up with new objects without involving a programmer;</li> <li>there tend to be fewer source file dependencies, allowing code to be compiled faster;</li> <li>the engine as a whole becomes more general;</li> <li>unforseen consequences of having to change concrete classes high up the inheiritance hierarchy can be avoided;</li> <li>and so on.</li> </ul> <p>But there are parts of the system that remain opaque. Primarily among these is how components of the same object communicate with each other. For example, let's say an object that models a bullet in game is implemented in terms of these components:</p> <ul> <li>a bit of geometry for visual representation</li> <li>a position in the world</li> <li>a volume used for collision with other objects</li> <li>other things</li> </ul> <p>At render time the geometry has to know its position in the world in order to display correctly, but how does it find that position among all its sibling components in the object? And at update time, how does the collision volume find the object's position in the world in order to test for its intersection with other objects?</p> <p>I guess my question can be boiled down to this: Okay, we have objects that are composed of a number of components that each implement a bit of functionality. What is the best way for this to work at runtime?</p>
[ { "answer_id": 205284, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 1, "selected": false, "text": "object.burnable = new Burnable(object);\n if (object.burnable != null)\n{\n object.burnable.burn();\n}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13149/" ]
202,197
<p>I have a requirement to create a simple database in Access to collect some user data that will be loaded into another database for further reporting. There will be a module in the Access db that when invoked by the user (probably by clicking a button) will output a query to a delimited file. The user also needs a mechanism (for example a form with a button) to easily transfer the file to a remote server, using sftp. Does anyone have an idea of how to accomplish this?</p>
[ { "answer_id": 202316, "author": "Mat Nadrofsky", "author_id": 26853, "author_profile": "https://Stackoverflow.com/users/26853", "pm_score": 4, "selected": true, "text": "mySFTPCall = \"sftp <insert your options here!>\"\nCall Shell(mySFTPCall, 1)\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3734/" ]
202,198
<p>I'm interested in hearing your opinions in which is the best way of implementing a social activity stream (Facebook is the most famous example). Problems/challenges involved are:</p> <ul> <li>Different types of activities (posting, commenting ..)</li> <li>Different types of objects (post, comment, photo ..)</li> <li>1-n users involved in different roles ("User x replied to User y's comment on User's Z post")</li> <li>Different views of the same activity item ("you commented .." vs. "your friend x commented" vs. "user x commented .." => 3 representations of a "comment" activity)</li> </ul> <p>.. and some more, especially if you take it to a high level of sophistication, as Facebook does, for example, combining several activity items into one ("users x, y and z commented on that photo"</p> <p>Any thoughts or pointers on patterns, papers, etc on the most flexible, efficient and powerful approaches to implementing such a system, data model, etc. would be appreciated.</p> <p>Although most of the issues are platform-agnostic, chances are I end up implementing such a system on Ruby on Rails</p>
[ { "answer_id": 205477, "author": "heyman", "author_id": 27406, "author_profile": "https://Stackoverflow.com/users/27406", "pm_score": 7, "selected": false, "text": "{id:1, userId:1, type:PHOTO, time:2008-10-15 12:00:00, data:{photoId:2089, photoName:A trip to the beach}}\n" }, { "answer_id": 1753335, "author": "Rodrigo", "author_id": 213432, "author_profile": "https://Stackoverflow.com/users/213432", "pm_score": 2, "selected": false, "text": "HISTORY_TYPE\n\nID - The id of the history type\nNAME - The name (type of the history)\nDESCRIPTION - A description\n\nHISTORY_MESSAGES\n\nID\nHISTORY_TYPE - A message of history belongs to a history type\nMESSAGE - The message to print, I put variables to be replaced by the actual values\n\nHISTORY_ACTIVITY\n\nID\nMESSAGE_ID - The message ID to use\nVALUES - The data to use\n MESSAGE_ID_1 => \"User %{user} created a new entry\"\nACTIVITY_ID_1 => MESSAGE_ID = 1, VALUES = {user: \"Rodrigo\"}\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
202,205
<p>One of the responses to <a href="https://stackoverflow.com/questions/198721/converting-a-word-document-into-usable-html-in-php">a question I asked yesterday</a> suggested that I should make sure my database can handle UTF-8 characters correctly. How I can do this with MySQL?</p>
[ { "answer_id": 202246, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 8, "selected": true, "text": "utf8mb4 utf8mb4_unicode_ci ALTER DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n my.cnf default-character-set character-set-server SET NAMES utf8 DEFAULT CHARSET=utf8 my.cnf" }, { "answer_id": 202248, "author": "Claudio", "author_id": 27958, "author_profile": "https://Stackoverflow.com/users/27958", "pm_score": -1, "selected": false, "text": "SET NAMES UTF8" }, { "answer_id": 202276, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 6, "selected": false, "text": "my.cnf [client]\ndefault-character-set=utf8\n[mysqld]\ncharacter-set-server = utf8\n SHOW VARIABLES LIKE 'character_set%';\n utf8 ..._filesystem binary ..._dir" }, { "answer_id": 202287, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 3, "selected": false, "text": "show create database foo; \n> CREATE DATABASE `foo`.`foo` /*!40100 DEFAULT CHARACTER SET latin1 */\n\nshow create table foo.bar;\n> lots of stuff ending with\n> ) ENGINE=InnoDB AUTO_INCREMENT=252 DEFAULT CHARSET=latin1\n ALTER TABLE `foo`.`bar` CHARACTER SET utf8;\n" }, { "answer_id": 10673309, "author": "Vlad Balan", "author_id": 791250, "author_profile": "https://Stackoverflow.com/users/791250", "pm_score": 2, "selected": false, "text": "[myslqd]\nskip-character-set-client-handshake\ncollation_server=utf8_unicode_ci\ncharacter_set_server=utf8 \n" }, { "answer_id": 18197185, "author": "fin", "author_id": 2676561, "author_profile": "https://Stackoverflow.com/users/2676561", "pm_score": -1, "selected": false, "text": " if($handle = @mysql_connect(DB_HOST, DB_USER, DB_PASS)){ \n //set to utf8 encoding\n mysql_set_charset('utf8',$handle);\n }\n" }, { "answer_id": 29929677, "author": "T.W.R. Cole", "author_id": 1536280, "author_profile": "https://Stackoverflow.com/users/1536280", "pm_score": 5, "selected": false, "text": "utf8 utf8mb4" }, { "answer_id": 30725859, "author": "Nishant", "author_id": 4960611, "author_profile": "https://Stackoverflow.com/users/4960611", "pm_score": -1, "selected": false, "text": "SET NAMES UTF8;\nset collation_server = utf8_general_ci;\nset default-character-set = utf8;\nset init_connect = ’SET NAMES utf8′;\nset character_set_server = utf8;\nset character_set_client = utf8;\n" }, { "answer_id": 34889966, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 4, "selected": false, "text": "utf8mb4 SET NAMES utf8mb4 CHARACTER SET utf8mb4 <meta charset charset=UTF-8> CHARACTER SET utf8mb4 COLLATION utf8mb4_unicode_520_ci" }, { "answer_id": 34892639, "author": "Vipin Jain", "author_id": 2153834, "author_profile": "https://Stackoverflow.com/users/2153834", "pm_score": -1, "selected": false, "text": "Character Set Collation latin1, latin1_swedish_ci utf8 utf8_general_ci CREATE DATABASE new_db\n DEFAULT CHARACTER SET utf8\n DEFAULT COLLATE utf8_general_ci;\n [mysqld]\ncharacter-set-server=utf8\ncollation-server=utf8_general_ci\n shell> cmake . -DDEFAULT_CHARSET=utf8 \\\n -DDEFAULT_COLLATION=utf8_general_ci\n SHOW VARIABLES LIKE 'character_set%';\nSHOW VARIABLES LIKE 'collation%';\n" }, { "answer_id": 34986985, "author": "Nyein Aung", "author_id": 5789774, "author_profile": "https://Stackoverflow.com/users/5789774", "pm_score": 2, "selected": false, "text": "ALTER DATABASE ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;\n" }, { "answer_id": 34987675, "author": "Gaurav Lad", "author_id": 4587277, "author_profile": "https://Stackoverflow.com/users/4587277", "pm_score": 0, "selected": false, "text": "database collation UTF-8 table collation" }, { "answer_id": 36616316, "author": "sunil subramanya", "author_id": 3494644, "author_profile": "https://Stackoverflow.com/users/3494644", "pm_score": -1, "selected": false, "text": "$connect = mysql_connect('$localhost','$username','$password') or die(mysql_error());\nmysql_set_charset('utf8',$connect);\nmysql_select_db('$database_name','$connect') or die(mysql_error());\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11522/" ]
202,206
<p>I am building an enterprise application with .Net 1.1 and SQL Server 2000. I use the read committed isolation level . However changes in non-functional requirements have made it necessary to take measures against non-repeatable reads and phantoms. I see two options: </p> <ol> <li><p>Introduce row-versioning to check if a row has been modified since it was read within a transaction. This is done by adding a VersionId column to tables abd incrementing the value whenever the row is changed. This would solve the problem but require us to rewrite all stored procedures and the data access layer of our applications. </p></li> <li><p>Migrate to SQL Server 2005 and use the snapshot isolation level. This would save us the trouble of rewriting code, but there are a few challenges: a. The snapshot isolation level is not known in .Net 1.1, so we must take an extra round trip to the server to set it manually. b. We cannot make use of temporary tables in our stored procedures because the snapshot isolation level does not allow changes to the schema of the tempdb. I'm not sure how to around this. </p></li> </ol> <p>Any ideas or suggestions are more than wellcome </p>
[ { "answer_id": 243609, "author": "GilaMonster", "author_id": 9342, "author_profile": "https://Stackoverflow.com/users/9342", "pm_score": 1, "selected": false, "text": "ALLOW_SNAPSHOT_ISOLATION" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
202,231
<p>I need to detect the device resolution automatically, right now I have a global var &amp; hardwire the resolution:</p> <pre><code>Public gDeviceRes As String = "640" 'Public gDeviceRes As String = "320" </code></pre> <p>then recompile for each device, does anyone have a quick snippit of code for this??</p>
[ { "answer_id": 202582, "author": "Scott Kramer", "author_id": 3522, "author_profile": "https://Stackoverflow.com/users/3522", "pm_score": 2, "selected": false, "text": " Dim screensize As System.Drawing.Rectangle = Screen.PrimaryScreen.Bounds\n Public gDeviceRes As String = screensize.Height\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3522/" ]
202,234
<p>I have an app that executes commands on a Linux server via SSH just fine. When I connect to a Solaris server, things don't work. It seems that the Solaris command line is limited to 267 characters.</p> <p>Is there a way to change this?</p> <p>Update: As was pointed out before, this is a limit to the default shell for Solaris (sh) vs Linux (bash). So, now the question is, is there a way to change the limit for sh?</p>
[ { "answer_id": 202396, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 1, "selected": false, "text": "/usr/bin/foo with a very long list of options and parameters\n ssh user@machine \"/usr/bin/foo with a very long list of options and parameters\"\n echo \"/usr/bin/foo with a very long list of options and parameters\" | \\\nssh user@machine \"/bin/bash\"\n" }, { "answer_id": 2056784, "author": "brianegge", "author_id": 14139, "author_profile": "https://Stackoverflow.com/users/14139", "pm_score": 2, "selected": false, "text": "$ getconf ARG_MAX\n1048320\n" }, { "answer_id": 65608390, "author": "pituś", "author_id": 14957066, "author_profile": "https://Stackoverflow.com/users/14957066", "pm_score": 1, "selected": false, "text": "serwer%\n\nserwer% echo *\n\nArguments too long\n\nserwer% ksh\n\n$ echo *\n\nfile1\n\nfile2\n\n....\n\nfile 10000\n\n% exit\n\nserwer%\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5389/" ]
202,243
<p>I am trying to write a stored procedure which selects columns from a table and adds 2 extra columns to the ResultSet. These 2 extra columns are the result of conversions on a field in the table which is a Datetime field.</p> <p>The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'</p> <p>The 2 additional fields which should be in the following format:</p> <ol> <li>DDMMM</li> <li>HHMMT, where T is 'A' for a.m. and 'P' for p.m.</li> </ol> <p>Example: If the data in the field was '2008-10-12 13:19:12.0' then the extracted fields should contain:</p> <ol> <li>12OCT</li> <li>0119P</li> </ol> <p>I have tried using CONVERT string formats, but none of the formats match the output I want to get. I am thinking along the lines of extracting the field data via CONVERT and then using REPLACE, but I surely need some help here, as I am no sure.</p> <p>Could anyone well versed in stored procedures help me out here? Thanks!</p>
[ { "answer_id": 202284, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 4, "selected": true, "text": "SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)\n + UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))\n SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)\n + SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)\n" }, { "answer_id": 202288, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 5, "selected": false, "text": "declare @myTime as DateTime\n\nset @myTime = GETDATE()\n\nselect @myTime\n\nselect DATENAME(day, @myTime) + SUBSTRING(UPPER(DATENAME(month, @myTime)), 0,4)\n /* Common date functions */\n--//This contains common date functions for MSSQL server\n\n/*Getting Parts of a DateTime*/\n --//gets the date only, 20x faster than using Convert/Cast to varchar\n --//this has been especially useful for JOINS\n SELECT (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime))\n\n --//gets the time only (date portion is '1900-01-01' and is considered the \"0 time\" of dates in MSSQL, even with the datatype min value of 01/01/1753. \n SELECT (GETDATE() - (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime)))\n\n\n/*Relative Dates*/\n--//These are all functions that will calculate a date relative to the current date and time\n /*Current Day*/\n --//now\n SELECT (GETDATE())\n\n --//midnight of today\n SELECT (DATEADD(ms,-4,(DATEADD(dd,DATEDIFF(dd,0,GETDATE()) + 1,0))))\n\n --//Current Hour\n SELECT DATEADD(hh,DATEPART(hh,GETDATE()),CAST(FLOOR(CAST(GETDATE() AS FLOAT)) as DateTime))\n\n --//Current Half-Hour - if its 9:36, this will show 9:30\n SELECT DATEADD(mi,((DATEDIFF(mi,(CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)), GETDATE())) / 30) * 30,(CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)))\n\n /*Yearly*/\n --//first datetime of the current year\n SELECT (DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))\n\n --//last datetime of the current year\n SELECT (DATEADD(ms,-4,(DATEADD(yy,DATEDIFF(yy,0,GETDATE()) + 1,0))))\n\n /*Monthly*/\n --//first datetime of current month\n SELECT (DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))\n\n --//last datetime of the current month\n SELECT (DATEADD(ms,-4,DATEADD(mm,1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))))\n\n --//first datetime of the previous month\n SELECT (DATEADD(mm,DATEDIFF(mm,0,GETDATE()) -1,0))\n\n --//last datetime of the previous month\n SELECT (DATEADD(ms, -4,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)))\n\n /*Weekly*/\n --//previous monday at 12AM\n SELECT (DATEADD(wk,DATEDIFF(wk,0,GETDATE()) -1 ,0))\n\n --//previous friday at 11:59:59 PM\n SELECT (DATEADD(ms,-4,DATEADD(dd,5,DATEADD(wk,DATEDIFF(wk,0,GETDATE()) -1 ,0))))\n\n /*Quarterly*/\n --//first datetime of current quarter\n SELECT (DATEADD(qq,DATEDIFF(qq,0,GETDATE()),0))\n\n --//last datetime of current quarter\n SELECT (DATEADD(ms,-4,DATEADD(qq,DATEDIFF(qq,0,GETDATE()) + 1,0)))\n" }, { "answer_id": 6368613, "author": "Davut Gürbüz", "author_id": 413032, "author_profile": "https://Stackoverflow.com/users/413032", "pm_score": 1, "selected": false, "text": "SELECT CAST(DATEPART(DD,GETDATE()) AS VARCHAR)+'/'\n+CAST(DATEPART(MM,GETDATE()) AS VARCHAR)\n+'/'+CAST(DATEPART(YYYY,GETDATE()) AS VARCHAR)\n+' '+CAST(DATEPART(HH,GETDATE()) AS VARCHAR)\n+':'+CAST(DATEPART(MI,GETDATE()) AS VARCHAR)\n Select to_char(sysdate,'DD/MM/YYYY HH24:MI') from dual\n select myshortfun(getdate(),myformat)\nGO\n" }, { "answer_id": 21631065, "author": "Mark", "author_id": 3250242, "author_profile": "https://Stackoverflow.com/users/3250242", "pm_score": 0, "selected": false, "text": "DateKey yyyymmdd DECLARE @DateKeyToday int = (SELECT 10000 * DATEPART(yy,GETDATE()) + 100 * DATEPART(mm,GETDATE()) + DATEPART(dd,GETDATE()));\nPRINT @DateKeyToday\n" }, { "answer_id": 28683330, "author": "Pawel Cioch", "author_id": 1818723, "author_profile": "https://Stackoverflow.com/users/1818723", "pm_score": 0, "selected": false, "text": "REPLACE(SUBSTRING(CONVERT(VARCHAR, @dt, 120), 1, 10),'-','_')\n" }, { "answer_id": 38428513, "author": "Mehdi", "author_id": 1010619, "author_profile": "https://Stackoverflow.com/users/1010619", "pm_score": 4, "selected": false, "text": "select FORMAT(getdate(), N'yyyy-MM-ddThh:mm:ss')\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311/" ]
202,245
<p>I'm looking for a way to sequentially number rows in a <em>result set</em> (not a table). In essence, I'm starting with a query like the following:</p> <pre><code>SELECT id, name FROM people WHERE name = 'Spiewak' </code></pre> <p>The <code>id</code>s are obviously not a true sequence (e.g. <code>1, 2, 3, 4</code>). What I need is another column in the result set which contains these auto-numberings. I'm willing to use a SQL function if I have to, but I would rather do it without using extensions on the ANSI spec.</p> <p>Platform is MySQL, but the technique should be cross-platform if at all possible (hence the desire to avoid non-standard extensions).</p>
[ { "answer_id": 202265, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "SELECT id, name\n , (SELECT COUNT(*) FROM people p2 WHERE name='Spiewak' AND p2.id <= p1.id) AS RowNumber\nFROM people p1\nWHERE name = 'Spiewak'\nORDER BY id\n" }, { "answer_id": 202275, "author": "Claudio", "author_id": 27958, "author_profile": "https://Stackoverflow.com/users/27958", "pm_score": 3, "selected": false, "text": "SELECT a.*, @num := @num + 1 b from test a, (SELECT @num := 0) d;" }, { "answer_id": 202278, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 3, "selected": false, "text": "SELECT id, name, sub.lcount\nFROM people outer\nJOIN (SELECT id, COUNT(id) lcount FROM people WHERE name = 'Spiewak' AND id < outer.id GROUP BY id) sub on outer.id = sub.id\nWHERE name = 'Spiewak'\n" }, { "answer_id": 3470394, "author": "Peter Johnson", "author_id": 339280, "author_profile": "https://Stackoverflow.com/users/339280", "pm_score": 2, "selected": false, "text": "SELECT @i:=@i+1 AS iterator, t.*\nFROM tablename t,(SELECT @i:=0) foo\n" }, { "answer_id": 8056028, "author": "jsutSomeRandonAnswer", "author_id": 1036325, "author_profile": "https://Stackoverflow.com/users/1036325", "pm_score": 2, "selected": false, "text": "select rownum, id , blah, blah\nfrom (\nselect id, name FROM people WHERE name = 'Spiewak'\n)\n" }, { "answer_id": 16679882, "author": "Code Cavalier", "author_id": 2125476, "author_profile": "https://Stackoverflow.com/users/2125476", "pm_score": 1, "selected": false, "text": " SELECT SUM(IF(p1.id > p2.id, 0, 1)) AS `row`, p2.id, p2.name\n FROM people p1 JOIN people p2 ON p1.name = p2.name\n WHERE p1.name = 'Spiewak'\n GROUP BY p2.id\n" }, { "answer_id": 67137995, "author": "k0L1081", "author_id": 8875079, "author_profile": "https://Stackoverflow.com/users/8875079", "pm_score": 1, "selected": false, "text": "SELECT\n p.ROW_NUMBER() over (order by id) as 'row_id',\n p.id as 'id',\n p.name as 'name'\nFROM\n people p\nWHERE\n p.name = 'Spiewak'\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9815/" ]
202,252
<p>Anybody know of a plugin, or a built in function to make the columns in a table sortable? i.e. I click on the column header and it sorts the rows by that column?</p>
[ { "answer_id": 36380772, "author": "João Paulo", "author_id": 1455108, "author_profile": "https://Stackoverflow.com/users/1455108", "pm_score": 0, "selected": false, "text": "var data = {\n people: [\n {name: 'a', address: 'c', salesperson: 'b'},\n {name: 'b', address: 'b', salesperson: 'a'},\n {name: 'c', address: 'a', salesperson: 'c'},\n ]\n};\n\nbreed.run({\n scope: 'people',\n input: data\n});\n <table>\n <thead>\n <tr>\n <th sort='name'>Name</th>\n <th sort='address'>Address</th>\n <th sort='salesperson'>Sales Person</th>\n </tr>\n </thead>\n <tbody>\n <tr b-scope=\"people\" b-loop=\"person in people\">\n <td b-sort=\"name\">{{person.name}}</td>\n <td b-sort=\"address\">{{person.address}}</td>\n <td b-sort=\"salesperson\">{{person.salesperson}}</td>\n </tr>\n </tbody>\n</table>\n breed.sort({\n scope: 'people',\n selector: //field name\n});\n $(\"th\").click(function(){\n breed.sort({\n scope: 'people',\n selector: $(this).attr('sort')\n });\n});\n" }, { "answer_id": 74111482, "author": "Douglas Vicentini", "author_id": 6938902, "author_profile": "https://Stackoverflow.com/users/6938902", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<body>\n <table>\n <thead>\n <tr>\n <th>Column 1 <span>&uarr;</span></th>\n <th>Column 2 <span>&uarr;</span></th>\n <th>Column 3 <span>&uarr;</span></th>\n <th>Column 4 <span>&uarr;</span></th>\n <th>Column 5 <span>&uarr;</span></th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>100</td>\n <td>Product 22</td>\n <td>ABCASD</td>\n <td>22DDS</td>\n <td>454645</td>\n </tr>\n <tr>\n <td>99</td>\n <td>Proddduct 12</td>\n <td>AACASD</td>\n <td>22DDS</td>\n <td>354645</td>\n </tr>\n <tr>\n <td>300</td>\n <td>Product 22</td>\n <td>AcCASD</td>\n <td>32DDS</td>\n <td>554649</td>\n </tr>\n <tr>\n <td>400</td>\n <td>Proooooooduct 22</td>\n <td>AcdCASD</td>\n <td>3d2DDS</td>\n <td>554645</td>\n </tr>\n <tr>\n <td>10</td>\n <td>Product 1</td>\n <td>cCASD</td>\n <td>DDS</td>\n <td>4645</td>\n </tr>\n </tbody>\n </table>\n <br>\n <table>\n <thead>\n <tr>\n <th>Column 1 <span>&uarr;</span></th>\n <th>Column 2 <span>&uarr;</span></th>\n <th>Column 3 <span>&uarr;</span></th>\n <th>Column 4 <span>&uarr;</span></th>\n <th>Column 5 <span>&uarr;</span></th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>100</td>\n <td>Product 221</td>\n <td>ABCASD</td>\n <td>22DDS</td>\n <td>454645</td>\n </tr>\n <tr>\n <td>99</td>\n <td>Product 12</td>\n <td>AACASD</td>\n <td>22DDS</td>\n <td>354645</td>\n </tr>\n <tr>\n <td>300</td>\n <td>Product 222</td>\n <td>AcCASD</td>\n <td>32DDS</td>\n <td>554649</td>\n </tr>\n <tr>\n <td>400</td>\n <td>Product 22</td>\n <td>AcdCASD</td>\n <td>3d2DDS</td>\n <td>554645</td>\n </tr>\n <tr>\n <td>10</td>\n <td>Product 11</td>\n <td>cCASD</td>\n <td>DDS</td>\n <td>4645</td>\n </tr>\n </tbody>\n </table>\n <script>\n window.onload = function () { // After page loads\n Array.from(document.getElementsByTagName(\"th\")).forEach((element, index) => { // Table headers\n element.addEventListener(\"click\", function (event) {\n let table = this.closest(\"table\");\n\n let order_icon = this.getElementsByTagName(\"span\")[0];\n let order = encodeURI(order_icon.innerHTML).includes(\"%E2%86%91\") ? \"desc\" : \"asc\";\n\n let value_list = {}; // <tr> Object\n let obj_key = []; // Values of selected column\n let separator = \"-----\"; // Separate the value of it's index, so data keeps intact\n\n let string_count = 0;\n let number_count = 0;\n\n table.querySelectorAll(\"tbody tr\").forEach((linha, index_line) => { // <tbody> rows\n let key = linha.children[element.cellIndex].textContent.toUpperCase();\n key.replace(\"-\", \"\").match(/^[0-9,.]*$/g) ? number_count++ : string_count++; // Check if value is numeric or string\n\n value_list[key + separator + index_line] = linha.outerHTML.replace(/(\\t)|(\\n)/g, ''); // Adding <tr> to object\n obj_key.push(key + separator + index_line);\n });\n\n if (number_count > 0 && string_count <= 0) { // If all values are numeric\n obj_key.sort(function(a, b) {\n return a.split(separator)[0] - b.split(separator)[0];\n });\n }\n else {\n obj_key.sort();\n }\n\n if (order == \"desc\"){\n obj_key.reverse();\n order_icon.innerHTML = \"&darr;\";\n }\n else {\n order_icon.innerHTML = \"&uarr;\";\n }\n\n let html = \"\";\n obj_key.forEach(function (chave) {\n html += value_list[chave];\n });\n table.getElementsByTagName(\"tbody\")[0].innerHTML = html;\n });\n });\n }\n </script>\n</body>\n</html>" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
202,253
<p>I'm using Eclipse 3.4 and Tomcat 5.5 and I have a Dynamic Web Project set up. I can access it from <a href="http://127.0.0.1:8080/project/" rel="noreferrer">http://127.0.0.1:8080/project/</a> but by default it serves files from WebContent folder. The real files, that I want to serve, can be found under folder named "share". This folder comes from CVS so I'd like to use it with its given name instead of renaming it. How can this be done?</p>
[ { "answer_id": 202391, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 4, "selected": true, "text": ".settings org.eclipse.wst.common.component <wb-module deploy-name=\"WebProjectName\">\n <wb-resource deploy-path=\"/\" source-path=\"/WebContent\"/>\n <wb-resource deploy-path=\"/WEB-INF/classes\" source-path=\"/src\"/>\n wb-resource /share/" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27736/" ]
202,271
<p>The following code will not compile:</p> <pre><code>string foo = "bar"; Object o = foo == null ? DBNull.Value : foo; </code></pre> <p>I get: <em>Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'string'</em></p> <p>To fix this, I must do something like this:</p> <pre><code>string foo = "bar"; Object o = foo == null ? DBNull.Value : (Object)foo; </code></pre> <p>This cast seems pointless as this is certainly legal:</p> <pre><code>string foo = "bar"; Object o = foo == null ? "gork" : foo; </code></pre> <p>It seems to me that when the ternary branches are of different types, the compiler will not autobox the values to the type object...but when they are of the same type then the autoboxing is automatic.</p> <p>In my mind the first statement should be legal...</p> <p>Can anyone describe why the compiler does not allow this and why the designers of C# chose to do this? I believe this is legal in Java...Though I have not verified this.</p> <p>Thanks.</p> <p><strong>EDIT:</strong> I am asking for an understanding of why Java and C# handle this differently, what is going on underneath the scenes in C# that make this invalid. I know how to use ternary, and am not looking for a "better way" to code the examples. I understand the rules of ternary in C#, but I want to know WHY...</p> <p><strong>EDIT</strong> (Jon Skeet): Removed "autoboxing" tag as no boxing is involved in this question.</p>
[ { "answer_id": 202281, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "DBNull.Value DBNull string string null DBNull [condition] ? true value : false value;\n string item = \"item\";\n\nvar test = item != null ? item : \"BLANK\";\n var" }, { "answer_id": 202382, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "object result = (object)foo ?? DBNull.Value;\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
202,273
<p>I can currently to the following:</p> <pre><code>class SubClass extends SuperClass { function __construct() { parent::__construct(); } } class SuperClass { function __construct() { // this echoes "I'm SubClass and I'm extending SuperClass" echo 'I\'m '.get_class($this).' and I\'m extending '.__CLASS__; } } </code></pre> <p>I would like to do something similar with the filenames (<code>__FILE__</code>, but dynamically evaluated); I would like to know what file the subclass resides in, from the superclass. Is it possible in any elegant way?</p> <p>I know you could do something with <a href="http://fi.php.net/get_included_files" rel="nofollow noreferrer"><code>get_included_files()</code></a>, but that's not very efficient, especially if I have numerous instances.</p>
[ { "answer_id": 202308, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "__FILE__" }, { "answer_id": 202687, "author": "user27987", "author_id": 27987, "author_profile": "https://Stackoverflow.com/users/27987", "pm_score": 3, "selected": true, "text": "$ref = new ReflectionObject($this);\n$ref->getFileName(); // return the file where the object's class was declared\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238/" ]