qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
123,335
<p>what configuration needs to be tweaked, and where does it live, in order to increase the maximum allowed post size?</p>
[ { "answer_id": 10689080, "author": "Ahmed MANSOUR", "author_id": 1408361, "author_profile": "https://Stackoverflow.com/users/1408361", "pm_score": 2, "selected": false, "text": "<!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->\n<Connector port=\"8009\" \n enableLookups=\"false\" redirectPort=\"8443\" debug=\"0\"\n protocol=\"AJP/1.3\" maxPostSize=\"0\"/>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13973/" ]
123,336
<p>How can you strip non-ASCII characters from a string? (in C#)</p>
[ { "answer_id": 123340, "author": "philcruz", "author_id": 3784, "author_profile": "https://Stackoverflow.com/users/3784", "pm_score": 10, "selected": true, "text": "string s = \"søme string\";\ns = Regex.Replace(s, @\"[^\\u0000-\\u007F]+\", string.Empty);\n" }, { "answer_id": 135473, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 7, "selected": false, "text": "string inputString = \"Räksmörgås\";\nstring asAscii = Encoding.ASCII.GetString(\n Encoding.Convert(\n Encoding.UTF8,\n Encoding.GetEncoding(\n Encoding.ASCII.EncodingName,\n new EncoderReplacementFallback(string.Empty),\n new DecoderExceptionFallback()\n ),\n Encoding.UTF8.GetBytes(inputString)\n )\n);\n" }, { "answer_id": 2149552, "author": "Bent Rasmussen", "author_id": 444976, "author_profile": "https://Stackoverflow.com/users/444976", "pm_score": 4, "selected": false, "text": "public static string PureAscii(this string source, char nil = ' ')\n{\n var min = '\\u0000';\n var max = '\\u007F';\n return source.Select(c => c < min ? nil : c > max ? nil : c).ToText();\n}\n\npublic static string ToText(this IEnumerable<char> source)\n{\n var buffer = new StringBuilder();\n foreach (var c in source)\n buffer.Append(c);\n return buffer.ToString();\n}\n" }, { "answer_id": 10996650, "author": "Anonymous coward", "author_id": 1406693, "author_profile": "https://Stackoverflow.com/users/1406693", "pm_score": 1, "selected": false, "text": " string s = \"søme string\";\n Regex regex = new Regex(@\"[^a-zA-Z0-9\\s]\", (RegexOptions)0);\n return regex.Replace(s, \"\");\n" }, { "answer_id": 12671181, "author": "MonsCamus", "author_id": 1259649, "author_profile": "https://Stackoverflow.com/users/1259649", "pm_score": 3, "selected": false, "text": "parsememo = Regex.Replace(parsememo, @\"[^\\u001F-\\u007F]\", string.Empty);\n" }, { "answer_id": 17175416, "author": "rjp", "author_id": 2498194, "author_profile": "https://Stackoverflow.com/users/2498194", "pm_score": 3, "selected": false, "text": "sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));\n" }, { "answer_id": 18018166, "author": "Josh", "author_id": 767854, "author_profile": "https://Stackoverflow.com/users/767854", "pm_score": 6, "selected": false, "text": "parsememo = Regex.Replace(parsememo, @\"[^\\u0020-\\u007E]\", string.Empty);\n" }, { "answer_id": 18597825, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 2, "selected": false, "text": "string strippedString = new string(\n yourString.Where(c => c <= sbyte.MaxValue).ToArray()\n );\n char[] string" }, { "answer_id": 39987193, "author": "Polynomial Proton", "author_id": 2196341, "author_profile": "https://Stackoverflow.com/users/2196341", "pm_score": 3, "selected": false, "text": "Dim str1 as String= \"â, ??î or ôu� n☁i✑++$-♓!‼⁉4⃣od;/⏬'®;☕:☝)///1!@#\"\n\nDim extendedAscii As Encoding = Encoding.GetEncoding(\"ISO-8859-1\", \n New EncoderReplacementFallback(String.empty),\n New DecoderReplacementFallback())\n\nDim extendedAsciiBytes() As Byte = extendedAscii.GetBytes(str1)\n\nDim str2 As String = extendedAscii.GetString(extendedAsciiBytes)\n\nconsole.WriteLine(str2)\n'Output : â, ??î or ôu ni++$-!‼⁉4od;/';:)///1!@#$%^yz:\n" }, { "answer_id": 44464392, "author": "user890332", "author_id": 890332, "author_profile": "https://Stackoverflow.com/users/890332", "pm_score": 1, "selected": false, "text": "Regex.Replace(directory, \"[^a-zA-Z0-9\\\\:_\\- ]\", \"\")\n" }, { "answer_id": 65605049, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": -1, "selected": false, "text": "// https://en.wikipedia.org/wiki/Code_page#EBCDIC-based_code_pages\n// https://en.wikipedia.org/wiki/Windows_code_page#East_Asian_multi-byte_code_pages\n// https://en.wikipedia.org/wiki/Chinese_character_encoding\nSystem.Text.Encoding encRemoveAllBut = System.Text.Encoding.ASCII;\nencRemoveAllBut = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage); // System-encoding\nencRemoveAllBut = System.Text.Encoding.GetEncoding(1252); // Western European (iso-8859-1)\nencRemoveAllBut = System.Text.Encoding.GetEncoding(1251); // Windows-1251/KOI8-R\nencRemoveAllBut = System.Text.Encoding.GetEncoding(\"ISO-8859-5\"); // used by less than 0.1% of websites\nencRemoveAllBut = System.Text.Encoding.GetEncoding(37); // IBM EBCDIC US-Canada\nencRemoveAllBut = System.Text.Encoding.GetEncoding(500); // IBM EBCDIC Latin 1\nencRemoveAllBut = System.Text.Encoding.GetEncoding(936); // Chinese Simplified\nencRemoveAllBut = System.Text.Encoding.GetEncoding(950); // Chinese Traditional\nencRemoveAllBut = System.Text.Encoding.ASCII; // putting ASCII again, as to answer the question \n\n// https://stackoverflow.com/questions/123336/how-can-you-strip-non-ascii-characters-from-a-string-in-c\nstring inputString = \"RäksmörПривет, мирgås\";\nstring asAscii = encRemoveAllBut.GetString(\n System.Text.Encoding.Convert(\n System.Text.Encoding.UTF8,\n System.Text.Encoding.GetEncoding(\n encRemoveAllBut.CodePage,\n new System.Text.EncoderReplacementFallback(string.Empty),\n new System.Text.DecoderExceptionFallback()\n ),\n System.Text.Encoding.UTF8.GetBytes(inputString)\n )\n);\n\nSystem.Console.WriteLine(asAscii);\n // string str = Latinize(\"(æøå âôû?aè\");\npublic static string Latinize(string stIn)\n{\n // Special treatment for German Umlauts\n stIn = stIn.Replace(\"ä\", \"ae\");\n stIn = stIn.Replace(\"ö\", \"oe\");\n stIn = stIn.Replace(\"ü\", \"ue\");\n\n stIn = stIn.Replace(\"Ä\", \"Ae\");\n stIn = stIn.Replace(\"Ö\", \"Oe\");\n stIn = stIn.Replace(\"Ü\", \"Ue\");\n // End special treatment for German Umlauts\n\n string stFormD = stIn.Normalize(System.Text.NormalizationForm.FormD);\n System.Text.StringBuilder sb = new System.Text.StringBuilder();\n\n for (int ich = 0; ich < stFormD.Length; ich++)\n {\n System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);\n\n if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)\n {\n sb.Append(stFormD[ich]);\n } // End if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)\n\n } // Next ich\n\n\n //return (sb.ToString().Normalize(System.Text.NormalizationForm.FormC));\n return (sb.ToString().Normalize(System.Text.NormalizationForm.FormKC));\n} // End Function Latinize\n" }, { "answer_id": 73003696, "author": "Chris", "author_id": 19561503, "author_profile": "https://Stackoverflow.com/users/19561503", "pm_score": 0, "selected": false, "text": "var result = Regex.Replace(value, @\"[^\\u0020-\\u007E\\u00A0-\\u00FF]+\", string.Empty);\n" }, { "answer_id": 73134461, "author": "payam purchi", "author_id": 12955548, "author_profile": "https://Stackoverflow.com/users/12955548", "pm_score": 1, "selected": false, "text": "public string ReturnCleanASCII(string s)\n {\n StringBuilder sb = new StringBuilder(s.Length);\n foreach (char c in s)\n {\n if ((int)c > 127) // you probably don't want 127 either\n continue;\n if ((int)c < 32) // I bet you don't want control characters \n continue;\n if (c == '%')\n continue;\n if (c == '?')\n continue;\n sb.Append(c);\n }\n return sb.ToString();\n }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3784/" ]
123,378
<p>Is there a good command-line UNIX charting / graphing / plotting tool out there? I'm looking for something that will plot xy points on an ASCII graph.</p> <p>Just to clarify, I'm looking for something that will output a graph in ASCII (like ascii-art style), so I can use it over an interactive shell session without needing X.</p>
[ { "answer_id": 123396, "author": "Palmin", "author_id": 5949, "author_profile": "https://Stackoverflow.com/users/5949", "pm_score": 8, "selected": true, "text": "gnuplot> set terminal dumb\nTerminal type set to 'dumb'\nOptions are 'feed 79 24'\ngnuplot> plot sin(x)\n\n 1 ++----------------**---------------+----**-----------+--------**-----++\n + *+ * + * * + sin(x) ****** +\n 0.8 ++ * * * * * * ++\n | * * * * * * |\n 0.6 ++ * * * * * * ++\n * * * * * * * |\n 0.4 +* * * * * * * ++\n |* * * * * * * |\n 0.2 +* * * * * * * ++\n | * * * * * * * |\n 0 ++* * * * * * *++\n | * * * * * * *|\n-0.2 ++ * * * * * * *+\n | * * * * * * *|\n-0.4 ++ * * * * * * *+\n | * * * * * * *\n-0.6 ++ * * * * * * ++\n | * * * * * * |\n-0.8 ++ * * * * * * ++\n + * * + * * + * * +\n -1 ++-----**---------+----------**----+---------------**+---------------++\n -10 -5 0 5 10\n" }, { "answer_id": 12868778, "author": "Xiong Chiamiov", "author_id": 120999, "author_profile": "https://Stackoverflow.com/users/120999", "pm_score": 6, "selected": false, "text": "gnuplot --- eplot.orig 2012-10-12 17:07:35.000000000 -0700\n+++ eplot 2012-10-12 17:09:06.000000000 -0700\n@@ -377,6 +377,7 @@\n # ---- print the options\n com=\"echo '\\n\"+getStyleString+@oc[\"MiscOptions\"]\n com=com+\"set multiplot;\\n\" if doMultiPlot\n+ com=com+\"set terminal dumb;\\n\"\n com=com+\"plot \"+@oc[\"Range\"]+comString+\"\\n'| gnuplot -persist\"\n printAndRun(com)\n # ---- convert to PDF\n [$]> git shortlog -s -n | awk '{print $1}' | eplot 2> /dev/null\n\n\n 3500 ++-------+-------+--------+--------+-------+--------+-------+-------++\n + + + \"/tmp/eplot20121012-19078-fw3txm-0\" ****** + * | 3000 +* ++ |* | | * | 2500 ++* ++ | * |\n | * |\n 2000 ++ * ++\n | ** |\n 1500 ++ **** ++\n | * |\n | ** |\n 1000 ++ * ++\n | * |\n | * |\n 500 ++ *** ++\n | ************** |\n + + + + ********** + + + +\n 0 ++-------+-------+--------+--------+-----***************************++\n 0 5 10 15 20 25 30 35 40\n" }, { "answer_id": 21319776, "author": "Xiong Chiamiov", "author_id": 120999, "author_profile": "https://Stackoverflow.com/users/120999", "pm_score": 5, "selected": false, "text": "[$]> git shortlog -s -n | awk '{print $1}' | hist\n\n 33| o\n 32| o\n 30| o\n 28| o\n 27| o\n 25| o\n 23| o\n 22| o\n 20| o\n 18| o\n 16| o\n 15| o\n 13| o\n 11| o\n 10| o\n 8| o\n 6| o\n 5| o\n 3| o o o\n 1| o o o o o\n 0| o o o o o o o\n ----------------------\n\n-----------------------\n| Summary |\n-----------------------\n| observations: 50 |\n| min value: 1.000000 |\n| mean : 519.140000 |\n|max value: 3207.000000|\n-----------------------\n [$]> git shortlog -s -n | awk '{print $1}' | hist --nosummary --bins=40\n\n 18| o\n | o\n 17| o\n 16| o\n 15| o\n 14| o\n 13| o\n 12| o\n 11| o\n 10| o\n 9| o\n 8| o\n 7| o\n 6| o\n 5| o o\n 4| o o o\n 3| o o o o o\n 2| o o o o o\n 1| o o o o o o o\n 0| o o o o o o o o o o o o o\n | o o o o o o o o o o o o o\n --------------------------------------------------------------------------------\n" }, { "answer_id": 27732634, "author": "denis", "author_id": 86643, "author_profile": "https://Stackoverflow.com/users/86643", "pm_score": 4, "selected": false, "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nimport numpy as np\n\n__version__ = \"2015-01-02 jan denis\"\n\n\n#...............................................................................\ndef onelineplot( x, chars=u\"▁▂▃▄▅▆▇█\", sep=\" \" ):\n \"\"\" numbers -> v simple one-line plots like\n\nf ▆ ▁ ▁ ▁ █ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ osc 47 ▄ ▁ █ ▇ ▄ ▆ ▅ ▇ ▇ ▇ ▇ ▇ ▄ ▃ ▃ ▁ ▃ ▂ rosenbrock\nf █ ▅ █ ▅ █ ▅ █ ▅ █ ▅ █ ▅ █ ▅ █ ▅ ▁ ▁ ▁ ▁ osc 58 ▂ ▁ ▃ ▂ ▄ ▃ ▅ ▄ ▆ ▅ ▇ ▆ █ ▇ ▇ ▃ ▃ ▇ rastrigin\nf █ █ █ █ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ osc 90 █ ▇ ▇ ▁ █ ▇ █ ▇ █ ▇ █ ▇ █ ▇ █ ▇ █ ▇ ackley\n\nUsage:\n astring = onelineplot( numbers [optional chars= sep= ])\nIn:\n x: a list / tuple / numpy 1d array of numbers\n chars: plot characters, default the 8 Unicode bars above\n sep: \"\" or \" \" between plot chars\n\nHow it works:\n linscale x -> ints 0 1 2 3 ... -> chars ▁ ▂ ▃ ▄ ...\n\nSee also: https://github.com/RedKrieg/pysparklines\n \"\"\"\n\n xlin = _linscale( x, to=[-.49, len(chars) - 1 + .49 ])\n # or quartiles 0 - 25 - 50 - 75 - 100\n xints = xlin.round().astype(int)\n assert xints.ndim == 1, xints.shape # todo: 2d\n return sep.join([ chars[j] for j in xints ])\n\n\ndef _linscale( x, from_=None, to=[0,1] ):\n \"\"\" scale x from_ -> to, default min, max -> 0, 1 \"\"\"\n x = np.asanyarray(x)\n m, M = from_ if from_ is not None \\\n else [np.nanmin(x), np.nanmax(x)]\n if m == M:\n return np.ones_like(x) * np.mean( to )\n return (x - m) * (to[1] - to[0]) \\\n / (M - m) + to[0]\n\n\n#...............................................................................\nif __name__ == \"__main__\": # standalone test --\n import sys\n\n if len(sys.argv) > 1: # numbers on the command line, may be $(cat myfile)\n x = map( float, sys.argv[1:] )\n else:\n np.random.seed( 0 )\n x = np.random.exponential( size=20 )\n\n print onelineplot( x )\n" }, { "answer_id": 28590211, "author": "mc0e", "author_id": 2109800, "author_profile": "https://Stackoverflow.com/users/2109800", "pm_score": 5, "selected": false, "text": " $ seq 5 | awk '{print 2*$1, $1*$1}' |\n feedgnuplot --lines --points --legend 0 \"data 0\" --title \"Test plot\" --y2 1 \\\n --terminal 'dumb 80,40' --exit\n\n Test plot\n\n 10 ++------+--------+-------+-------+-------+--------+-------+------*A 25\n + + + + + + + + **#+\n | : : : : : : data 0+**A*** |\n | : : : : : : :** # |\n 9 ++.......................................................**.##....|\n | : : : : : : ** :# |\n | : : : : : : ** # |\n | : : : : : :** ##: ++ 20\n 8 ++................................................A....#..........|\n | : : : : : **: # : |\n | : : : : : ** : ## : |\n | : : : : : ** :# : |\n | : : : : :** B : |\n 7 ++......................................**......##................|\n | : : : : ** : ## : : ++ 15\n | : : : : ** : # : : |\n | : : : :** : ## : : |\n 6 ++..............................*A.......##.......................|\n | : : : ** : ##: : : |\n | : : : ** : # : : : |\n | : : :** : ## : : : ++ 10\n 5 ++......................**........##..............................|\n | : : ** : #B : : : |\n | : : ** : ## : : : : |\n | : :** : ## : : : : |\n 4 ++...............A.......###......................................|\n | : **: ##: : : : : |\n | : ** : ## : : : : : ++ 5\n | : ** : ## : : : : : |\n | :** ##B# : : : : : |\n 3 ++.....**..####...................................................|\n | **#### : : : : : : |\n | **## : : : : : : : |\n B** + + + + + + + +\n 2 A+------+--------+-------+-------+-------+--------+-------+------++ 0\n 1 1.5 2 2.5 3 3.5 4 4.5 5\n sudo apt install feedgnuplot" }, { "answer_id": 42009770, "author": "Max Kosyakov", "author_id": 549915, "author_profile": "https://Stackoverflow.com/users/549915", "pm_score": 2, "selected": false, "text": "--- eplot 2008-07-09 16:50:04.000000000 -0400\n+++ eplot+ 2017-02-02 13:20:23.551353793 -0500\n@@ -172,7 +172,10 @@\n com=com+\"set terminal postscript color;\\n\"\n @o[\"DoPDF\"]=true\n\n- # ---- Specify a custom output file\n+ when /^-T$|^--terminal$/\n+ com=com+\"set terminal dumb;\\n\"\n+\n+ # ---- Specify a custom output file\n when /^-o$|^--output$/\n @o[\"OutputFileSpecified\"]=checkOptArg(xargv,i)\n i=i+1\n\n i=i+1\n eplot -T" }, { "answer_id": 66103402, "author": "Sankalp", "author_id": 1527814, "author_profile": "https://Stackoverflow.com/users/1527814", "pm_score": 2, "selected": false, "text": "ttyplot" }, { "answer_id": 67849079, "author": "Nico Schlömer", "author_id": 353337, "author_profile": "https://Stackoverflow.com/users/353337", "pm_score": 2, "selected": false, "text": "import termplotlib as tpl\nimport numpy\n\nx = numpy.linspace(0, 2 * numpy.pi, 10)\ny = numpy.sin(x)\n\nfig = tpl.figure()\nfig.plot(x, y, label=\"data\", width=50, height=15)\nfig.show()\n 1 +---------------------------------------+\n 0.8 | ** ** |\n 0.6 | * ** data ******* |\n 0.4 | ** |\n 0.2 |* ** |\n 0 | ** |\n | * |\n -0.2 | ** ** |\n -0.4 | ** * |\n -0.6 | ** |\n -0.8 | **** ** |\n -1 +---------------------------------------+\n 0 1 2 3 4 5 6 7\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21339/" ]
123,387
<p>we're have a client that needs to get interactive messages from a server, from clients that are distributed around the world behind all kinds of firewalls with all kinds of ports closed. The only thing we can rely on is HTTP port 80 (and HTTPS 443).</p> <p>The design is basically modeled after XMPP (the Jabber protocol), using our client and IIS. The client issues GET requests to a .NET Handler; the handler holds the request open for a while looking for messages. If any messages arrive, they are immediately sent to the client; if not, after a timeout the connection is closed with a "no-data" response. The client immediately reopens the communication.</p> <p>Well, theoretically.</p> <p>What's actually happening is first, IIS can't handle more than about 100 simultaneous requests - others are all queued, and there can be a several minute lag between "connected" and IIS recognizing that the client called in. Second, about half the time the client times out without any response from the server (the client timeout is five minutes longer than the server's).</p> <p>POST always works. Other data served on the same web server works. Web services on the same server work. This is an out-of-the-box installation on Windows 2K3 Server.</p> <p>Is there a configuration option we're missing, or is there something else I should look at to address this?</p> <p>Thanks.</p>
[ { "answer_id": 136797, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 3, "selected": true, "text": "IHttpAsyncHandler" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22809/" ]
123,391
<p>I would like to know how to unload an assembly that is loaded into the main AppDomain.</p> <p>I have the following code:</p> <pre><code>var assembly = Assembly.LoadFrom( FilePathHere ); </code></pre> <p>I need/want to be able to unload this assembly when I am done.</p> <p>Thanks for your help.</p>
[ { "answer_id": 123465, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 3, "selected": false, "text": "DynamicMethod" }, { "answer_id": 666312, "author": "Nipun", "author_id": 79323, "author_profile": "https://Stackoverflow.com/users/79323", "pm_score": 4, "selected": false, "text": "AppDomain AppDomain" }, { "answer_id": 34077090, "author": "Kirk Herron", "author_id": 5637076, "author_profile": "https://Stackoverflow.com/users/5637076", "pm_score": 5, "selected": false, "text": "var assembly = Assembly.LoadFrom( FilePathHere );\n var assembly = Assembly.Load( File.ReadAllBytes(FilePathHere));\n assembly = null;\n" }, { "answer_id": 49155123, "author": "Gerrie Pretorius", "author_id": 505558, "author_profile": "https://Stackoverflow.com/users/505558", "pm_score": 0, "selected": false, "text": "AssemblyName an = AssemblyName.GetAssemblyName (\"myfile.exe\");\nbyte[] publicKey = an.GetPublicKey();\nCultureInfo culture = an.CultureInfo;\nVersion version = an.Version;\n Assembly.ReflectionOnlyLoadFrom public void AssemblyLoadTest(string assemblyToLoad)\n{\n var initialAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //4\n\n Assembly.ReflectionOnlyLoad(assemblyToLoad);\n var reflectionOnlyAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //4\n\n //Shows that assembly is NOT loaded in to AppDomain with Assembly.ReflectionOnlyLoad\n Assert.AreEqual(initialAppDomainAssemblyCount, reflectionOnlyAppDomainAssemblyCount); // 4 == 4\n\n Assembly.Load(assemblyToLoad);\n var loadAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //5\n\n //Shows that assembly is loaded in to AppDomain with Assembly.Load\n Assert.AreNotEqual(initialAppDomainAssemblyCount, loadAppDomainAssemblyCount); // 4 != 5\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14164/" ]
123,394
<p>I know I can do this:</p> <pre><code>IDateTimeFactory dtf = MockRepository.GenerateStub&lt;IDateTimeFactory&gt;(); dtf.Now = new DateTime(); DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value dtf.Now = new DateTime()+new TimeSpan(0,1,0); // 1 minute later DoStuff(dtf); //ditto from above </code></pre> <p>What if instead of <strong>IDateTimeFactory.Now</strong> being a property it is a method <strong>IDateTimeFactory.GetNow()</strong>, how do I do the same thing?</p> <p>As per Judah's suggestion below I have rewritten my SetDateTime helper method as follows:</p> <pre><code> private void SetDateTime(DateTime dt) { Expect.Call(_now_factory.GetNow()).Repeat.Any(); LastCall.Do((Func&lt;DateTime&gt;)delegate() { return dt; }); } </code></pre> <p>but it still throws "The result for ICurrentDateTimeFactory.GetNow(); has already been setup." errors.</p> <p>Plus its still not going to work with a stub....</p>
[ { "answer_id": 123515, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 0, "selected": false, "text": "using (mocks.Record())\n{\n Expect.Call(s.GetSomething()).Return(\"ABC\"); // 1st call will return ABC\n Expect.Call(s.GetSomething()).Return(\"XYZ\"); // 2nd call will return XYZ\n}\nusing (mocks.Playback())\n{\n DoStuff(s);\n DoStuff(s);\n}\n" }, { "answer_id": 123736, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 0, "selected": false, "text": "bool shouldReturnABC = true;\nusing (mocks.Record())\n{\n Expect.Call(s.GetSomething()).Repeat.Any();\n\n LastCall.Do((Func<string>)delegate()\n {\n return shouldReturnABC ? \"ABC\" : \"XYZ\";\n }\n}\nusing (mocks.Playback())\n{\n DoStuff(s);\n shouldReturnABC = false;\n DoStuff(s);\n}\n" }, { "answer_id": 124158, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 2, "selected": true, "text": "MockRepository mocks = new MockRepository();\n\n[Test]\npublic void Test()\n{\n IDateTimeFactory dtf = mocks.DynamicMock<IDateTimeFactory>();\n\n DateTime desiredNowTime = DateTime.Now;\n using (mocks.Record())\n {\n SetupResult.For(dtf.GetNow()).Do((Func<DateTime>)delegate { return desiredNowTime; });\n }\n using (mocks.Playback())\n {\n DoStuff(dtf); // Prints the current time \n desiredNowTime += TimeSpan.FromMinutes(1); // 1 minute later \n DoStuff(dtf); // Prints the time 1 minute from now\n }\n}\n\nvoid DoStuff(IDateTimeFactory factory)\n{\n DateTime time = factory.GetNow();\n Console.WriteLine(time);\n}\n" }, { "answer_id": 4904265, "author": "David Tchepak", "author_id": 906, "author_profile": "https://Stackoverflow.com/users/906", "pm_score": 3, "selected": false, "text": " [Test]\n public void TestDoStuff()\n {\n var now = DateTime.Now;\n var dtf = MockRepository.GenerateStub<IDateTimeFactory>();\n dtf\n .Stub(x => x.GetNow())\n .Return(default(DateTime)) //need to set a dummy return value\n .WhenCalled(x => x.ReturnValue = now); //close over the now variable\n\n DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value\n now = now + new TimeSpan(0, 1, 0); // 1 minute later\n DoStuff(dtf); //ditto from above\n }\n\n private void DoStuff(IDateTimeFactory dtf)\n {\n Console.WriteLine(dtf.GetNow());\n }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
123,401
<p>Using jQuery, how do you bind a click event to a table cell (below, <code>class="expand"</code>) that will change the <code>image src</code> (which is in the clicked cell - original will be plus.gif, alternating with minus.gif) and <code>hide/show</code> the row immediately below it based on whether that row has a class of <code>hide</code>. (show it if it has a class of "hide" and hide if it does not have a class of "hide"). I am flexible with changing ids and classes in the markup.</p> <p>Thanks</p> <p>Table rows</p> <pre><code>&lt;tr&gt; &lt;td class="expand"&gt;&lt;img src="plus.gif"/&gt;&lt;/td&gt; &lt;td&gt;Data1&lt;/td&gt;&lt;td&gt;Data2&lt;/td&gt;&lt;td&gt;Data3&lt;/td&gt; &lt;/tr&gt; &lt;tr class="show hide"&gt; &lt;td&gt; &lt;/td&gt; &lt;td&gt;Data4&lt;/td&gt;&lt;td&gt;Data5&lt;/td&gt;&lt;td&gt;Data6&lt;/td&gt; &lt;/tr&gt; </code></pre>
[ { "answer_id": 123518, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 5, "selected": true, "text": "$(document).ready(function(){ \n $('.expand').click(function() {\n if( $(this).hasClass('hidden') )\n $('img', this).attr(\"src\", \"plus.jpg\");\n else \n $('img', this).attr(\"src\", \"minus.jpg\");\n\n $(this).toggleClass('hidden');\n $(this).parent().next().toggle();\n });\n});\n" }, { "answer_id": 123525, "author": "Brad8118", "author_id": 7617, "author_profile": "https://Stackoverflow.com/users/7617", "pm_score": -1, "selected": false, "text": "<tr>\n\n<td colspan=\"2\" align=\"center\"\n<input type=\"image\" src=\"save.gif\" id=\"saveButton\" name=\"saveButton\"\n style=\"visibility: collapse; display: none\" \n onclick=\"ToggleFunction(false)\"/>\n\n<input type=\"image\" src=\"saveDisabled.jpg\" id=\"saveButtonDisabled\" \n name=\"saveButton\" style=\"visibility: collapse; display: inline\"\n onclick=\"ToggleFunction(true)\"/>\n</td>\n</tr>\n onClick ToggleFunction(seeSaveButton){ \n if(seeSaveButton){\n $(\"#saveButton\").attr(\"disabled\", true)\n .attr(\"style\", \"visibility: collapse; display: none;\");\n $(\"#saveButtonDisabled\").attr(\"disabled\", true)\n .attr(\"style\", \"display: inline;\");\n } \n else { \n $(\"#saveButton\").attr(\"disabled\", false)\n .attr(\"style\", \"display: inline;\");\n $(\"#saveButtonDisabled\")\n .attr(\"disabled\", true)\n .attr(\"style\", \"visibility: collapse; display: none;\");\n }\n}\n" }, { "answer_id": 123669, "author": "jckeyes", "author_id": 17881, "author_profile": "https://Stackoverflow.com/users/17881", "pm_score": 1, "selected": false, "text": "//this will bind the click event\n//put this in a $(document).ready or something\n$(\".expand\").click(expand_ClickEvent);\n\n//this is your event handler\nfunction expand_ClickEvent(){\n //get the TR that you want to show/hide\n var TR = $('.expand').parent().next();\n\n //check its class\n if (TR.hasClass('hide')){\n TR.removeClass('hide'); //remove the hide class\n TR.addClass('show'); //change it to the show class\n TR.show(); //show the TR (you can use any jquery animation)\n\n //change the image URL\n //select the expand class and the img in it, then change its src attribute\n $('.expand img').attr('src', 'minus.gif');\n } else {\n TR.removeClass('show'); //remove the show class\n TR.addClass('hide'); //change it to the hide class\n TR.hide(); //hide the TR (you can use any jquery animation)\n\n //change the image URL\n //select the expand class and the img in it, then change its src attribute\n $('.expand img').attr('src', 'plus.gif');\n }\n}\n" }, { "answer_id": 123844, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 3, "selected": false, "text": "$(document).ready( function () {\n $(\".expand\").click(function() {\n $(\"img\",this).attr(\"src\", \n $(\"img\",this)\n .attr(\"src\")==\"minus.gif\" ? \"plus.gif\" : \"minus.gif\"\n );\n $(this).parent().next().toggle();\n });\n});\n" }, { "answer_id": 10089195, "author": "PCasagrande", "author_id": 624089, "author_profile": "https://Stackoverflow.com/users/624089", "pm_score": 2, "selected": false, "text": "$(document).ready(function() {\n $('.expandButton').click(function() {\n $(this).closest('tr').next('tr.expandable').fadeToggle();\n });\n});\n fadeToggle()" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
123,480
<p>We are using Zabbix for services monitoring.</p> <p>There are some essential monitoring configured. I want to have timeline of version strings of my service along with this monitorings. That would give me opportunity to see that upgrading to this version altered overall error-count.</p> <p>Is it possible? </p>
[ { "answer_id": 395338, "author": "James Cape", "author_id": 41044, "author_profile": "https://Stackoverflow.com/users/41044", "pm_score": 0, "selected": false, "text": "zabbix_agentd.conf zabbix_agent.conf zabbix_server.conf" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/844/" ]
123,489
<p>I am using REPLACE in an SQL view to remove the spaces from a property number. The function is setup like this REPLACE(pin, ' ', ''). On the green-screen the query looked fine. In anything else we get the hex values of the characters in the field. I am sure it is an encoding thing, but how do I fix it?</p> <p>Here is the statement I used to create the view:</p> <pre><code>CREATE VIEW RLIC2GIS AS SELECT REPLACE(RCAPIN, ' ', '') AS RCAPIN13 , RLICNO, RONAME, ROADR1, ROADR2, ROCITY, ROSTAT, ROZIP1, ROZIP2, RGRID, RRADR1, RRADR2, RANAME, RAADR1, RAADR2, RACITY, RASTAT, RAZIP1, RAZIP2, REGRES, RPENDI, RBLDGT, ROWNOC, RRCODE, RROOMS, RUNITS, RTUNIT, RPAID, RAMTPD, RMDYPD, RRFUSE, RNUMCP, RDATCP, RINSP, RCAUKY, RCAPIN, RAMTYR, RYREXP, RDELET, RVARIA, RMDYIN, RDTLKI, ROPHN1, ROPHN2, ROCOM1, ROCOM2, RAPHN1, RAPHN2, RACOM1, RACOM2, RNOTES FROM RLIC2 </code></pre> <p>UPDATE: I posted the answer below.</p>
[ { "answer_id": 123784, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 3, "selected": true, "text": "CREATE VIEW RLIC2GIS AS \nSELECT CONCAT(SUBSTR(RCAPIN,1,3),CONCAT(SUBSTR(RCAPIN,5,2), \nCONCAT(SUBSTR(RCAPIN,8,2), CONCAT(SUBSTR(RCAPIN,11,3), \nSUBSTR(RCAPIN, 15,3))))) AS CAPIN13, RLICNO, RONAME, ROADR1, \nROADR2, ROCITY, ROSTAT, ROZIP1, ROZIP2, RGRID, RRADR1, RRADR2, \nRANAME, RAADR1, RAADR2, RACITY, RASTAT, RAZIP1, RAZIP2, REGRES, \nRPENDI, RBLDGT, ROWNOC, RRCODE, RROOMS, RUNITS, RTUNIT, RPAID, \nRAMTPD, RMDYPD, RRFUSE, RNUMCP, RDATCP, RINSP, RCAUKY, RCAPIN, \nRAMTYR, RYREXP, RDELET, RVARIA, RMDYIN, RDTLKI, ROPHN1, ROPHN2, \nROCOM1, ROCOM2, RAPHN1, RAPHN2, RACOM1, RACOM2, RNOTES FROM RLIC2\n" }, { "answer_id": 124163, "author": "IK.", "author_id": 21283, "author_profile": "https://Stackoverflow.com/users/21283", "pm_score": 1, "selected": false, "text": "SELECT ascii(substr(RCAPIN,4,1)) \nFROM YOUR-TABLE\n SELECT replace(RCAPIN,chr(9))\nFROM YOUR-TABLE\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
123,499
<p>I've got the directive</p> <pre><code>&lt;VirtualHost *&gt; &lt;Location /&gt; AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users &lt;Limit GET&gt; Require valid-user &lt;/Limit&gt; &lt;/Location&gt; WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some.example.org &lt;/VirtualHost&gt; </code></pre> <p>I'd like to know in the /some/script.wsgi</p> <pre><code>def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/plain'), ]) return ['Hello'] </code></pre> <p>What user is logged in.</p> <p>How do I do that?</p>
[ { "answer_id": 123526, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 5, "selected": true, "text": "WSGIPassAuthorization On <VirtualHost *>\n <Location />\n AuthType Digest\n AuthName \"global\"\n AuthDigestDomain /\n AuthUserFile /root/apache_users\n <Limit GET>\n Require valid-user\n </Limit>\n </Location>\n WSGIPassAuthorization On\n WSGIScriptAlias / /some/script.wsgi\n WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25\n WSGIProcessGroup mywsgi\n ServerName some.example.org\n</VirtualHost>\n environ['REMOTE_USER'] def application(environ, start_response):\n start_response('200 OK', [\n ('Content-Type', 'text/plain'),\n ])\n return ['Hello %s' % environ['REMOTE_USER']]\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19435/" ]
123,503
<p>I'm writing an iPhone app with Cocoa in xcode. I can't find any tutorials or sample code that shows how to take photos with the built in camera. How do I do this? Where can I find good info?</p> <p>Thanks!</p>
[ { "answer_id": 123590, "author": "jblocksom", "author_id": 20626, "author_profile": "https://Stackoverflow.com/users/20626", "pm_score": 2, "selected": false, "text": "UIImagePickerController UIImagePickerControllerSourceTypeCamera" }, { "answer_id": 127155, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 4, "selected": false, "text": "UIImagePickerController UIImagePickerControllerSourceTypeCamera UIImagePickerControllerSourceTypePhotoLibrary UIImagePickerController UINavigationController" }, { "answer_id": 12381839, "author": "W.S", "author_id": 1202271, "author_profile": "https://Stackoverflow.com/users/1202271", "pm_score": 5, "selected": false, "text": " -(IBAction)takePhoto :(id)sender\n\n{\n UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];\n\n if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])\n {\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];\n }\n\n // image picker needs a delegate,\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentModalViewController:imagePickerController animated:YES];\n}\n\n\n\n-(IBAction)chooseFromLibrary:(id)sender\n{\n\n UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; \n [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];\n\n // image picker needs a delegate so we can respond to its messages\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentModalViewController:imagePickerController animated:YES];\n\n}\n\n//delegate methode will be called after picking photo either from camera or library\n- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{ \n [self dismissModalViewControllerAnimated:YES]; \n UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];\n\n [myImageView setImage:image]; // \"myImageView\" name of any UIImageView.\n}\n" }, { "answer_id": 22013944, "author": "Prince Agrawal", "author_id": 1952610, "author_profile": "https://Stackoverflow.com/users/1952610", "pm_score": 1, "selected": false, "text": "-(void)takePhoto\n{\n UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];\n\n if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])\n {\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];\n }\n\n // image picker needs a delegate,\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentViewController:imagePickerController animated:YES completion:nil];\n}\n\n\n\n-(void)chooseFromLibrary\n{\n\n UIImagePickerController *imagePickerController= [[UIImagePickerController alloc]init];\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];\n\n // image picker needs a delegate so we can respond to its messages\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentViewController:imagePickerController animated:YES completion:nil];\n\n}\n\n//delegate methode will be called after picking photo either from camera or library\n- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{\n [self dismissViewControllerAnimated:YES completion:nil];\n UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];\n\n[myImageView setImage:image]; // \"myImageView\" name of any UImageView.\n}\n view controller.h @interface myVC<UINavigationControllerDelegate, UIImagePickerControllerDelegate>\n" }, { "answer_id": 26244292, "author": "Sabrina Tuli", "author_id": 3854617, "author_profile": "https://Stackoverflow.com/users/3854617", "pm_score": 0, "selected": false, "text": "- (IBAction)takephoto:(id)sender {\n\n picker = [[UIImagePickerController alloc] init];\n picker.delegate = self;\n [picker setSourceType:UIImagePickerControllerSourceTypeCamera];\n [self presentViewController:picker animated:YES completion:NULL];\n\n\n}\n-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{\n img = [info objectForKey:@\"UIImagePickerControllerOriginalImage\"];\n [imageview setImage:img];\n [self dismissViewControllerAnimated:YES completion:NULL];\n}\n -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker\n{\n [self dismissViewControllerAnimated:YES completion:NULL];\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
123,504
<p>In wxWidgets, how can you find the pixels per inch on a wxDC? I'd like to be able to scale things by a real world number like inches. That often makes it easier to use the same code for printing to the screen and the printer.</p>
[ { "answer_id": 123590, "author": "jblocksom", "author_id": 20626, "author_profile": "https://Stackoverflow.com/users/20626", "pm_score": 2, "selected": false, "text": "UIImagePickerController UIImagePickerControllerSourceTypeCamera" }, { "answer_id": 127155, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 4, "selected": false, "text": "UIImagePickerController UIImagePickerControllerSourceTypeCamera UIImagePickerControllerSourceTypePhotoLibrary UIImagePickerController UINavigationController" }, { "answer_id": 12381839, "author": "W.S", "author_id": 1202271, "author_profile": "https://Stackoverflow.com/users/1202271", "pm_score": 5, "selected": false, "text": " -(IBAction)takePhoto :(id)sender\n\n{\n UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];\n\n if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])\n {\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];\n }\n\n // image picker needs a delegate,\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentModalViewController:imagePickerController animated:YES];\n}\n\n\n\n-(IBAction)chooseFromLibrary:(id)sender\n{\n\n UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; \n [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];\n\n // image picker needs a delegate so we can respond to its messages\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentModalViewController:imagePickerController animated:YES];\n\n}\n\n//delegate methode will be called after picking photo either from camera or library\n- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{ \n [self dismissModalViewControllerAnimated:YES]; \n UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];\n\n [myImageView setImage:image]; // \"myImageView\" name of any UIImageView.\n}\n" }, { "answer_id": 22013944, "author": "Prince Agrawal", "author_id": 1952610, "author_profile": "https://Stackoverflow.com/users/1952610", "pm_score": 1, "selected": false, "text": "-(void)takePhoto\n{\n UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];\n\n if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])\n {\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];\n }\n\n // image picker needs a delegate,\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentViewController:imagePickerController animated:YES completion:nil];\n}\n\n\n\n-(void)chooseFromLibrary\n{\n\n UIImagePickerController *imagePickerController= [[UIImagePickerController alloc]init];\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];\n\n // image picker needs a delegate so we can respond to its messages\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentViewController:imagePickerController animated:YES completion:nil];\n\n}\n\n//delegate methode will be called after picking photo either from camera or library\n- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{\n [self dismissViewControllerAnimated:YES completion:nil];\n UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];\n\n[myImageView setImage:image]; // \"myImageView\" name of any UImageView.\n}\n view controller.h @interface myVC<UINavigationControllerDelegate, UIImagePickerControllerDelegate>\n" }, { "answer_id": 26244292, "author": "Sabrina Tuli", "author_id": 3854617, "author_profile": "https://Stackoverflow.com/users/3854617", "pm_score": 0, "selected": false, "text": "- (IBAction)takephoto:(id)sender {\n\n picker = [[UIImagePickerController alloc] init];\n picker.delegate = self;\n [picker setSourceType:UIImagePickerControllerSourceTypeCamera];\n [self presentViewController:picker animated:YES completion:NULL];\n\n\n}\n-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{\n img = [info objectForKey:@\"UIImagePickerControllerOriginalImage\"];\n [imageview setImage:img];\n [self dismissViewControllerAnimated:YES completion:NULL];\n}\n -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker\n{\n [self dismissViewControllerAnimated:YES completion:NULL];\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
123,506
<p>I have a ASP.NET application running on a remote web server and I just started getting this error:</p> <pre><code>Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'. </code></pre> <p>I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:</p> <pre><code>Set&lt;int&gt; set = new Set&lt;int&gt;(); </code></pre> <p>Is compiled into this line:</p> <pre><code>Set&lt;int&gt; set = (Set&lt;int&gt;) new ICollection&lt;CalendarModule&gt;(); </code></pre> <p>The CalendarModule class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?</p> <p><strong>Update #1:</strong> This problem seems to be introduced by Microsoft's <a href="http://research.microsoft.com/~mbarnett/ILMerge.aspx" rel="nofollow noreferrer">ILMerge</a> tool. We are currently investigating how to overcome it.</p> <p><strong>Update #2:</strong> We found two ways to solve this problem so far. We don't quite understand what the underlying problem is, but both of these fix it:</p> <ol> <li><p>Turn off optimization.</p></li> <li><p>Merge the assemblie with ILMerge on a different machine.</p></li> </ol> <p>So we are left wondering if the build machine is misconfigured somehow (which is strange considering that we have been using the machine to build releases for over a year now) or if it is some other problem.</p>
[ { "answer_id": 123607, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 1, "selected": false, "text": "System.Collections.Generic.HashSet<T> Set<>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10475/" ]
123,529
<p>A site I'm working on has Flash headers (using <a href="http://code.google.com/p/swfobject/" rel="noreferrer">swfobject</a> to embed them). Now I'm required to code in a bit of HTML that's supposed to overlap the Flash movie.</p> <p>I've tried setting z-index on the Flash element's container and the (absolutely positioned) div but it keeps "vanishing" behind the Flash movie. </p> <p>I'm hoping for a CSS solution, but if there's a bit of JS magic that will do the trick, I'm up for it.</p> <p><strong>Update:</strong> Thanks, setting wmode to "transparent" mostly fixed it. Only Safari/Mac still hid the div behind the flash on first show. When I'd switch to another app and back it would be in front. I was able to fix this by setting the div's initial styles to <code>display: none;</code> and make it visible via JS half a second after the page has loaded.</p>
[ { "answer_id": 397349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "s1.addParam(\"wmode\",\"transparent\");\n style=\"z-index:inherit; \n" }, { "answer_id": 6933950, "author": "Nassim Chikh", "author_id": 877526, "author_profile": "https://Stackoverflow.com/users/877526", "pm_score": 1, "selected": false, "text": "OBJECT EMBED" }, { "answer_id": 24228097, "author": "Khadka Pushpendra", "author_id": 2318637, "author_profile": "https://Stackoverflow.com/users/2318637", "pm_score": 1, "selected": false, "text": "<object id='myId' width='700' height='500'>\n <param name='movie' value='images/ann/$imagename' />\n <param name='wmode' value='transparent' />\n <!--[if !IE]>-->\n <object type='application/x-shockwave-flash' data='images/ann/$imagename' width='700' height='500' wmode='transparent'>\n <!--<![endif]-->\n <div>\n <h1>Please download flash player</h1>\n <p><a href='http://www.adobe.com/go/getflashplayer'><img src='http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a></p>\n </div>\n <!--[if !IE]>-->\n </object>\n <!--<![endif]-->\n </object>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9438/" ]
123,557
<p>I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 step?</p>
[ { "answer_id": 123644, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 8, "selected": true, "text": "SELECT *, IDENTITY( int ) AS idcol\n INTO #newtable\n FROM oldtable\n" }, { "answer_id": 123735, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "ALTER TABLE #mytable\nADD PRIMARY KEY(KeyColumn)\n CREATE #myTable TABLE DECLARE TABLE @myTable IDENTITY PRIMARY KEY" }, { "answer_id": 123881, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 3, "selected": false, "text": "create table oldtable (id int not null identity(1,1), v varchar(10) )\n\nselect * into #newtable from oldtable\n\nuse tempdb\nGO\nsp_help #newtable\n select id + 1 - 1 as nid, v, IDENTITY( int ) as id into #newtable\n from oldtable\n" }, { "answer_id": 757666, "author": "Catto", "author_id": 17877, "author_profile": "https://Stackoverflow.com/users/17877", "pm_score": 2, "selected": false, "text": "SELECT col1, col2, IDENTITY( int ) AS idcol\nINTO #newtable\nFROM oldtable\n CREATE TABLE [dbo].[oldtable]\n(\n [oldtableID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,\n [col1] [nvarchar](50) NULL,\n [col2] [numeric](18, 0) NULL,\n)\n" }, { "answer_id": 1986493, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "select cast (CurrentID as int) as CurrentID, SomeOtherField, identity(int) as TempID \ninto #temp\nfrom myserver.dbo.mytable\n" }, { "answer_id": 19287109, "author": "RichM", "author_id": 2865461, "author_profile": "https://Stackoverflow.com/users/2865461", "pm_score": 0, "selected": false, "text": "select IDENTITY( int ) as TempID, *, SectionID as Fix2IDs\ninto #TempSections\nfrom Files_Sections\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19305/" ]
123,558
<p>Is it possible to disable a trigger for a batch of commands and then enable it when the batch is done?</p> <p>I'm sure I could drop the trigger and re-add it but I was wondering if there was another way.</p>
[ { "answer_id": 123566, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 7, "selected": true, "text": "DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }\nON { object_name | DATABASE | ALL SERVER } [ ; ]\n ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }\nON { object_name | DATABASE | ALL SERVER } [ ; ]\n" }, { "answer_id": 123966, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 5, "selected": false, "text": "sp_msforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"\nsp_msforeachtable \"ALTER TABLE ? DISABLE TRIGGER all\"\n exec sp_msforeachtable @command1=\"print '?'\", @command2=\"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\"\nsp_msforeachtable @command1=\"print '?'\", @command2=\"ALTER TABLE ? ENABLE TRIGGER all\"\n" }, { "answer_id": 17462589, "author": "Daniel Imms", "author_id": 1156119, "author_profile": "https://Stackoverflow.com/users/1156119", "pm_score": 4, "selected": false, "text": "USE AdventureWorks;\nGO\nDISABLE TRIGGER Person.uAddress ON Person.Address;\nGO\nENABLE Trigger Person.uAddress ON Person.Address;\nGO\n" }, { "answer_id": 19148678, "author": "crokusek", "author_id": 538763, "author_profile": "https://Stackoverflow.com/users/538763", "pm_score": 3, "selected": false, "text": "create trigger [SomeSchema].[SomeTableIsEditableTrigger] ON [SomeSchema].[SomeTable]\nfor insert, update, delete \nas\ndeclare\n @isTableTriggerEnabled bit;\n\nexec usp_IsTableTriggerEnabled -- Have to use USP instead of UFN for access to #temp\n @pTriggerProcedureIdOpt = @@procid, \n @poIsTableTriggerEnabled = @isTableTriggerEnabled out;\n\nif (@isTableTriggerEnabled = 0)\n return;\n\n-- Rest of existing trigger\ngo\n create proc [usp_IsTableTriggerEnabled]\n @pTriggerProcedureIdOpt bigint = null, -- Either provide this\n @pTableNameOpt varchar(300) = null, -- or this\n @poIsTableTriggerEnabled bit = null out\nbegin\n\n set @poIsTableTriggerEnabled = 1; -- default return value (ensure not null)\n\n -- Allow a particular session to disable all triggers (since local \n -- temp tables are session scope limited).\n --\n if (object_id('tempdb..#Common_DisableTableTriggers') is not null)\n begin\n set @poIsTableTriggerEnabled = 0;\n return;\n end\n\n -- Resolve table name if given trigger procedure id instead of table name.\n -- Google: \"How to get the table name in the trigger definition\"\n --\n set @pTableNameOpt = coalesce(\n @pTableNameOpt, \n (select object_schema_name(parent_id) + '.' + object_name(parent_id) as tablename \n from sys.triggers \n where object_id = @pTriggerProcedureIdOpt)\n );\n\n -- Else decide based on logic involving @pTableNameOpt and possibly current session\nend\n select 1 as A into #Common_DisableTableTriggers;\n-- do work \ndrop table #Common_DisableTableTriggers; -- or close connection\n" }, { "answer_id": 39035649, "author": "ABHISHEK GANGULY", "author_id": 6734262, "author_profile": "https://Stackoverflow.com/users/6734262", "pm_score": 2, "selected": false, "text": "ALTER TABLE table_name DISABLE TRIGGER TRIGGER_NAME\n-- Here your SQL query\nALTER TABLE table_name ENABLE TRIGGER TRIGGER_NAME\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4068/" ]
123,559
<p>I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following:</p> <ul> <li><code>1-234-567-8901</code></li> <li><code>1-234-567-8901 x1234</code></li> <li><code>1-234-567-8901 ext1234</code></li> <li><code>1 (234) 567-8901</code></li> <li><code>1.234.567.8901</code></li> <li><code>1/234/567/8901</code></li> <li><code>12345678901</code></li> </ul> <p>I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.</p>
[ { "answer_id": 123565, "author": "Nicholas Trandem", "author_id": 765, "author_profile": "https://Stackoverflow.com/users/765", "pm_score": 4, "selected": false, "text": "^\\d?(?:(?:[\\+]?(?:[\\d]{1,3}(?:[ ]+|[\\-.])))?[(]?(?:[\\d]{3})[\\-/)]?(?:[ ]+)?)?(?:[a-zA-Z2-9][a-zA-Z0-9 \\-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\\.]?)){1,2}(?:[\\d]{1,5}))?$\n" }, { "answer_id": 123666, "author": "Justin R.", "author_id": 4593, "author_profile": "https://Stackoverflow.com/users/4593", "pm_score": 8, "selected": false, "text": "^(?:(?:\\+?1\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?$\n" }, { "answer_id": 123681, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 10, "selected": true, "text": "+44 (0) ... (0) 12345678901\n 12345678901x1234\n 345678901x1234\n 12344678901\n 12345678901\n 12345678901\n 12345678901\n +4112345678\n +441234567890\n 1 (234) 567-8901\n 1 (234) 567-8901 x1234\n" }, { "answer_id": 124179, "author": "indiv", "author_id": 19719, "author_profile": "https://Stackoverflow.com/users/19719", "pm_score": 6, "selected": false, "text": "1?\\W*([2-9][0-8][0-9])\\W*([2-9][0-9]{2})\\W*([0-9]{4})(\\se?x?t?(\\d*))?\n #!/usr/bin/perl\n\nmy $us_phone_regex =\n '1?\\W*([2-9][0-8][0-9])\\W*([2-9][0-9]{2})\\W*([0-9]{4})(\\se?x?t?(\\d*))?';\n\n\nmy @tests =\n(\n\"1-234-567-8901\",\n\"1-234-567-8901 x1234\",\n\"1-234-567-8901 ext1234\",\n\"1 (234) 567-8901\",\n\"1.234.567.8901\",\n\"1/234/567/8901\",\n\"12345678901\",\n\"not a phone number\"\n);\n\nforeach my $num (@tests)\n{\n if( $num =~ m/$us_phone_regex/ )\n {\n print \"match [$1-$2-$3]\\n\" if not defined $4;\n print \"match [$1-$2-$3 $5]\\n\" if defined $4;\n }\n else\n {\n print \"no match [$num]\\n\";\n }\n}\n\n#\n# Extract all phone numbers from an arbitrary file.\n#\nmy $external_filename =\n 'http://web.textfiles.com/ezines/PHREAKSANDGEEKS/PnG-spring05.txt';\nmy @external_file = `curl $external_filename`;\nforeach my $line (@external_file)\n{\n if( $line =~ m/$us_phone_regex/ )\n {\n print \"match $1 $2 $3\\n\";\n }\n}\n '1?\\s*\\W?\\s*([2-9][0-8][0-9])\\s*\\W?\\s*([2-9][0-9]{2})\\s*\\W?\\s*([0-9]{4})(\\se?x?t?(\\d*))?';\n" }, { "answer_id": 124456, "author": "piCookie", "author_id": 8763, "author_profile": "https://Stackoverflow.com/users/8763", "pm_score": 2, "selected": false, "text": "@f = /(\\d+)/g;\ntr/0-9//dc;\n" }, { "answer_id": 737464, "author": "ron0", "author_id": 89431, "author_profile": "https://Stackoverflow.com/users/89431", "pm_score": 4, "selected": false, "text": "^((((\\(\\d{3}\\))|(\\d{3}-))\\d{3}-\\d{4})|(\\+?\\d{2}((-| )\\d{1,8}){1,5}))(( x| ext)\\d{1,5}){0,1}$\n (xxx)xxx-xxxx (xxx)-xxx-xxxx (xxx)xxx-xxxx x123 12 1234 123 1 x1111 12 12 12 12 12 12 1 1234 123456 x12345 +12 1234 1234 +12 12 12 1234 +12 1234 5678 +12 12345678" }, { "answer_id": 1158718, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "012345678x5 \\d+ ?\\w{0,9} ?\\d+\n 01234467 extension 123456 01234567x123456 01234567890" }, { "answer_id": 1158772, "author": "rooskie", "author_id": 49704, "author_profile": "https://Stackoverflow.com/users/49704", "pm_score": 3, "selected": false, "text": " $replace = array( ' ', '-', '/', '(', ')', ',', '.' ); //etc; as needed\n preg_match( '/1?[0-9]{10}((ext|x)[0-9]{1,4})?/i', str_replace( $replace, '', $phone_num );\n" }, { "answer_id": 1245990, "author": "Dave Kirby", "author_id": 152635, "author_profile": "https://Stackoverflow.com/users/152635", "pm_score": 8, "selected": false, "text": ".*\n \"123 456 7890 until 6pm, then 098 765 4321\" \n\"123 456 7890 or try my mobile on 098 765 4321\" \n\"ex-directory - mind your own business\"\n" }, { "answer_id": 2487795, "author": "Ben Clifford", "author_id": 269515, "author_profile": "https://Stackoverflow.com/users/269515", "pm_score": 5, "selected": false, "text": "() +44 (0) 1234 567890 +441234567890 01234567890" }, { "answer_id": 4597742, "author": "Chris", "author_id": 563053, "author_profile": "https://Stackoverflow.com/users/563053", "pm_score": 2, "selected": false, "text": "<?php\n/*\nstring validate_telephone_number (string $number, array $formats)\n*/\n\nfunction validate_telephone_number($number, $formats)\n{\n$format = trim(ereg_replace(\"[0-9]\", \"#\", $number));\n\nreturn (in_array($format, $formats)) ? true : false;\n}\n\n/* Usage Examples */\n\n// List of possible formats: You can add new formats or modify the existing ones\n\n$formats = array('###-###-####', '####-###-###',\n '(###) ###-###', '####-####-####',\n '##-###-####-####', '####-####', '###-###-###',\n '#####-###-###', '##########');\n\n$number = '08008-555-555';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n\necho \"<br />\";\n\n$number = '123-555-555';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n\necho \"<br />\";\n\n$number = '1800-1234-5678';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n\necho \"<br />\";\n\n$number = '(800) 555-123';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n\necho \"<br />\";\n\n$number = '1234567890';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n?>\n" }, { "answer_id": 5148731, "author": "Ian", "author_id": 638512, "author_profile": "https://Stackoverflow.com/users/638512", "pm_score": 2, "selected": false, "text": " pattern=\"^[\\d|\\+|\\(]+[\\)|\\d|\\s|-]*[\\d]$\" \n validateat=\"onsubmit\"\n" }, { "answer_id": 6994851, "author": "Bob-ob", "author_id": 3819557, "author_profile": "https://Stackoverflow.com/users/3819557", "pm_score": 2, "selected": false, "text": "<?php\n$pattern = \"/^(083|086|085|086|087)\\d{7}$/\";\n$phone = \"087343266\";\n\nif (preg_match($pattern,$phone)) echo \"Match\";\nelse echo \"Not match\";\n $(function(){\n //original field values\n var field_values = {\n //id : value\n 'url' : 'url',\n 'yourname' : 'yourname',\n 'email' : 'email',\n 'phone' : 'phone'\n };\n\n var url =$(\"input#url\").val();\n var yourname =$(\"input#yourname\").val();\n var email =$(\"input#email\").val();\n var phone =$(\"input#phone\").val();\n\n\n //inputfocus\n $('input#url').inputfocus({ value: field_values['url'] });\n $('input#yourname').inputfocus({ value: field_values['yourname'] });\n $('input#email').inputfocus({ value: field_values['email'] }); \n $('input#phone').inputfocus({ value: field_values['phone'] });\n\n\n\n //reset progress bar\n $('#progress').css('width','0');\n $('#progress_text').html('0% Complete');\n\n //first_step\n $('form').submit(function(){ return false; });\n $('#submit_first').click(function(){\n //remove classes\n $('#first_step input').removeClass('error').removeClass('valid');\n\n //ckeck if inputs aren't empty\n var fields = $('#first_step input[type=text]');\n var error = 0;\n fields.each(function(){\n var value = $(this).val();\n if( value.length<12 || value==field_values[$(this).attr('id')] ) {\n $(this).addClass('error');\n $(this).effect(\"shake\", { times:3 }, 50);\n\n error++;\n } else {\n $(this).addClass('valid');\n }\n }); \n\n if(!error) {\n if( $('#password').val() != $('#cpassword').val() ) {\n $('#first_step input[type=password]').each(function(){\n $(this).removeClass('valid').addClass('error');\n $(this).effect(\"shake\", { times:3 }, 50);\n });\n\n return false;\n } else { \n //update progress bar\n $('#progress_text').html('33% Complete');\n $('#progress').css('width','113px');\n\n //slide steps\n $('#first_step').slideUp();\n $('#second_step').slideDown(); \n } \n } else return false;\n });\n\n //second section\n $('#submit_second').click(function(){\n //remove classes\n $('#second_step input').removeClass('error').removeClass('valid');\n\n var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/; \n var fields = $('#second_step input[type=text]');\n var error = 0;\n fields.each(function(){\n var value = $(this).val();\n if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {\n $(this).addClass('error');\n $(this).effect(\"shake\", { times:3 }, 50);\n\n error++;\n } else {\n $(this).addClass('valid');\n }\n\n\n function validatePhone(phone) {\n var a = document.getElementById(phone).value;\n var filter = /^[0-9-+]+$/;\n if (filter.test(a)) {\n return true;\n }\n else {\n return false;\n }\n }\n\n $('#phone').blur(function(e) {\n if (validatePhone('txtPhone')) {\n $('#spnPhoneStatus').html('Valid');\n $('#spnPhoneStatus').css('color', 'green');\n }\n else {\n $('#spnPhoneStatus').html('Invalid');\n $('#spnPhoneStatus').css('color', 'red');\n }\n });\n\n });\n\n if(!error) {\n //update progress bar\n $('#progress_text').html('66% Complete');\n $('#progress').css('width','226px');\n\n //slide steps\n $('#second_step').slideUp();\n $('#fourth_step').slideDown(); \n } else return false;\n\n });\n\n\n $('#submit_second').click(function(){\n //update progress bar\n $('#progress_text').html('100% Complete');\n $('#progress').css('width','339px');\n\n //prepare the fourth step\n var fields = new Array(\n $('#url').val(),\n $('#yourname').val(),\n $('#email').val(),\n $('#phone').val()\n\n );\n var tr = $('#fourth_step tr');\n tr.each(function(){\n //alert( fields[$(this).index()] )\n $(this).children('td:nth-child(2)').html(fields[$(this).index()]);\n });\n\n //slide steps\n $('#third_step').slideUp();\n $('#fourth_step').slideDown(); \n });\n\n\n $('#submit_fourth').click(function(){\n\n url =$(\"input#url\").val();\n yourname =$(\"input#yourname\").val();\n email =$(\"input#email\").val();\n phone =$(\"input#phone\").val();\n\n //send information to server\n var dataString = 'url='+ url + '&yourname=' + yourname + '&email=' + email + '&phone=' + phone; \n\n\n\n alert (dataString);//return false; \n $.ajax({ \n type: \"POST\", \n url: \"http://clients.socialnetworkingsolutions.com/infobox/contact/\", \n data: \"url=\"+url+\"&yourname=\"+yourname+\"&email=\"+email+'&phone=' + phone,\n cache: false,\n success: function(data) { \n console.log(\"form submitted\");\n alert(\"success\");\n }\n }); \n return false;\n\n });\n\n\n //back button\n $('.back').click(function(){\n var container = $(this).parent('div'),\n previous = container.prev();\n\n switch(previous.attr('id')) {\n case 'first_step' : $('#progress_text').html('0% Complete');\n $('#progress').css('width','0px');\n break;\n case 'second_step': $('#progress_text').html('33% Complete');\n $('#progress').css('width','113px');\n break;\n\n case 'third_step' : $('#progress_text').html('66% Complete');\n $('#progress').css('width','226px');\n break;\n\n default: break;\n }\n\n $(container).slideUp();\n $(previous).slideDown();\n});\n\n\n});\n" }, { "answer_id": 8904016, "author": "GaiusSensei", "author_id": 139284, "author_profile": "https://Stackoverflow.com/users/139284", "pm_score": 4, "selected": false, "text": "((\\+[0-9]{2})|0)[.\\- ]?9[0-9]{2}[.\\- ]?[0-9]{3}[.\\- ]?[0-9]{4}\n ((\\+63)|0)[.\\- ]?9[0-9]{2}[.\\- ]?[0-9]{3}[.\\- ]?[0-9]{4}\n +63.917.123.4567 \n+63-917-123-4567 \n+63 917 123 4567 \n+639171234567 \n09171234567 \n" }, { "answer_id": 9636657, "author": "ReactiveRaven", "author_id": 390508, "author_profile": "https://Stackoverflow.com/users/390508", "pm_score": 4, "selected": false, "text": "/^[+#*\\(\\)\\[\\]]*([0-9][ ext+-pw#*\\(\\)\\[\\]]*){6,45}$/\n +(01) 123 (456) 789 ext555\n123456\n*44 123-456-789 [321]\n123456\n123456789012345678901234567890123456789012345\n*****++[](][((( 123456tteexxttppww\n mob 07777 777777\n1234 567 890 after 5pm\njohn smith\n(empty)\n1234567890123456789012345678901234567890123456\n911\n" }, { "answer_id": 10574682, "author": "Richard Ayotte", "author_id": 382228, "author_profile": "https://Stackoverflow.com/users/382228", "pm_score": 2, "selected": false, "text": "\"^(\\\\(?\\\\d\\\\d\\\\d\\\\)?)( |-|\\\\.)?\\\\d\\\\d\\\\d( |-|\\\\.)?\\\\d{4,4}(( |-|\\\\.)?[ext\\\\.]+ ?\\\\d+)?$\"\n" }, { "answer_id": 11977522, "author": "Steve", "author_id": 1564490, "author_profile": "https://Stackoverflow.com/users/1564490", "pm_score": 5, "selected": false, "text": "^[0-9+\\(\\)#\\.\\s\\/ext-]+$\n e x t" }, { "answer_id": 12112726, "author": "yurisich", "author_id": 881224, "author_profile": "https://Stackoverflow.com/users/881224", "pm_score": 1, "selected": false, "text": "'x' BAD_AREA_CODES BAD_AREA_CODES = open('badareacodes.txt', 'r').read().split('\\n')\n\ndef is_valid_phone(phone_number, country_code='US'):\n \"\"\"for now, only US codes are handled\"\"\"\n if country_code:\n country_code = country_code.upper()\n\n #drop everything except 0-9 and 'x'\n phone_number = filter(lambda n: n.isdigit() or n == 'x', phone_number)\n\n ext = None\n check_ext = phone_number.split('x')\n if len(check_ext) > 1:\n #there's an extension. Check for errors.\n if len(check_ext) > 2:\n return False\n phone_number, ext = check_ext\n\n #we only accept 10 digit phone numbers.\n if len(phone_number) == 11 and phone_number[0] == '1':\n #international code\n phone_number = phone_number[1:]\n if len(phone_number) != 10:\n return False\n\n #area_code: XXXxxxxxxx \n #head: xxxXXXxxxx\n #tail: xxxxxxXXXX\n area_code = phone_number[ :3]\n head = phone_number[3:6]\n tail = phone_number[6: ]\n\n if area_code in BAD_AREA_CODES:\n return False\n if head[0] == '1':\n return False\n if head[1:] == '11':\n return False\n\n #any other ideas?\n return True\n" }, { "answer_id": 15644461, "author": "Halfwarr", "author_id": 370861, "author_profile": "https://Stackoverflow.com/users/370861", "pm_score": 8, "selected": false, "text": "15555555555\n getNumberType isNumberMatch getExampleNumber getExampleNumberByType isPossibleNumber isValidNumber AsYouTypeFormatter findNumbers PhoneNumberOfflineGeocoder (408) 974–2042 (999) 974–2042 0404 999 999 (02) 9999 9999 (09) 9999 9999 libphonenumber 1-234-567-8901 x1234 libphonenumber Validation Results\n\nResult from isPossibleNumber() true\nResult from isValidNumber() true\n\nFormatting Results:\n\nE164 format +12345678901\nOriginal format (234) 567-8901 ext. 123\nNational format (234) 567-8901 ext. 123\nInternational format +1 234-567-8901 ext. 123\nOut-of-country format from US 1 (234) 567-8901 ext. 123\nOut-of-country format from CH 00 1 234-567-8901 ext. 123\n libphonenumber +61299999999 (02) 9999 9999 Validation Results\n\nResult from isPossibleNumber() true\nResult from isValidNumber() true\n\nFormatting Results\n\nE164 format +61299999999\nOriginal format 61 2 9999 9999\nNational format (02) 9999 9999\nInternational format +61 2 9999 9999\nOut-of-country format from US 011 61 2 9999 9999\nOut-of-country format from CH 00 61 2 9999 9999\n PhoneNumberOfflineGeocoder Results\nLocation Australia\n\nPhoneNumberToTimeZonesMapper Results\nTime zone(s) [Australia/Sydney]\n (09) 9999 9999 Validation Results\n\nResult from isPossibleNumber() true\nResult from isValidNumber() false\n" }, { "answer_id": 20971688, "author": "Ismael Miguel", "author_id": 2729937, "author_profile": "https://Stackoverflow.com/users/2729937", "pm_score": 6, "selected": false, "text": "/^(?:(?:\\(?(?:00|\\+)([1-4]\\d\\d|[1-9]\\d+)\\)?)[\\-\\.\\ \\\\\\/]?)?((?:\\(?\\d{1,}\\)?[\\-\\.\\ \\\\\\/]?)+)(?:[\\-\\.\\ \\\\\\/]?(?:#|ext\\.?|extension|x)[\\-\\.\\ \\\\\\/]?(\\d+))?$/i - (+351) 282 43 50 50\n - 90191919908\n - 555-8909\n - 001 6867684\n - 001 6867684x1\n - 1 (234) 567-8901\n - 1-234-567-8901 x1234\n - 1-234-567-8901 ext1234\n - 1-234 567.89/01 ext.1234\n - 1(234)5678901x1234\n - (123)8575973\n - (0055)(123)8575973\n" }, { "answer_id": 23175647, "author": "Sinan Eldem", "author_id": 895239, "author_profile": "https://Stackoverflow.com/users/895239", "pm_score": 1, "selected": false, "text": "d{9}\n function validateMobile($phone)\n{\n $pattern = \"/^(05)\\d{9}$/\";\n if (!preg_match($pattern, $phone))\n {\n return false;\n }\n return true;\n}\n\n$phone = \"0532486061\";\n\nif(!validateMobile($phone))\n{\n echo 'Incorrect Mobile Number!';\n}\n\n$phone = \"05324860614\";\nif(validateMobile($phone))\n{\n echo 'Correct Mobile Number!';\n}\n" }, { "answer_id": 24639167, "author": "Drew Thomas", "author_id": 2307704, "author_profile": "https://Stackoverflow.com/users/2307704", "pm_score": 3, "selected": false, "text": "/(\\+*\\d{1,})*([ |\\(])*(\\d{3})[^\\d]*(\\d{3})[^\\d]*(\\d{4})/ function phoneToTel($number) {\n $return = preg_replace('/(\\+*\\d{1,})*([ |\\(])*(\\d{3})[^\\d]*(\\d{3})[^\\d]*(\\d{4})/', '<a href=\"tel:$1$3$4$5\">$1 ($3) $4-$5</a>', $number); // includes international\n return $return;\n}\n" }, { "answer_id": 25298914, "author": "vapcguy", "author_id": 1181535, "author_profile": "https://Stackoverflow.com/users/1181535", "pm_score": 6, "selected": false, "text": "/^ [\\s] \\s [(] [)] \\( \\) ? - [-] \\- [-.\\s] \\d{3} [0-9][0-9][0-9] [2-9] (\\+|1\\s)? | [246] (?:77|78) [77|78] $/" }, { "answer_id": 29835355, "author": "Stuart Kershaw", "author_id": 2332112, "author_profile": "https://Stackoverflow.com/users/2332112", "pm_score": 4, "selected": false, "text": "/^\\s*(?:\\+?(\\d{1,3}))?([-. (]*(\\d{3})[-. )]*)?((\\d{3})[-. ]*(\\d{2,4})(?:[-.x ]*(\\d+))?)\\s*$/gm" }, { "answer_id": 31130267, "author": "bcherny", "author_id": 435124, "author_profile": "https://Stackoverflow.com/users/435124", "pm_score": -1, "selected": false, "text": "/\\b(\\d{3}[^\\d]{0,2}\\d{3}[^\\d]{0,2}\\d{4})\\b/\n" }, { "answer_id": 32532777, "author": "Herobrine2Nether", "author_id": 4350585, "author_profile": "https://Stackoverflow.com/users/4350585", "pm_score": 4, "selected": false, "text": "^\\(*\\+*[1-9]{0,3}\\)*-*[1-9]{0,3}[-. /]*\\(*[2-9]\\d{2}\\)*[-. /]*\\d{3}[-. /]*\\d{4} *e*x*t*\\.* *\\d{0,4}$\n 1-234-567-8901\n1-234-567-8901 x1234\n1-234-567-8901 ext1234\n1 (234) 567-8901\n1.234.567.8901\n1/234/567/8901\n12345678901\n1-234-567-8901 ext. 1234\n(+351) 282 433 5050\n" }, { "answer_id": 42002579, "author": "Sai prateek", "author_id": 2841472, "author_profile": "https://Stackoverflow.com/users/2841472", "pm_score": 1, "selected": false, "text": "String regex = \"^\\\\+(?:[0-9] ?){6,14}[0-9]$\";" }, { "answer_id": 49231246, "author": "Gautam Sharma", "author_id": 1406845, "author_profile": "https://Stackoverflow.com/users/1406845", "pm_score": 0, "selected": false, "text": " function isValidMobile(num,format) {\n if (!format) format=false\n var m1 = /^(\\W|^)[(]{0,1}\\d{3}[)]{0,1}[.]{0,1}[\\s-]{0,1}\\d{3}[\\s-]{0,1}[\\s.]{0,1}\\d{4}(\\W|$)/\n if(!m1.test(num)) {\n return false\n }\n num = num.replace(/ /g,'').replace(/\\./g,'').replace(/-/g,'').replace(/\\(/g,'').replace(/\\)/g,'').replace(/\\[/g,'').replace(/\\]/g,'').replace(/\\+/g,'').replace(/\\~/g,'').replace(/\\{/g,'').replace(/\\*/g,'').replace(/\\}/g,'')\n if ((num.length < 10) || (num.length > 11) || (num.substring(0,1)=='0') || (num.substring(1,1)=='0') || ((num.length==10)&&(num.substring(0,1)=='1'))||((num.length==11)&&(num.substring(0,1)!='1'))) return false;\n num = (num.length == 11) ? num : ('1' + num); \n if ((num.length == 11) && (num.substring(0,1) == \"1\")) {\n if (format===true) {\n return '(' + num.substr(1,3) + ') ' + num.substr(4,3) + '-' + num.substr(7,4)\n } else {\n return num\n }\n } else {\n return false;\n }\n }\n" }, { "answer_id": 49377835, "author": "Shailendra Madda", "author_id": 2462531, "author_profile": "https://Stackoverflow.com/users/2462531", "pm_score": 0, "selected": false, "text": "if (!phoneNumber.matches(\"^[6-9]\\\\d{9}$\")) {\n return false;\n} else {\n return true;\n}\n" }, { "answer_id": 49887511, "author": "SIM", "author_id": 9189799, "author_profile": "https://Stackoverflow.com/users/9189799", "pm_score": 1, "selected": false, "text": "regex 1[\\s./-]?\\(?[\\d]+\\)?[\\s./-]?[\\d]+[-/.]?[\\d]+\\s?[\\d]+\n import re\n\nphonelist =\"1-234-567-8901,1-234-567-8901 1234,1-234-567-8901 1234,1 (234) 567-8901,1.234.567.8901,1/234/567/8901,12345678901\"\n\nphonenumber = '\\n'.join([phone for phone in re.findall(r'1[\\s./-]?\\(?[\\d]+\\)?[\\s./-]?[\\d]+[-/.]?[\\d]+\\s?[\\d]+' ,phonelist)])\nprint(phonenumber)\n 1-234-567-8901\n1-234-567-8901 1234\n1-234-567-8901 1234\n1 (234) 567-8901\n1.234.567.8901\n1/234/567/8901\n12345678901\n" }, { "answer_id": 63354044, "author": "oriadam", "author_id": 3356679, "author_profile": "https://Stackoverflow.com/users/3356679", "pm_score": -1, "selected": false, "text": "^\\D*(\\d\\D*){9,14}$\n (\\d\\D*){9,}\n ^$" }, { "answer_id": 63771966, "author": "DigitShifter", "author_id": 6422459, "author_profile": "https://Stackoverflow.com/users/6422459", "pm_score": 0, "selected": false, "text": "Set<String> regexSet = uniqueValidPhoneNumbersFormats.stream()\n .map(s -> s.replaceAll(\"\\\\+\", \"\\\\\\\\+\"))\n .map(s -> s.replaceAll(\"\\\\d\", \"\\\\\\\\d\"))\n .map(s -> s.replaceAll(\"\\\\.\", \"\\\\\\\\.\"))\n .map(s -> s.replaceAll(\"([\\\\(\\\\)])\", \"\\\\\\\\$1\"))\n .collect(Collectors.toSet());\n\nString regex = String.join(\"|\", regexSet);\n public class TestBench {\n\n public static void main(String[] args) {\n List<String> validPhoneNumbersFormat = Arrays.asList(\n \"1-234-567-8901\",\n \"1-234-567-8901 x1234\",\n \"1-234-567-8901 ext1234\",\n \"1 (234) 567-8901\",\n \"1.234.567.8901\",\n \"1/234/567/8901\",\n \"12345678901\",\n \"+12345678901\",\n \"(234) 567-8901 ext. 123\",\n \"+1 234-567-8901 ext. 123\",\n \"1 (234) 567-8901 ext. 123\",\n \"00 1 234-567-8901 ext. 123\",\n \"+210-998-234-01234\",\n \"210-998-234-01234\",\n \"+21099823401234\",\n \"+210-(998)-(234)-(01234)\",\n \"(+351) 282 43 50 50\",\n \"90191919908\",\n \"555-8909\",\n \"001 6867684\",\n \"001 6867684x1\",\n \"1 (234) 567-8901\",\n \"1-234-567-8901 x1234\",\n \"1-234-567-8901 ext1234\",\n \"1-234 567.89/01 ext.1234\",\n \"1(234)5678901x1234\",\n \"(123)8575973\",\n \"(0055)(123)8575973\"\n );\n\n Set<String> uniqueValidPhoneNumbersFormats = new LinkedHashSet<>(validPhoneNumbersFormat);\n\n List<String> invalidPhoneNumbers = Arrays.asList(\n \"+210-99A-234-01234\", // FAIL\n \"+210-999-234-0\\\"\\\"234\", // FAIL\n \"+210-999-234-02;4\", // FAIL\n \"-210+998-234-01234\", // FAIL\n \"+210-998)-(234-(01234\" // FAIL\n );\n List<String> invalidAndValidPhoneNumbers = new ArrayList<>();\n invalidAndValidPhoneNumbers.addAll(invalidPhoneNumbers);\n invalidAndValidPhoneNumbers.addAll(uniqueValidPhoneNumbersFormats);\n\n Set<String> regexSet = uniqueValidPhoneNumbersFormats.stream()\n .map(s -> s.replaceAll(\"\\\\+\", \"\\\\\\\\+\"))\n .map(s -> s.replaceAll(\"\\\\d\", \"\\\\\\\\d\"))\n .map(s -> s.replaceAll(\"\\\\.\", \"\\\\\\\\.\"))\n .map(s -> s.replaceAll(\"([\\\\(\\\\)])\", \"\\\\\\\\$1\"))\n .collect(Collectors.toSet());\n\n String regex = String.join(\"|\", regexSet);\n\n List<String> result = new ArrayList<>();\n Pattern pattern = Pattern.compile(regex);\n for (String phoneNumber : invalidAndValidPhoneNumbers) {\n Matcher matcher = pattern.matcher(phoneNumber);\n if(matcher.matches()) {\n result.add(matcher.group());\n }\n }\n\n // Output:\n if(uniqueValidPhoneNumbersFormats.size() == result.size()) {\n System.out.println(\"All valid numbers was matched!\\n\");\n } \n result.forEach(System.out::println); \n }\n\n}\n All valid numbers was matched!\n\n1-234-567-8901\n1-234-567-8901 x1234\n1-234-567-8901 ext1234\n...\n...\n...\n" }, { "answer_id": 66233732, "author": "victoria55", "author_id": 12283084, "author_profile": "https://Stackoverflow.com/users/12283084", "pm_score": 0, "selected": false, "text": "validate_phone() pip install dataprep >>> from dataprep.clean import validate_phone\n>>> df = pd.DataFrame({'phone': ['1-234-567-8901', '1-234-567-8901 x1234', \n '1-234-567-8901 ext1234', '1 (234) 567-8901', '1.234.567.8901',\n '1/234/567/8901', 12345678901, '12345678', '123-456-78987']})\n>>> validate_phone(df['phone'])\n0 True\n1 True\n2 True\n3 True\n4 True\n5 True\n6 True\n7 False\n8 False\nName: phone, dtype: bool\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765/" ]
123,585
<p>I installed a ASP.Net website on a Windows 2008 server, which is by default using IIS7. The website seems to work fine, but the post backs on my forms do not work. After a few hours of debugging, I realized that when I manually try to hit the WebResource.axd file in my browser (e.g. I type <a href="http://www.domain.com/WebResource.axd" rel="nofollow noreferrer">http://www.domain.com/WebResource.axd</a> in the address bar), I get a HTTP 403 error (Access Denied). </p> <p>I'm not quite sure where to look next and my Windows 2008 security knowledge is limited. How do I go about giving access to that file?</p>
[ { "answer_id": 331832, "author": "Enes", "author_id": 2921654, "author_profile": "https://Stackoverflow.com/users/2921654", "pm_score": 2, "selected": false, "text": "<handlers> <add name=\"AssemblyResourceLoader-Integrated\" path=\"WebResource.axd\" verb=\"GET,DEBUG\" type=\"System.Web.Handlers.AssemblyResourceLoader\" preCondition=\"integratedMode\" />\n <add name=\"AXD-ISAPI-2.0\" path=\"*.axd\" verb=\"GET,HEAD,POST,DEBUG\" modules=\"IsapiModule\" scriptProcessor=\"%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_isapi.dll\" preCondition=\"classicMode,runtimeVersionv2.0,bitness32\" responseBufferLimit=\"0\" />\n <clear />" }, { "answer_id": 69806548, "author": "Jeff", "author_id": 3128942, "author_profile": "https://Stackoverflow.com/users/3128942", "pm_score": 1, "selected": false, "text": "[id \"942440\"]" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2013/" ]
123,598
<p>I have an Enum called Status defined as such:</p> <pre><code>public enum Status { VALID("valid"), OLD("old"); private final String val; Status(String val) { this.val = val; } public String getStatus() { return val; } } </code></pre> <p>I would like to access the value of <code>VALID</code> from a JSTL tag. Specifically the <code>test</code> attribute of the <code>&lt;c:when&gt;</code> tag. E.g.</p> <pre><code>&lt;c:when test="${dp.status eq Status.VALID"&gt; </code></pre> <p>I'm not sure if this is possible.</p>
[ { "answer_id": 130002, "author": "IaCoder", "author_id": 17337, "author_profile": "https://Stackoverflow.com/users/17337", "pm_score": 5, "selected": false, "text": "<% pageContext.setAttribute(\"old\", Status.OLD); %>\n <c:when test=\"${someModel.status == old}\"/>...</c:when>\n" }, { "answer_id": 368526, "author": "Alexander Vasiljev", "author_id": 42418, "author_profile": "https://Stackoverflow.com/users/42418", "pm_score": 8, "selected": true, "text": "<c:when test=\"${someModel.status == 'OLD'}\">\n" }, { "answer_id": 1110268, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<c:set var=\"abc\">\n <%=Status.OLD.getStatus()%>\n</c:set>\n\n<c:if test=\"${someVariable == abc}\">\n ....\n</c:if>\n" }, { "answer_id": 1787377, "author": "Eclatante", "author_id": 196339, "author_profile": "https://Stackoverflow.com/users/196339", "pm_score": -1, "selected": false, "text": "<c:if test=\"${dp.Status eq 'OLD'}\">\n ...\n</c:if>\n" }, { "answer_id": 4445976, "author": "Dean", "author_id": 542789, "author_profile": "https://Stackoverflow.com/users/542789", "pm_score": 2, "selected": false, "text": "public String getString() {\n return this.name();\n}\n public enum MyEnum {\n VALUE_1,\n VALUE_2;\n public String getString() {\n return this.name();\n }\n}\n <c:if test=\"${myObject.myEnumProperty.string eq 'VALUE_2'}\">...</c:if>\n" }, { "answer_id": 5341196, "author": "eremmel", "author_id": 664422, "author_profile": "https://Stackoverflow.com/users/664422", "pm_score": 2, "selected": false, "text": "toString() Enum.valueOf() Enum.name() <% pageContext.setAttribute(\"Status_OLD\", Status.OLD.name()); %>\n...\n<c:when test=\"${someModel.status == Status_OLD}\"/>...</c:when>\n" }, { "answer_id": 5855764, "author": "James", "author_id": 285288, "author_profile": "https://Stackoverflow.com/users/285288", "pm_score": 6, "selected": false, "text": "<spring:eval expression=\"dp.status == T(com.example.Status).VALID\" var=\"isValid\" />\n<c:if test=\"${isValid}\">\n isValid\n</c:if>\n" }, { "answer_id": 16692821, "author": "Matt", "author_id": 23723, "author_profile": "https://Stackoverflow.com/users/23723", "pm_score": 5, "selected": false, "text": "test <c:when test=\"<%= dp.getStatus() == Status.VALID %>\"> when ${} pageContext .tag <c:when test=\"${dp.status == 'VALID'}\"> <c:set var=\"VALID\" value=\"<%=Status.VALID%>\"/> <c:when test=\"${dp.status == VALID}\"> test when" }, { "answer_id": 37844534, "author": "Pavan", "author_id": 1397066, "author_profile": "https://Stackoverflow.com/users/1397066", "pm_score": -1, "selected": false, "text": " public class EnumTest{\n //Other property link\n private String name;\n ....\n\n public enum Status {\n ACTIVE,NEWLINK, BROADCASTED, PENDING, CLICKED, VERIFIED, AWARDED, INACTIVE, EXPIRED, DELETED_BY_ADMIN;\n }\n\n private Status statusobj ;\n\n //Getter and Setters\n}\n <c:if test=\"${enumTest.statusobj == 'ACTIVE'}\">\n\n//TRUE??? THEN PROCESS SOME LOGIC\n" }, { "answer_id": 44966422, "author": "Rupert Madden-Abbott", "author_id": 236587, "author_profile": "https://Stackoverflow.com/users/236587", "pm_score": 4, "selected": false, "text": "<%@ page import=\"org.example.Status\" %>\n<c:when test=\"${dp.status eq Status.VALID}\">\n public enum Status { \n VALID(\"valid\"), OLD(\"old\");\n\n private final String val;\n\n Status(String val) {\n this.val = val;\n }\n\n public String getStatus() {\n return val;\n }\n\n public boolean isValid() {\n return this == VALID;\n }\n\n public boolean isOld() {\n return this == OLD;\n }\n}\n <c:when test=\"${dp.status.valid}\">\n <c:when test=\"${not empty db.status and dp.status.valid}\">\n" }, { "answer_id": 45017117, "author": "ElectronicBlacksmith", "author_id": 250166, "author_profile": "https://Stackoverflow.com/users/250166", "pm_score": 1, "selected": false, "text": "request.setAttribute(RequestParameterNamesEnum.INBOX_ACTION.name(), RequestParameterNamesEnum.INBOX_ACTION.name());\n <script> var url = 'http://www.nowhere.com/?${INBOX_ACTION}=' + someValue;</script>\n <c:when test=\"${someModel.action == INBOX_ACTION}\">\n" }, { "answer_id": 53261143, "author": "HS Shin", "author_id": 4853250, "author_profile": "https://Stackoverflow.com/users/4853250", "pm_score": -1, "selected": false, "text": "public enum Status { \n\n VALID(\"valid\"), OLD(\"old\");\n\n private final String val;\n\n Status(String val) {\n this.val = val;\n }\n\n public String getStatus() {\n return val;\n }\n\n public static void setRequestAttributes(HttpServletRequest request) {\n Map<String,String> vals = new HashMap<String,String>();\n for (Status val : Status.values()) {\n vals.put(val.name(), val.value);\n }\n request.setAttribute(\"Status\", vals);\n }\n\n}\n <%@ page import=\"...Status\" %>\n<% Status.setRequestAttributes(request) %>\n\n<c:when test=\"${dp.status eq Status.VALID}\">\n...\n" }, { "answer_id": 56506213, "author": "Mehdi", "author_id": 1970299, "author_profile": "https://Stackoverflow.com/users/1970299", "pm_score": 1, "selected": false, "text": "<%@ page import=\"com.example.Status\" %>\n\n1. ${dp.status eq Title.VALID.getStatus()}\n2. ${dp.status eq Title.VALID}\n3. ${dp.status eq Title.VALID.toString()}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17337/" ]
123,632
<pre><code>devenv mysolution.sln /build "Release|Win32" /project myproject </code></pre> <p>When building from the command line, it seems I have the option of doing a <code>/build</code> or <code>/rebuild</code>, but no way of saying I want to do "project only" (i.e. not build or rebuild the specified project's dependencies as well). Does anyone know of a way?</p>
[ { "answer_id": 123649, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 2, "selected": false, "text": "devenv vcbuild subproject.vcproj \"release|win32\"\n" }, { "answer_id": 123651, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 3, "selected": false, "text": "MSBuild.exe MyProject.proj /t:build\n" }, { "answer_id": 123659, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 4, "selected": false, "text": "msbuild /p:BuildProjectReferences=false project.proj\n" }, { "answer_id": 124017, "author": "Owen", "author_id": 4790, "author_profile": "https://Stackoverflow.com/users/4790", "pm_score": 0, "selected": false, "text": "msbuild .sln .vcproj .vcproj /build devenv /rebuild grep awk .sln msbuild msbuild .sln" }, { "answer_id": 3813267, "author": "Ilia K.", "author_id": 252116, "author_profile": "https://Stackoverflow.com/users/252116", "pm_score": 1, "selected": false, "text": "msbuild foo.sln /t:proj1:Rebuild;folder_of_proj2\\proj2:Clean\n" }, { "answer_id": 15580657, "author": "Denkkar", "author_id": 1873507, "author_profile": "https://Stackoverflow.com/users/1873507", "pm_score": 0, "selected": false, "text": "call \"%VS100COMNTOOLS%\"\\\\vsvars32.bat\nmsbuild /detailedsummary /p:Configuration=Debug /p:Platform=x64 /t:build MY_ABSOLUTE_PATH.vcxproj\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
123,639
<p>Suppose I use the [RemoteClass] tag to endow a custom Flex class with serialization intelligence. </p> <p>What happens when I need to change my object (add a new field, remove a field, rename a field, etc)?</p> <p>Is there a design pattern for handling this in an elegant way?</p>
[ { "answer_id": 327306, "author": "cliff.meyers", "author_id": 41754, "author_profile": "https://Stackoverflow.com/users/41754", "pm_score": 2, "selected": false, "text": "java:\npublic class User {\n public Long id;\n public String firstName;\n public String lastName;\n}\n\nas3:\npublic class UserBase {\n public var id : Number;\n public var firstName : String;\n public var lastName : String;\n}\n\n[Bindable] [RemoteClass(...)]\npublic class User extends UserBase {\n public function getFullName() : String {\n return firstName + \" \" + lastName;\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1750627/" ]
123,648
<p>I know that a SQL Server full text index can not index more than one table. But, I have relationships in tables that I would like to implement full text indexes on.</p> <p>Take the 3 tables below...</p> <pre><code>Vehicle Veh_ID - int (Primary Key) FK_Atr_VehicleColor - int Veh_Make - nvarchar(20) Veh_Model - nvarchar(50) Veh_LicensePlate - nvarchar(10) Attributes Atr_ID - int (Primary Key) FK_Aty_ID - int Atr_Name - nvarchar(50) AttributeTypes Aty_ID - int (Primary key) Aty_Name - nvarchar(50) </code></pre> <p>The Attributes and AttributeTypes tables hold values that can be used in drop down lists throughout the application being built. For example, Attribute Type of "Vehicle Color" with Attributes of "Black", "Blue", "Red", etc...</p> <p>Ok, so the problem comes when a user is trying to search for a "Blue Ford Mustang". So what is the best solution considering that tables like Vehicle will get rather large?</p> <p>Do I create another field in the "Vehicle" table that is "Veh Color" that holds the text value of what is selected in the drop down in addition to "FK Atr VehicleColor"?</p> <p>Or, do I drop "FK Atr VehicleColor" altogether and add "Veh Color"? I can use text value of "Veh Color" to match against "Atr Name" when the drop down is populated in an update form. With this approach I will have to handle if Attributes are dropped from the database.</p> <p>-- Note: could not use underscore outside of code view as everything between two underscores is <em>italicized</em>.</p>
[ { "answer_id": 123814, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 0, "selected": false, "text": "SELECT \n Vehicle.VehID, ..., Color.Atr_Name AS ColorName \nFROM\n Vehicle \nLEFT OUTER JOIN Attributes AS Color ON (Vehicle.FK_Atr_VehicleColor = Attributes.Atr_Id)\n" }, { "answer_id": 123890, "author": "Jason DeFontes", "author_id": 6159, "author_profile": "https://Stackoverflow.com/users/6159", "pm_score": 2, "selected": false, "text": "CREATE VIEW VehicleSearch\nWITH SCHEMABINDING\nAS\nSELECT\n v.Veh_ID,\n v.Veh_Make,\n v.Veh_Model,\n v.Veh_LicensePlate,\n a.Atr_Name as Veh_Color\nFROM\n Vehicle v\nINNER JOIN\n Attributes a on a.Atr_ID = v.FK_Atr_VehicleColor\nGO\n\nCREATE UNIQUE CLUSTERED INDEX IX_VehicleSearch_Veh_ID ON VehicleSearch (\n Veh_ID ASC\n) ON [PRIMARY]\nGO\n\nCREATE FULLTEXT INDEX ON VehicleSearch (\n Veh_Make LANGUAGE [English],\n Veh_Model LANGUAGE [English],\n Veh_Color LANGUAGE [English]\n)\nKEY INDEX IX_VehicleSearch_Veh_ID ON [YourFullTextCatalog]\nWITH CHANGE_TRACKING AUTO\nGO\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576/" ]
123,657
<p>I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.</p> <p>I don't know if it depends on the technologies used, but I'll use Tomcat 5.5</p> <hr> <p>I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)</p>
[ { "answer_id": 123696, "author": "yalestar", "author_id": 2177, "author_profile": "https://Stackoverflow.com/users/2177", "pm_score": 1, "selected": false, "text": "getSession().setAttribute(\"thing\", object);\n Object obj = getSession.getAttribute(\"thing\");\n" }, { "answer_id": 123785, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 7, "selected": true, "text": "protected void doGet(HttpServletRequest request, HttpServletResponse response) {\n String shared = \"shared\";\n request.setAttribute(\"sharedId\", shared); // add to request\n request.getSession().setAttribute(\"sharedId\", shared); // add to session\n this.getServletConfig().getServletContext().setAttribute(\"sharedId\", shared); // add to application context\n request.getRequestDispatcher(\"/URLofOtherServlet\").forward(request, response);\n}\n request.getAttribute(\"sharedId\");\n request.getSession().getAttribute(\"sharedId\");\n request.getSession().invalidate();\n request.getSession().removeAttribute(\"sharedId\");\n this.getServletConfig().getServletContext().getAttribute(\"sharedId\");\n this.getServletConfig().getServletContext().removeAttribute(\"sharedId\");\n" }, { "answer_id": 16058123, "author": "ggrandes", "author_id": 1450967, "author_profile": "https://Stackoverflow.com/users/1450967", "pm_score": 2, "selected": false, "text": " <Context path=\"/myApp1\" docBase=\"myApp1\" crossContext=\"true\"/>\n <Context path=\"/myApp2\" docBase=\"myApp2\" crossContext=\"true\"/>\n ServletContext sc = getServletContext();\n sc.setAttribute(\"attribute\", \"value\");\n ServletContext sc = getServletContext(\"/myApp1\");\n String anwser = (String)sc.getAttribute(\"attribute\");\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19689/" ]
123,661
<p>Consider a <em>hypothetical</em> method of an object that does stuff for you:</p> <pre><code>public class DoesStuff { BackgroundWorker _worker = new BackgroundWorker(); ... public void CancelDoingStuff() { _worker.CancelAsync(); //todo: Figure out a way to wait for BackgroundWorker to be cancelled. } } </code></pre> <p>How can one wait for a BackgroundWorker to be done?</p> <hr> <p>In the past people have tried:</p> <pre><code>while (_worker.IsBusy) { Sleep(100); } </code></pre> <p>But <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1819196&amp;SiteID=1" rel="noreferrer">this deadlocks</a>, because <code>IsBusy</code> is not cleared until after the <code>RunWorkerCompleted</code> event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.)</p> <p>Others have add suggested kludging it into:</p> <pre><code>while (_worker.IsBusy) { Application.DoEvents(); } </code></pre> <p>The problem with that is that is <code>Application.DoEvents()</code> causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant).</p> <p>I would hope to use some solution involving Event synchronization objects, where the code <strong>waits</strong> for an event - that the worker's <code>RunWorkerCompleted</code> event handlers sets. Something like:</p> <pre><code>Event _workerDoneEvent = new WaitHandle(); public void CancelDoingStuff() { _worker.CancelAsync(); _workerDoneEvent.WaitOne(); } private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e) { _workerDoneEvent.SetEvent(); } </code></pre> <p>But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event.</p> <p>So how can you wait for an BackgroundWorker to finish?</p> <hr> <p><strong>Update</strong> People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as:</p> <pre><code>BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += MyWork; worker.RunWorkerAsync(); WaitForWorkerToFinish(worker); </code></pre> <p>That is <em>not</em> it, that is <em>not</em> what I'm doing, and that is <em>not</em> what is being asked here. If that were the case, there would be no point in using a background worker.</p>
[ { "answer_id": 123684, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 2, "selected": false, "text": "private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)\n{\n if(e.Cancelled)\n {\n Console.WriteLine(\"The worker was cancelled.\");\n }\n}\n if (_worker.CancellationPending)\n{\n Console.WriteLine(\"Cancellation is pending, no need to call CancelAsync again\");\n}\n" }, { "answer_id": 123791, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 8, "selected": true, "text": "private BackgroundWorker worker = new BackgroundWorker();\nprivate AutoResetEvent _resetEvent = new AutoResetEvent(false);\n\npublic Form1()\n{\n InitializeComponent();\n\n worker.DoWork += worker_DoWork;\n}\n\npublic void Cancel()\n{\n worker.CancelAsync();\n _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made\n}\n\nvoid worker_DoWork(object sender, DoWorkEventArgs e)\n{\n while(!e.Cancel)\n {\n // do something\n }\n\n _resetEvent.Set(); // signal that worker is done\n}\n" }, { "answer_id": 123864, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 0, "selected": false, "text": "BackgroundWorker RunWorkerCompleted using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.ComponentModel;\n\nnamespace WindowsFormsApplication1\n{\n public class AsyncForm : Form\n {\n private Button _startButton;\n private Label _statusLabel;\n private Button _stopButton;\n private MyWorker _worker;\n\n public AsyncForm()\n {\n var layoutPanel = new TableLayoutPanel();\n layoutPanel.Dock = DockStyle.Fill;\n layoutPanel.ColumnStyles.Add(new ColumnStyle());\n layoutPanel.ColumnStyles.Add(new ColumnStyle());\n layoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));\n layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100));\n\n _statusLabel = new Label();\n _statusLabel.Text = \"Idle.\";\n layoutPanel.Controls.Add(_statusLabel, 0, 0);\n\n _startButton = new Button();\n _startButton.Text = \"Start\";\n _startButton.Click += HandleStartButton;\n layoutPanel.Controls.Add(_startButton, 0, 1);\n\n _stopButton = new Button();\n _stopButton.Enabled = false;\n _stopButton.Text = \"Stop\";\n _stopButton.Click += HandleStopButton;\n layoutPanel.Controls.Add(_stopButton, 1, 1);\n\n this.Controls.Add(layoutPanel);\n }\n\n private void HandleStartButton(object sender, EventArgs e)\n {\n _stopButton.Enabled = true;\n _startButton.Enabled = false;\n\n _worker = new MyWorker() { WorkerSupportsCancellation = true };\n _worker.RunWorkerCompleted += HandleWorkerCompleted;\n _worker.RunWorkerAsync();\n\n _statusLabel.Text = \"Running...\";\n }\n\n private void HandleStopButton(object sender, EventArgs e)\n {\n _worker.CancelAsync();\n _statusLabel.Text = \"Cancelling...\";\n }\n\n private void HandleWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n if (e.Cancelled)\n {\n _statusLabel.Text = \"Cancelled!\";\n }\n else\n {\n _statusLabel.Text = \"Completed.\";\n }\n\n _stopButton.Enabled = false;\n _startButton.Enabled = true;\n }\n\n }\n\n public class MyWorker : BackgroundWorker\n {\n protected override void OnDoWork(DoWorkEventArgs e)\n {\n base.OnDoWork(e);\n\n for (int i = 0; i < 10; i++)\n {\n System.Threading.Thread.Sleep(500);\n\n if (this.CancellationPending)\n {\n e.Cancel = true;\n e.Result = false;\n return;\n }\n }\n\n e.Result = true;\n }\n }\n}\n AutoResetEvent BackgroundWorker OnRunWorkerCompleted RunWorkerCompleted" }, { "answer_id": 126570, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": false, "text": "_resetEvent.Set()" }, { "answer_id": 127362, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 3, "selected": false, "text": "private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n if (!e.Cancelled)\n {\n rocketOnPad = false;\n label1.Text = \"Rocket launch complete.\";\n }\n else\n {\n rocketOnPad = true;\n label1.Text = \"Rocket launch aborted.\";\n }\n worker = null;\n}\n private void BlowUpRocket()\n{\n if (worker != null)\n {\n worker.CancelAsync();\n WaitForWorkerToFinish(worker);\n worker = null;\n }\n\n StartClaxon();\n SelfDestruct();\n}\n private void OpenAccessGates()\n{\n if (worker != null)\n {\n worker.CancelAsync();\n WaitForWorkerToFinish(worker);\n worker = null;\n }\n\n if (!rocketOnPad)\n DisengageAllGateLatches();\n}\n private void DrainRocket()\n{\n if (worker != null)\n {\n worker.CancelAsync();\n WaitForWorkerToFinish(worker);\n worker = null;\n }\n\n if (rocketOnPad)\n OpenFuelValves();\n}\n private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n if (!e.Cancelled)\n {\n rocketOnPad = false;\n label1.Text = \"Rocket launch complete.\";\n }\n else\n {\n rocketOnPad = true;\n label1.Text = \"Rocket launch aborted.\";\n }\n worker = null;\n\n if (delayedBlowUpRocket)\n BlowUpRocket();\n else if (delayedOpenAccessGates)\n OpenAccessGates();\n else if (delayedDrainRocket)\n DrainRocket();\n}\n\nprivate void BlowUpRocket()\n{\n if (worker != null)\n {\n delayedBlowUpRocket = true;\n worker.CancelAsync();\n return;\n }\n\n StartClaxon();\n SelfDestruct();\n}\n\nprivate void OpenAccessGates()\n{\n if (worker != null)\n {\n delayedOpenAccessGates = true;\n worker.CancelAsync();\n return;\n }\n\n if (!rocketOnPad)\n DisengageAllGateLatches();\n}\n\nprivate void DrainRocket()\n{\n if (worker != null)\n {\n delayedDrainRocket = true;\n worker.CancelAsync();\n return;\n }\n\n if (rocketOnPad)\n OpenFuelValves();\n}\n" }, { "answer_id": 129487, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "// do stuff\n\nif(bw.CancellationPending)\n{\n e.Cancel = True;\n return;\n}\n\n// do other stuff\n" }, { "answer_id": 11370746, "author": "Infotekka", "author_id": 497445, "author_profile": "https://Stackoverflow.com/users/497445", "pm_score": 0, "selected": false, "text": "class Test : Form\n{\n private BackgroundWorker MyWorker = new BackgroundWorker();\n\n public Test() {\n MyWorker.DoWork += new DoWorkEventHandler(MyWorker_DoWork);\n }\n\n void MyWorker_DoWork(object sender, DoWorkEventArgs e) {\n for (int i = 0; i < 100; i++) {\n //Do stuff here\n System.Threading.Thread.Sleep((new Random()).Next(0, 1000)); //WARN: Artificial latency here\n if (MyWorker.CancellationPending) { return; } //Bail out if MyWorker is cancelled\n }\n }\n\n public void CancelWorker() {\n if (MyWorker != null && MyWorker.IsBusy) {\n MyWorker.CancelAsync();\n System.Threading.ThreadStart WaitThread = new System.Threading.ThreadStart(delegate() {\n while (MyWorker.IsBusy) {\n System.Threading.Thread.Sleep(100);\n }\n });\n WaitThread.BeginInvoke(a => {\n Invoke((MethodInvoker)delegate() { //Invoke your StuffAfterCancellation call back onto the UI thread\n StuffAfterCancellation();\n });\n }, null);\n } else {\n StuffAfterCancellation();\n }\n }\n\n private void StuffAfterCancellation() {\n //Things to do after MyWorker is cancelled\n }\n}\n MyWorker MyWorker AsyncCallback MyWorker" }, { "answer_id": 18485183, "author": "Nitesh", "author_id": 2724944, "author_profile": "https://Stackoverflow.com/users/2724944", "pm_score": 0, "selected": false, "text": "Imports System.Net\nImports System.IO\nImports System.Text\n\nPublic Class Form1\n Dim f As New Windows.Forms.Form\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n BackgroundWorker1.WorkerReportsProgress = True\n BackgroundWorker1.RunWorkerAsync()\n Dim l As New Label\n l.Text = \"Please Wait\"\n f.Controls.Add(l)\n l.Dock = DockStyle.Fill\n f.StartPosition = FormStartPosition.CenterScreen\n f.FormBorderStyle = Windows.Forms.FormBorderStyle.None\n While BackgroundWorker1.IsBusy\n f.ShowDialog()\n End While\nEnd Sub\n\n\n\n\nPrivate Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork\n\n Dim i As Integer\n For i = 1 To 5\n Threading.Thread.Sleep(5000)\n BackgroundWorker1.ReportProgress((i / 5) * 100)\n Next\nEnd Sub\n\nPrivate Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged\n Me.Text = e.ProgressPercentage\n\nEnd Sub\n\n Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted\n\n f.Close()\n\nEnd Sub\n\nEnd Class\n" }, { "answer_id": 24458088, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 0, "selected": false, "text": "Application.DoEvent() BackgroundWorker public class BackgroundWorkerEx : BackgroundWorker\n{\n private AutoResetEvent _resetEvent = new AutoResetEvent(false);\n private bool _resetting, _started;\n private object _lockObject = new object();\n\n public void CancelSync()\n {\n bool doReset = false;\n lock (_lockObject) {\n if (_started && !_resetting) {\n _resetting = true;\n doReset = true;\n }\n }\n if (doReset) {\n CancelAsync();\n _resetEvent.WaitOne();\n lock (_lockObject) {\n _started = false;\n _resetting = false;\n }\n }\n }\n\n protected override void OnDoWork(DoWorkEventArgs e)\n {\n lock (_lockObject) {\n _resetting = false;\n _started = true;\n _resetEvent.Reset();\n }\n try {\n base.OnDoWork(e);\n } finally {\n _resetEvent.Set();\n }\n }\n}\n _resetEvent.WaitOne() _resetEvent.Set(); _resetEvent.Set(); CancelSync BackgroundWorkerEx _worker;\n\nvoid StartWork()\n{\n StopWork();\n _worker = new BackgroundWorkerEx { \n WorkerSupportsCancellation = true,\n WorkerReportsProgress = true\n };\n _worker.DoWork += Worker_DoWork;\n _worker.ProgressChanged += Worker_ProgressChanged;\n}\n\nvoid StopWork()\n{\n if (_worker != null) {\n _worker.CancelSync(); // Use our new method.\n }\n}\n\nprivate void Worker_DoWork(object sender, DoWorkEventArgs e)\n{\n for (int i = 1; i <= 20; i++) {\n if (worker.CancellationPending) {\n e.Cancel = true;\n break;\n } else {\n // Simulate a time consuming operation.\n System.Threading.Thread.Sleep(500);\n worker.ReportProgress(5 * i);\n }\n }\n}\n\nprivate void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n progressLabel.Text = e.ProgressPercentage.ToString() + \"%\";\n}\n RunWorkerCompleted" }, { "answer_id": 30920928, "author": "Connor Williams", "author_id": 5024957, "author_profile": "https://Stackoverflow.com/users/5024957", "pm_score": 0, "selected": false, "text": "foreach(DataRow rw in dt.Rows)\n{\n //loop code\n while(!backgroundWorker1.IsBusy)\n {\n backgroundWorker1.RunWorkerAsync();\n }\n}\n" }, { "answer_id": 43690090, "author": "A876", "author_id": 5684184, "author_profile": "https://Stackoverflow.com/users/5684184", "pm_score": 0, "selected": false, "text": "MainWin_FormClosing() Thread.Sleep(1500) private volatile bool bwRunning = false;\n\n...\n\nprivate void MainWin_FormClosing(Object sender, FormClosingEventArgs e)\n{\n ... // Clean house as-needed.\n\n bwInstance.CancelAsync(); // Flag background worker to stop.\n while (bwRunning)\n Thread.Sleep(100); // Wait for background worker to stop.\n} // (The form really gets closed now.)\n\n...\n\nprivate void bwBody(object sender, DoWorkEventArgs e)\n{\n bwRunning = true;\n\n BackgroundWorker bw = sender as BackgroundWorker;\n\n ... // Set up (open logfile, etc.)\n\n for (; ; ) // infinite loop\n {\n ...\n if (bw.CancellationPending) break;\n ...\n } \n\n ... // Tear down (close logfile, etc.)\n\n bwRunning = false;\n} // (bwInstance dies now.)\n" }, { "answer_id": 47521216, "author": "Shawn Rubie", "author_id": 4151560, "author_profile": "https://Stackoverflow.com/users/4151560", "pm_score": 0, "selected": false, "text": "public class DoesStuff\n{\n BackgroundWorker _worker = new BackgroundWorker();\n\n ...\n\n public void CancelDoingStuff()\n {\n _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) => \n {\n // do whatever you want to do when the cancel completes in here!\n });\n _worker.CancelAsync();\n }\n}\n void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n if (_worker != null)\n {\n _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) => this.Close());\n _worker.CancelAsync();\n e.Cancel = true;\n }\n}\n" }, { "answer_id": 55426077, "author": "Anthony", "author_id": 1786137, "author_profile": "https://Stackoverflow.com/users/1786137", "pm_score": 0, "selected": false, "text": "async await public async Task StopAsync()\n {\n _worker.CancelAsync();\n\n while (_isBusy)\n await Task.Delay(1);\n }\n DoWork public async Task DoWork()\n {\n _isBusy = true;\n while (!_worker.CancellationPending)\n {\n // Do something.\n }\n _isBusy = false;\n }\n while DoWork try ... catch _isBusy false _worker.IsBusy StopAsync class MyBackgroundWorker\n{\n private BackgroundWorker _worker;\n private bool _isBusy;\n\n public void Start()\n {\n if (_isBusy)\n throw new InvalidOperationException(\"Cannot start as a background worker is already running.\");\n\n InitialiseWorker();\n _worker.RunWorkerAsync();\n }\n\n public async Task StopAsync()\n {\n if (!_isBusy)\n throw new InvalidOperationException(\"Cannot stop as there is no running background worker.\");\n\n _worker.CancelAsync();\n\n while (_isBusy)\n await Task.Delay(1);\n\n _worker.Dispose();\n }\n\n private void InitialiseWorker()\n {\n _worker = new BackgroundWorker\n {\n WorkerSupportsCancellation = true\n };\n _worker.DoWork += WorkerDoWork;\n }\n\n private void WorkerDoWork(object sender, DoWorkEventArgs e)\n {\n _isBusy = true;\n try\n {\n while (!_worker.CancellationPending)\n {\n // Do something.\n }\n }\n catch\n {\n _isBusy = false;\n throw;\n }\n\n _isBusy = false;\n }\n}\n await myBackgroundWorker.StopAsync();\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
123,672
<p>In <a href="http://msdn.microsoft.com/en-us/library/ms155365%28SQL.90%29.aspx" rel="nofollow noreferrer">this MSDN article</a>, MS explains how to specify other delimiters besides commas for csv-type exports from SSRS 2005, however, literal tab characters are stripped by the config file parser, and it doesn't appear that MS has provided a workaround.<br> <a href="http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=357527" rel="nofollow noreferrer">This entry</a> on Microsoft Connect seems to confirm this.<br> Has anyone developed a way to export tab-delimited files from SSRS 2005?<br> Or perhaps developed an open-source custom renderer to get the job done? </p> <p>Note: I've heard of manually appending <code>&amp;rc:FieldDelimiter=%09</code> via URL access, but that's not an acceptable workaround for my users and doesn't appear to work anyways.</p>
[ { "answer_id": 124523, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 1, "selected": false, "text": "use tempdb\ngo\ncreate view vw_bcpMasterSysobjects\nas\n select\n name = '\"' + name + '\"' ,\n crdate = '\"' + convert(varchar(8), crdate, 112) + '\"' ,\n crtime = '\"' + convert(varchar(8), crdate, 108) + '\"'\n from master..sysobjects\ngo\ndeclare @sql varchar(8000)\nselect @sql = 'bcp \"select * from tempdb..vw_bcpMasterSysobjects\n order by crdate desc, crtime desc\"\n queryout c:\\bcp\\sysobjects.txt -c -t, -T -S'\n + @@servername\nexec master..xp_cmdshell @sql\n" }, { "answer_id": 140542, "author": "jimmyorr", "author_id": 19239, "author_profile": "https://Stackoverflow.com/users/19239", "pm_score": 1, "selected": false, "text": "<Extension Name=\"Tabs\" Type=\"Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering\">\n <OverrideNames>\n <Name Language=\"en-US\">Tab-delimited (requires patch)</Name>\n </OverrideNames>\n <Configuration>\n <DeviceInfo>\n <Encoding>ASCII</Encoding>\n <FieldDelimiter>REPLACE_WITH_TAB</FieldDelimiter>\n <Extension>txt</Extension>\n </DeviceInfo>\n </Configuration>\n</Extension>\n # all .txt files in the working directory\n@files = <*.txt>;\n\nforeach $file (@files) {\n $old = $file;\n $new = \"$file.temp\";\n\n open OLD, \"<\", $old or die $!;\n open NEW, \">\", $new or die $!;\n\n while (my $line = <OLD>) {\n\n # SSRS 2005 SP2 can't output tab-delimited files\n $line =~ s/REPLACE_WITH_TAB/\\t/g;\n\n print NEW $line;\n }\n\n close OLD or die $!;\n close NEW or die $!;\n\n rename($old, \"$old.orig\");\n rename($new, $old);\n}\n" }, { "answer_id": 1308462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<Extension Name=\"Tabs\" Type=\"Microsoft.ReportingServices.Rendering.DataRenderer.CsvReport,Microsoft.ReportingServices.DataRendering\">\n <OverrideNames>\n <Name Language=\"en-US\">Tab-delimited</Name>\n </OverrideNames>\n <Configuration>\n <DeviceInfo>\n <OutputFormat>TXT</OutputFormat>\n <Encoding>ASCII</Encoding>\n <FieldDelimiter>&#9;</FieldDelimiter>\n <!-- or as this -->\n <!-- <FieldDelimiter xml:space=\"preserve\">[TAB]</FieldDelimiter> -->\n <FileExtension>txt</FileExtension>\n </DeviceInfo>\n </Configuration>\n</Extension>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19239/" ]
123,718
<p>How can i check to see if a static class has been declared? ex Given the class</p> <pre><code>class bob { function yippie() { echo "skippie"; } } </code></pre> <p>later in code how do i check:</p> <pre><code>if(is_a_valid_static_object(bob)) { bob::yippie(); } </code></pre> <p>so i don't get: Fatal error: Class 'bob' not found in file.php on line 3</p>
[ { "answer_id": 123731, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 3, "selected": false, "text": "bool class_exists( string $class_name [, bool $autoload ]" }, { "answer_id": 123815, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 5, "selected": true, "text": "echo method_exists( bob, 'yippie' ) ? 'yes' : 'no';\n try {\n $method = new ReflectionMethod( 'bob::yippie' );\n if ( $method->isStatic() )\n {\n // verified that bob::yippie is defined AND static, proceed\n }\n}\ncatch ( ReflectionException $e )\n{\n // method does not exist\n echo $e->getMessage();\n}\n if ( method_exists( bob, 'yippie' ) )\n{\n $method = new ReflectionMethod( 'bob::yippie' );\n if ( $method->isStatic() )\n {\n // verified that bob::yippie is defined AND static, proceed\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
123,726
<p>How to disable standard ASP.NET handling of 401 response code (redirecting to login page) for AJAX/JSON requests?</p> <p>For web-pages it's okay, but for AJAX I need to get right 401 error code instead of good looking 302/200 for login page.</p> <p><strong>Update</strong>: There are several solutions from Phil Haack, PM of ASP.NET MVC - <a href="http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx" rel="noreferrer">http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx</a></p>
[ { "answer_id": 126985, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 1, "selected": false, "text": "FilterAttribute IAuthorizationFilter OnAuthorization AuthorizeAttribute filterContext.Cancel filterContext.Result HttpUnauthorizedResult" }, { "answer_id": 130314, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 5, "selected": true, "text": "HttpResponse.StatusCode <authentication />" }, { "answer_id": 311747, "author": "Jared", "author_id": 3442, "author_profile": "https://Stackoverflow.com/users/3442", "pm_score": 2, "selected": false, "text": " protected void Application_PreSendRequestHeaders(object sender, EventArgs e) {\n if (Response.StatusCode == 401) {\n Response.Clear();\n Response.Redirect(Response.ApplyAppPathModifier(\"~/Login.aspx\"));\n return;\n }\n }\n" }, { "answer_id": 1072996, "author": "Catalin DICU", "author_id": 13030, "author_profile": "https://Stackoverflow.com/users/13030", "pm_score": 5, "selected": false, "text": "protected void Application_EndRequest()\n{\n if (Context.Response.StatusCode == 302 && Context.Request.Headers[\"X-Requested-With\"] == \"XMLHttpRequest\")\n {\n Context.Response.Clear();\n Context.Response.StatusCode = 401;\n }\n}\n" }, { "answer_id": 17161541, "author": "Timothy Lee Russell", "author_id": 12919, "author_profile": "https://Stackoverflow.com/users/12919", "pm_score": 3, "selected": false, "text": "<authentication mode=\"Forms\">\n</authentication>\n [Authorize(Roles = \"Administrator,User\"), Response302to401]\n[AcceptVerbs(\"Get\")]\npublic async Task<JsonResult> GetDocuments()\n{\n string requestUri = User.Identity.Name.ToLower() + \"/document\";\n RequestKeyHttpClient<IEnumerable<DocumentModel>, string> client =\n new RequestKeyHttpClient<IEnumerable<DocumentModel>, string>(requestUri);\n\n var documents = await client.GetManyAsync<IEnumerable<DocumentModel>>();\n\n return Json(documents, JsonRequestBehavior.AllowGet);\n}\n public class Response302to401 : AuthorizeAttribute\n{\n protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)\n {\n if (!filterContext.HttpContext.User.Identity.IsAuthenticated)\n {\n if (filterContext.HttpContext.Request.IsAjaxRequest())\n {\n filterContext.Result = new JsonResult\n {\n Data = new { Message = \"Your session has died a terrible and gruesome death\" },\n JsonRequestBehavior = JsonRequestBehavior.AllowGet\n };\n filterContext.HttpContext.Response.StatusCode = 401;\n filterContext.HttpContext.Response.StatusDescription = \"Humans and robots must authenticate\";\n filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;\n }\n }\n //base.HandleUnauthorizedRequest(filterContext);\n }\n}\n" }, { "answer_id": 27574184, "author": "Sebastián Rojas", "author_id": 2163398, "author_profile": "https://Stackoverflow.com/users/2163398", "pm_score": 2, "selected": false, "text": "[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]\npublic class BetterAuthorize : AuthorizeAttribute\n{\n protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)\n {\n if (filterContext.HttpContext.Request.IsAjaxRequest())\n {\n //Set the response status code to 500\n filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;\n filterContext.HttpContext.Response.StatusDescription = \"Humans and robots must authenticate\";\n filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;\n\n filterContext.HttpContext.Response.End();\n }\n else\n base.HandleUnauthorizedRequest(filterContext);\n }\n}\n" }, { "answer_id": 29365244, "author": "valter.santos.matos", "author_id": 3182788, "author_profile": "https://Stackoverflow.com/users/3182788", "pm_score": 2, "selected": false, "text": " HttpContext.Response.End();\n public async Task<JsonResult> Return401()\n{\n HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;\n HttpContext.Response.End();\n return Json(\"Unauthorized\", JsonRequestBehavior.AllowGet);\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12045/" ]
123,758
<p>Let's say I have the following <code>class X</code> where I want to return access to an internal member:</p> <pre><code>class Z { // details }; class X { std::vector&lt;Z&gt; vecZ; public: Z&amp; Z(size_t index) { // massive amounts of code for validating index Z&amp; ret = vecZ[index]; // even more code for determining that the Z instance // at index is *exactly* the right sort of Z (a process // which involves calculating leap years in which // religious holidays fall on Tuesdays for // the next thousand years or so) return ret; } const Z&amp; Z(size_t index) const { // identical to non-const X::Z(), except printed in // a lighter shade of gray since // we're running low on toner by this point } }; </code></pre> <p>The two member functions <code>X::Z()</code> and <code>X::Z() const</code> have identical code inside the braces. This is duplicate code <strong>and can cause maintenance problems for long functions with complex logic</strong>. </p> <p>Is there a way to avoid this code duplication?</p>
[ { "answer_id": 123765, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 7, "selected": true, "text": "class X\n{\n std::vector<Z> vecZ;\n\npublic:\n const Z& z(size_t index) const\n {\n // same really-really-really long access \n // and checking code as in OP\n // ...\n return vecZ[index];\n }\n\n Z& z(size_t index)\n {\n // One line. One ugly, ugly line - but just one line!\n return const_cast<Z&>( static_cast<const X&>(*this).z(index) );\n }\n\n #if 0 // A slightly less-ugly version\n Z& Z(size_t index)\n {\n // Two lines -- one cast. This is slightly less ugly but takes an extra line.\n const X& constMe = *this;\n return const_cast<Z&>( constMe.z(index) );\n }\n #endif\n};\n" }, { "answer_id": 123995, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 8, "selected": false, "text": "const const const struct C {\n const char & get() const {\n return c;\n }\n char & get() {\n return const_cast<char &>(static_cast<const C &>(*this).get());\n }\n char c;\n};\n const const" }, { "answer_id": 124209, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 5, "selected": false, "text": "class X {\n\n private:\n\n // This method MUST NOT be called except from boilerplate accessors.\n Z &_getZ(size_t index) const {\n return something;\n }\n\n // boilerplate accessors\n public:\n Z &getZ(size_t index) { return _getZ(index); }\n const Z &getZ(size_t index) const { return _getZ(index); }\n};\n" }, { "answer_id": 439642, "author": "Andy Balaam", "author_id": 22610, "author_profile": "https://Stackoverflow.com/users/22610", "pm_score": 3, "selected": false, "text": "#include <vector>\n\nclass Z\n{\n // details\n};\n\nclass X\n{\n std::vector<Z> vecZ;\n\npublic:\n const std::vector<Z>& GetVector() const { return vecZ; }\n std::vector<Z>& GetVector() { return vecZ; }\n\n Z& GetZ( size_t index );\n const Z& GetZ( size_t index ) const;\n};\n #include \"constnonconst.h\"\n\ntemplate< class ParentPtr, class Child >\nChild& GetZImpl( ParentPtr parent, size_t index )\n{\n // ... massive amounts of code ...\n\n // Note you may only use methods of X here that are\n // available in both const and non-const varieties.\n\n Child& ret = parent->GetVector()[index];\n\n // ... even more code ...\n\n return ret;\n}\n\nZ& X::GetZ( size_t index )\n{\n return GetZImpl< X*, Z >( this, index );\n}\n\nconst Z& X::GetZ( size_t index ) const\n{\n return GetZImpl< const X*, const Z >( this, index );\n}\n" }, { "answer_id": 16780327, "author": "Pait", "author_id": 1135781, "author_profile": "https://Stackoverflow.com/users/1135781", "pm_score": 5, "selected": false, "text": "template <typename T>\nstruct NonConst {typedef T type;};\ntemplate <typename T>\nstruct NonConst<T const> {typedef T type;}; //by value\ntemplate <typename T>\nstruct NonConst<T const&> {typedef T& type;}; //by reference\ntemplate <typename T>\nstruct NonConst<T const*> {typedef T* type;}; //by pointer\ntemplate <typename T>\nstruct NonConst<T const&&> {typedef T&& type;}; //by rvalue-reference\n\ntemplate<typename TConstReturn, class TObj, typename... TArgs>\ntypename NonConst<TConstReturn>::type likeConstVersion(\n TObj const* obj,\n TConstReturn (TObj::* memFun)(TArgs...) const,\n TArgs&&... args) {\n return const_cast<typename NonConst<TConstReturn>::type>(\n (obj->*memFun)(std::forward<TArgs>(args)...));\n}\n struct T {\n int arr[100];\n\n int const& getElement(size_t i) const{\n return arr[i];\n }\n\n int& getElement(size_t i) {\n return likeConstVersion(this, &T::getElement, i);\n }\n};\n" }, { "answer_id": 20452784, "author": "gd1", "author_id": 671092, "author_profile": "https://Stackoverflow.com/users/671092", "pm_score": 5, "selected": false, "text": "class X {\n\nprivate:\n\n std::vector<Z> v;\n\n template<typename InstanceType>\n static auto get(InstanceType& instance, std::size_t i) -> decltype(instance.get(i)) {\n // massive amounts of code for validating index\n // the instance variable has to be used to access class members\n return instance.v[i];\n }\n\npublic:\n\n const Z& get(std::size_t i) const {\n return get(*this, i);\n }\n\n Z& get(std::size_t i) {\n return get(*this, i);\n }\n\n};\n instance" }, { "answer_id": 27041552, "author": "Christer Swahn", "author_id": 1293773, "author_profile": "https://Stackoverflow.com/users/1293773", "pm_score": -1, "selected": false, "text": "struct C {\n shared_ptr<const char> get() const {\n return c;\n }\n shared_ptr<char> get() {\n return const_pointer_cast<char>(static_cast<const C &>(*this).get());\n }\n shared_ptr<char> c;\n};\n" }, { "answer_id": 30868615, "author": "matovitch", "author_id": 2312686, "author_profile": "https://Stackoverflow.com/users/2312686", "pm_score": 0, "selected": false, "text": "const_cast #include <iostream>\n\nclass MyClass\n{\n\npublic:\n\n int getI()\n {\n std::cout << \"non-const getter\" << std::endl;\n return privateGetI<MyClass, int>(*this);\n }\n\n const int getI() const\n {\n std::cout << \"const getter\" << std::endl;\n return privateGetI<const MyClass, const int>(*this);\n }\n\nprivate:\n\n template <class C, typename T>\n static T privateGetI(C c)\n {\n //do my stuff\n return c._i;\n }\n\n int _i;\n};\n\nint main()\n{\n const MyClass myConstClass = MyClass();\n myConstClass.getI();\n\n MyClass myNonConstClass;\n myNonConstClass.getI();\n\n return 0;\n}\n" }, { "answer_id": 32994882, "author": "dats", "author_id": 1029366, "author_profile": "https://Stackoverflow.com/users/1029366", "pm_score": 2, "selected": false, "text": "class X\n{\n std::vector<Z> vecZ;\n\n // ReturnType is explicitly 'Z&' or 'const Z&'\n // ThisType is deduced to be 'X' or 'const X'\n template <typename ReturnType, typename ThisType>\n static ReturnType Z_impl(ThisType& self, size_t index)\n {\n // massive amounts of code for validating index\n ReturnType ret = self.vecZ[index];\n // even more code for determining, blah, blah...\n return ret;\n }\n\npublic:\n Z& Z(size_t index)\n {\n return Z_impl<Z&>(*this, index);\n }\n const Z& Z(size_t index) const\n {\n return Z_impl<const Z&>(*this, index);\n }\n};\n" }, { "answer_id": 41156327, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": -1, "selected": false, "text": "struct C {\n int x[10];\n\n int const* getp() const { return x; }\n int const* getp(int i) const { return &x[i]; }\n int const* getp(int* p) const { return &x[*p]; }\n\n int const& getr() const { return x[0]; }\n int const& getr(int i) const { return x[i]; }\n int const& getr(int* p) const { return x[*p]; }\n\n template<typename... Ts>\n auto* getp(Ts... args) {\n auto const* p = this;\n return const_cast<int*>(p->getp(args...));\n }\n\n template<typename... Ts>\n auto& getr(Ts... args) {\n auto const* p = this;\n return const_cast<int&>(p->getr(args...));\n }\n};\n const template<typename T, typename... Ts>\n auto* pwrap(T const* (C::*f)(Ts...) const, Ts... args) {\n return const_cast<T*>((this->*f)(args...));\n }\n\n int* getp_i(int i) { return pwrap(&C::getp_i, i); }\n int* getp_p(int* p) { return pwrap(&C::getp_p, p); }\n template<typename... Ts>\n auto* getp(Ts... args) { return pwrap<int, Ts...>(&C::getp, args...); }\n const" }, { "answer_id": 41646237, "author": "user1476176", "author_id": 1476176, "author_profile": "https://Stackoverflow.com/users/1476176", "pm_score": 2, "selected": false, "text": "struct A {\n\n #define GETTER_CORE_CODE \\\n /* line 1 of getter code */ \\\n /* line 2 of getter code */ \\\n /* .....etc............. */ \\\n /* line n of getter code */ \n\n // ^ NOTE: line continuation char '\\' on all lines but the last\n\n B& get() {\n GETTER_CORE_CODE\n }\n\n const B& get() const {\n GETTER_CORE_CODE\n }\n\n #undef GETTER_CORE_CODE\n\n};\n" }, { "answer_id": 47369227, "author": "David Stone", "author_id": 852254, "author_profile": "https://Stackoverflow.com/users/852254", "pm_score": 6, "selected": false, "text": "T const & f() const {\n return something_complicated();\n}\nT & f() {\n return const_cast<T &>(std::as_const(*this).f());\n}\n volatile volatile template<typename T>\nconstexpr T & as_mutable(T const & value) noexcept {\n return const_cast<T &>(value);\n}\ntemplate<typename T>\nconstexpr T * as_mutable(T const * value) noexcept {\n return const_cast<T *>(value);\n}\ntemplate<typename T>\nconstexpr T * as_mutable(T * value) noexcept {\n return value;\n}\ntemplate<typename T>\nvoid as_mutable(T const &&) = delete;\n volatile decltype(auto) f() const {\n return something_complicated();\n}\ndecltype(auto) f() {\n return as_mutable(std::as_const(*this).f());\n}\n" }, { "answer_id": 55426147, "author": "axxel", "author_id": 2088798, "author_profile": "https://Stackoverflow.com/users/2088798", "pm_score": 3, "selected": false, "text": "#include <utility>\n#include <type_traits>\n\ntemplate <typename T> struct NonConst;\ntemplate <typename T> struct NonConst<T const&> {using type = T&;};\ntemplate <typename T> struct NonConst<T const*> {using type = T*;};\n\n#define NON_CONST(func) \\\n template <typename... T> auto func(T&&... a) \\\n -> typename NonConst<decltype(func(std::forward<T>(a)...))>::type \\\n { \\\n return const_cast<decltype(func(std::forward<T>(a)...))>( \\\n std::as_const(*this).func(std::forward<T>(a)...)); \\\n }\n class X\n{\n const Z& get(size_t index) const { ... }\n NON_CONST(get)\n};\n" }, { "answer_id": 56694496, "author": "TheOperator", "author_id": 5427663, "author_profile": "https://Stackoverflow.com/users/5427663", "pm_score": 2, "selected": false, "text": "FROM_CONST_OVERLOAD() class MyClass\n{\nprivate:\n std::vector<std::string> data = {\"str\", \"x\"};\n\npublic:\n // Works for references\n const std::string& GetRef(std::size_t index) const\n {\n return data[index];\n }\n\n std::string& GetRef(std::size_t index)\n {\n return FROM_CONST_OVERLOAD( GetRef(index) );\n }\n\n\n // Works for pointers\n const std::string* GetPtr(std::size_t index) const\n {\n return &data[index];\n }\n\n std::string* GetPtr(std::size_t index)\n {\n return FROM_CONST_OVERLOAD( GetPtr(index) );\n }\n};\n template <typename T>\nT& WithoutConst(const T& ref)\n{\n return const_cast<T&>(ref);\n}\n\ntemplate <typename T>\nT* WithoutConst(const T* ptr)\n{\n return const_cast<T*>(ptr);\n}\n\ntemplate <typename T>\nconst T* WithConst(T* ptr)\n{\n return ptr;\n}\n\n#define FROM_CONST_OVERLOAD(FunctionCall) \\\n WithoutConst(WithConst(this)->FunctionCall)\n return const_cast<Result&>( static_cast<const MyClass*>(this)->Method(args) );\n const_cast WithoutConst() WithConst() this this-> __VA_ARGS__ FROM_CONST_OVERLOAD( ) const_iterator std::shared_ptr<const T> WithoutConst() this->Method(args)" }, { "answer_id": 58466360, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 1, "selected": false, "text": "class A\n{\n int x; \n public:\n MAYBE_CONST(\n CV int &GetX() CV {return x;}\n CV int &GetY() CV {return y;}\n )\n\n // Equivalent to:\n // int &GetX() {return x;}\n // int &GetY() {return y;}\n // const int &GetX() const {return x;}\n // const int &GetY() const {return y;}\n};\n MAYBE_CONST CV const CV CV CV_IN // Doesn't work\nMAYBE_CONST( CV int &foo(CV int &); )\n\n// Works, expands to\n// int &foo( int &);\n// const int &foo(const int &);\nMAYBE_CONST( CV int &foo CV_IN(CV int &); )\n #define MAYBE_CONST(...) IMPL_CV_maybe_const( (IMPL_CV_null,__VA_ARGS__)() )\n#define CV )(IMPL_CV_identity,\n#define CV_IN(...) )(IMPL_CV_p_open,)(IMPL_CV_null,__VA_ARGS__)(IMPL_CV_p_close,)(IMPL_CV_null,\n\n#define IMPL_CV_null(...)\n#define IMPL_CV_identity(...) __VA_ARGS__\n#define IMPL_CV_p_open(...) (\n#define IMPL_CV_p_close(...) )\n\n#define IMPL_CV_maybe_const(seq) IMPL_CV_a seq IMPL_CV_const_a seq\n\n#define IMPL_CV_body(cv, m, ...) m(cv) __VA_ARGS__\n\n#define IMPL_CV_a(...) __VA_OPT__(IMPL_CV_body(,__VA_ARGS__) IMPL_CV_b)\n#define IMPL_CV_b(...) __VA_OPT__(IMPL_CV_body(,__VA_ARGS__) IMPL_CV_a)\n\n#define IMPL_CV_const_a(...) __VA_OPT__(IMPL_CV_body(const,__VA_ARGS__) IMPL_CV_const_b)\n#define IMPL_CV_const_b(...) __VA_OPT__(IMPL_CV_body(const,__VA_ARGS__) IMPL_CV_const_a)\n CV_IN #define MAYBE_CONST(...) IMPL_MC( ((__VA_ARGS__)) )\n#define CV ))((\n\n#define IMPL_MC(seq) \\\n IMPL_MC_end(IMPL_MC_a seq) \\\n IMPL_MC_end(IMPL_MC_const_0 seq)\n\n#define IMPL_MC_identity(...) __VA_ARGS__\n#define IMPL_MC_end(...) IMPL_MC_end_(__VA_ARGS__)\n#define IMPL_MC_end_(...) __VA_ARGS__##_end\n\n#define IMPL_MC_a(elem) IMPL_MC_identity elem IMPL_MC_b\n#define IMPL_MC_b(elem) IMPL_MC_identity elem IMPL_MC_a\n#define IMPL_MC_a_end\n#define IMPL_MC_b_end\n\n#define IMPL_MC_const_0(elem) IMPL_MC_identity elem IMPL_MC_const_a\n#define IMPL_MC_const_a(elem) const IMPL_MC_identity elem IMPL_MC_const_b\n#define IMPL_MC_const_b(elem) const IMPL_MC_identity elem IMPL_MC_const_a\n#define IMPL_MC_const_a_end\n#define IMPL_MC_const_b_end\n" }, { "answer_id": 59201205, "author": "atablash", "author_id": 1123898, "author_profile": "https://Stackoverflow.com/users/1123898", "pm_score": 3, "selected": false, "text": "#include <type_traits>\n\n#define REQUIRES(...) class = std::enable_if_t<(__VA_ARGS__)>\n#define REQUIRES_CV_OF(A,B) REQUIRES( std::is_same_v< std::remove_cv_t< A >, B > )\n\nclass Foobar {\nprivate:\n int something;\n\n template<class FOOBAR, REQUIRES_CV_OF(FOOBAR, Foobar)>\n static auto& _getSomething(FOOBAR& self, int index) {\n // big, non-trivial chunk of code...\n return self.something;\n }\n\npublic:\n auto& getSomething(int index) { return _getSomething(*this, index); }\n auto& getSomething(int index) const { return _getSomething(*this, index); }\n};\n" }, { "answer_id": 68100053, "author": "ivaigult", "author_id": 1282773, "author_profile": "https://Stackoverflow.com/users/1282773", "pm_score": 2, "selected": false, "text": "const_cast class Foo {\npublic:\n // not great, non-const calls const version but resorts to const_cast\n Bar& get_bar()\n {\n return const_cast<Bar&>(static_cast<const Foo&>(*this).get_bar());\n }\n const Bar& get_bar() const\n {\n /* the complex logic around getting a const reference to my_bar */\n }\nprivate:\n Bar my_bar;\n};\n class Foo {\npublic: // good\n Bar& get_bar() { return get_bar_impl(*this); }\n const Bar& get_bar() const { return get_bar_impl(*this); }\nprivate:\n Bar my_bar;\n\n template<class T> // good, deduces whether T is const or non-const\n static auto& get_bar_impl(T& t)\n { /* the complex logic around getting a possibly-const reference to my_bar */ }\n};\n" }, { "answer_id": 69486322, "author": "David Stone", "author_id": 852254, "author_profile": "https://Stackoverflow.com/users/852254", "pm_score": 4, "selected": false, "text": "struct s {\n auto && f(this auto && self) {\n // all the common code goes here\n }\n};\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ]
123,773
<p>I will choose Java as an example, most people know it, though every other OO language was working as well.</p> <p>Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.</p> <p>However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.</p> <p>Now there was this <a href="http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html" rel="noreferrer">article, saying it's better to inherit interfaces than implementations</a>, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the <a href="http://en.wikipedia.org/wiki/Fragile_base_class" rel="noreferrer">fragile base class problem</a>. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.</p> <p>What bugs me about this, is that implementation inheritance means <strong>code reuse</strong>, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?</p> <p>E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.</p> <p>How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?</p> <p>Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.</p> <p>Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like</p> <pre><code>public void move() { abstractCarObject.move(); } </code></pre> <p>?</p> <p>Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?</p>
[ { "answer_id": 123800, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 2, "selected": false, "text": "public class Car\n{\n private ICar _car;\n\n public void Move() {\n _car.Move();\n }\n}\n" }, { "answer_id": 124743, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 3, "selected": false, "text": "interface Stack<T> {\n public void push(T object);\n public T pop();\n public void clear();\n public int size();\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15809/" ]
123,776
<p>I have a page that has an iframe</p> <p>From one of the pages within the iframe I want to look back and make a panel on the default page invisible because it is overshadowing a popup</p> <p>I tried using Parent.FindControl but it does not seem to be working. I am positive I have the right id in the findcontrol because I used Firebug to inspect the panel and I copied the id from there</p> <p>Does anyone know what I am missing?</p>
[ { "answer_id": 124102, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<body>\n <input type=\"text\" id=\"accessme\" value=\"Not Accessed\" />\n ...\n</body>\n <head>\n ...\n <script type=\"text/javascript\">\n function setValueOfAccessme()\n {\n window.parent.document.getElementById(\"accessme\").value = \"Accessed\";\n }\n </script>\n</head>\n<body onload=\"setValueOfAccessme();\">\n</body>\n document object window object getElementId()" }, { "answer_id": 124127, "author": "Sean Gough", "author_id": 12842, "author_profile": "https://Stackoverflow.com/users/12842", "pm_score": 0, "selected": false, "text": "Public Shared Function MoreHelpfulFindControl(ByVal parent As UI.Control, ByVal id As String) As UI.Control\n If parent.ID = id Then Return parent\n For Each child As UI.Control In parent.Controls\n Dim recurse As UI.Control = MoreHelpfulFindControl(child, id)\n If recurse IsNot Nothing Then Return recurse\n Next\n Return Nothing\nEnd Function\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
123,781
<p>Is there a way to tell SQL Server 2008 Express to log every query (including each and every SELECT Query!) into a file?</p> <p>It's a Development machine, so the negative side effects of logging Select-Queries are not an issue.</p> <p>Before someone suggests using the SQL Profiler: This is not available in Express (does anyone know if it's available in the Web Edition?) and i'm looking for a way to log queries even when I am away.</p>
[ { "answer_id": 17819485, "author": "Dmytriy Voloshyn", "author_id": 1255305, "author_profile": "https://Stackoverflow.com/users/1255305", "pm_score": 5, "selected": false, "text": "SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]\nFROM sys.dm_exec_query_stats AS deqs\nCROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest\nORDER BY deqs.last_execution_time DESC\n" }, { "answer_id": 73472056, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 0, "selected": false, "text": "SELECT last_execution_time, text\nFROM sys.dm_exec_query_stats stats\nCROSS APPLY sys.dm_exec_sql_text(stats.sql_handle) \nORDER BY last_execution_time\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
123,783
<p>Many websites have the concept of sending messages from user to user. When you send a message to another user, the message would show up in their inbox. You could respond to the message, and it would show up as a new entry in that message thread. </p> <p>You should be able to see if you've read a given message already, and messages that have got a new response should be able to be at the top.</p> <p>How would you design the classes (or tables or whatever) to support such a system?</p>
[ { "answer_id": 123799, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": true, "text": "user\n id\n name\n\nmessages\n id\n to_user_id\n from_user_id\n title\n date\n\nmessage_post\n id\n message_id\n user_id\n message\n date\n" }, { "answer_id": 123808, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "tblMessage\nID BIGINT \nToUserID GUID/BIGINT\nFromUserID GUID/BIGINT\nSubject NVARCHAR(150)\nMessage NVARCHAR(Max)\nDateDeletedFrom DATETIME\nDateDeletedTo DATETIME\nDateSent DATETIME\nDateRead DATETIME\n" }, { "answer_id": 123811, "author": "Silas Snider", "author_id": 2933, "author_profile": "https://Stackoverflow.com/users/2933", "pm_score": 0, "selected": false, "text": "Table Message:\nid INTEGER\nrecipient_id INTEGER -- FK to users table\nsender_id INTEGER -- ditto\nsubject VARCHAR\nbody TEXT\n\nTable Thread\nparent_id -- FK to message table\nchild_id -- FK to message table\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17076/" ]
123,809
<p>If my code throws an exception, sometimes - not everytime - the jsf presents a blank page. I´m using facelets for layout. A similar error were reported at this <a href="http://forums.sun.com/thread.jspa?messageID=10237827" rel="nofollow noreferrer">Sun forumn´s post</a>, but without answers. Anyone else with the same problem, or have a solution? ;)</p> <p>Due to some requests. Here follow more datails:</p> <p>web.xml</p> <pre><code> &lt;error-page&gt; &lt;exception-type&gt;com.company.ApplicationResourceException&lt;/exception-type&gt; &lt;location&gt;/error.faces&lt;/location&gt; &lt;/error-page&gt; </code></pre> <p>And the stack related to jsf is printed after the real exception:</p> <pre><code>####&lt;Sep 23, 2008 5:42:55 PM GMT-03:00&gt; &lt;Error&gt; &lt;HTTP&gt; &lt;comp141&gt; &lt;AdminServer&gt; &lt;[ACTIVE] ExecuteThread: '3' for queue: 'weblogic.kernel.Default (self-tuning)'&gt; &lt;&lt;WLS Kernel&gt;&gt; &lt;&gt; &lt;&gt; &lt;1222202575662&gt; &lt;BEA-101107&gt; &lt;[weblogic.servlet.internal.WebAppServletContext@6d46b9 - appName: 'ControlPanelEAR', name: 'ControlPanelWeb', context-path: '/Web'] Problem occurred while serving the error page. javax.servlet.ServletException: viewId:/error.xhtml - View /error.xhtml could not be restored. at javax.faces.webapp.FacesServlet.service(FacesServlet.java:249) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175) at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:525) at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:261) at weblogic.servlet.internal.ForwardAction.run(ForwardAction.java:22) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(Unknown Source) at weblogic.servlet.internal.ErrorManager.handleException(ErrorManager.java:144) at weblogic.servlet.internal.WebAppServletContext.handleThrowableFromInvocation(WebAppServletContext.java:2201) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2053) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200) at weblogic.work.ExecuteThread.run(ExecuteThread.java:172) javax.faces.application.ViewExpiredException: viewId:/error.xhtml - View /error.xhtml could not be restored. at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:180) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:248) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124) </code></pre> <p>I´m using the jsf version <code>Mojarra 1.2_09</code>, <code>richfaces 3.2.1.GA</code> and <code>facelets 1.1.13</code>.</p> <p>Hope some help :(</p>
[ { "answer_id": 4972670, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "error.jsp message ServletException(Throwable rootCause) String.split(message, \";\"); null NullPointerException ServletException(String message, Throwable rootCause) null error.jsp" }, { "answer_id": 14159539, "author": "Christophe Roussy", "author_id": 657427, "author_profile": "https://Stackoverflow.com/users/657427", "pm_score": -1, "selected": false, "text": "ExceptionHandlerWrapper.handle" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21370/" ]
123,826
<p>I have a local mercurial repository with some site-specific changes in it. What I would like to do is set a couple files to be un-commitable so that they aren't automatically committed when I do an <code>hg commit</code> with no arguments.</p> <p>Right now, I'm doing complicated things with <code>mq</code> and guards to achieve this, pushing and popping and selecting guards to prevent my changes (which are checked into an mq patch) from getting committed.</p> <p>Is there an easier way to do this? I'm sick of reading the help for all the <code>mq</code> commands every time I want to commit a change that doesn't include my site-specific changes.</p>
[ { "answer_id": 123943, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 2, "selected": false, "text": ".hgignore" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6160/" ]
123,838
<p>Our clients will be uploading images to be printed on their documents and we have been asked to come up with a way to get the resolution of the image in order to warn them if the image has too low of a resolution and will look pixalated in the end-product</p> <p>If it comes to it we could also go with the dimensions if anyone knows how to get those but the resolution would be preferred</p> <p>Thank you</p>
[ { "answer_id": 123854, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 5, "selected": true, "text": "Image newImage = Image.FromFile(\"SampImag.jpg\");\nnewImage.HorizontalResolution\n" }, { "answer_id": 123869, "author": "jlew", "author_id": 7450, "author_profile": "https://Stackoverflow.com/users/7450", "pm_score": 2, "selected": false, "text": "Image image = Image.FromFile( [file] );\nGraphicsUnit unit = GraphicsUnit.Point;\nRectangleF rect = image.GetBounds( ref unit );\nfloat hres = image.HorizontalResolution;\nfloat vres = image.VerticalResolution;\n" }, { "answer_id": 123969, "author": "Brian ONeil", "author_id": 21371, "author_profile": "https://Stackoverflow.com/users/21371", "pm_score": 3, "selected": false, "text": "Image i = Image.FromFile(@\"fileName.jpg\");\ni.HorizontalResolution;\n int docHeight = (i.Height / i.VerticalResolution);\nint docWidth = (i.Width / i.HorizontalResolution);\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
123,842
<p>Am I missing something or is there truly no alternative (yet, I hope) to SVCUTIL.EXE for generating WCF Web service proxies? </p>
[ { "answer_id": 411791, "author": "flq", "author_id": 51428, "author_profile": "https://Stackoverflow.com/users/51428", "pm_score": 2, "selected": false, "text": "DuplexChannelFactory<IServerWithCallback> cf = \n new DuplexChannelFactory<IServerWithCallback>(\n new CallbackImpl(), \n new NetTcpBinding(), \n new EndpointAddress(\"net.tcp://localhost:9080/DataService\"));\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536/" ]
123,862
<p>I have a method that periodically (e.g. once in every 10 secs) try to connect to a server and read some data from it. The server might not be available all the time. If the server is not available the method throws an exception.</p> <p>What would be the best way to implement a wrapper method that doesn't throw an exception except if the server wasn't available for at least one minute?</p>
[ { "answer_id": 123901, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 2, "selected": false, "text": "//Create Timer\n//Start Timer\nbool connected = false;\n\nwhile (!connected)\n\n try {\n //Connect To DB\n\n connected = true;\n }\n catch (Exception ex) {\n if (more than 1 minute has passed)\n throw new Exception(ex);\n }\n\n}\n" }, { "answer_id": 123904, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 0, "selected": false, "text": "int count = 0;\n\nCheckServer(count);\n\npublic void CheckServer(count) {\ntry\n{\n // connect to server\n}\ncatch(Exception e)\n{\n if(count < MAX_ATTEMPTS) {\n // wait 10 seconds\n CheckServer(count++)\n }\n else {\n throw e;\n }\n}\n}\n" }, { "answer_id": 124072, "author": "Mark Verrey", "author_id": 16728, "author_profile": "https://Stackoverflow.com/users/16728", "pm_score": 0, "selected": false, "text": "class ServerTester : public Object\n{\n private bool failing;\n private ServerConnection serverConnection;\n private Time firstFailure;\n\n public ServerTester(): failing(false)\n {\n }\n\n public void TestServer() throws ServerException\n {\n try\n {\n serverConnection.Connect();\n failing = false;\n }\n catch (ServerException e)\n {\n if (failing)\n {\n if (Time::GetTime() - firstFailure > 60)\n {\n failing = false;\n throw e;\n }\n }\n else\n {\n firstFailure = Time::GetTime();\n failing = true;\n }\n }\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686/" ]
123,918
<p>System.IO.BinaryReader reads values in a little-endian format.</p> <p>I have a C# application connecting to a proprietary networking library on the server side. The server-side sends everything down in network byte order, as one would expect, but I find that dealing with this on the client side is awkward, particularly for unsigned values.</p> <pre><code>UInt32 length = (UInt32)IPAddress.NetworkToHostOrder(reader.ReadInt32()); </code></pre> <p>is the only way I've come up with to get a correct unsigned value out of the stream, but this seems both awkward and ugly, and I have yet to test if that's just going to clip off high-order values so that I have to do fun BitConverter stuff.</p> <p>Is there some way I'm missing short of writing a wrapper around the whole thing to avoid these ugly conversions on every read? It seems like there should be an endian-ness option on the reader to make things like this simpler, but I haven't come across anything.</p>
[ { "answer_id": 155297, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 4, "selected": true, "text": "/// <summary>\n/// Utilities for reading big-endian files\n/// </summary>\npublic class BigEndianReader\n{\n public BigEndianReader(BinaryReader baseReader)\n {\n mBaseReader = baseReader;\n }\n\n public short ReadInt16()\n {\n return BitConverter.ToInt16(ReadBigEndianBytes(2), 0);\n }\n\n public ushort ReadUInt16()\n {\n return BitConverter.ToUInt16(ReadBigEndianBytes(2), 0);\n }\n\n public uint ReadUInt32()\n {\n return BitConverter.ToUInt32(ReadBigEndianBytes(4), 0);\n }\n\n public byte[] ReadBigEndianBytes(int count)\n {\n byte[] bytes = new byte[count];\n for (int i = count - 1; i >= 0; i--)\n bytes[i] = mBaseReader.ReadByte();\n\n return bytes;\n }\n\n public byte[] ReadBytes(int count)\n {\n return mBaseReader.ReadBytes(count);\n }\n\n public void Close()\n {\n mBaseReader.Close();\n }\n\n public Stream BaseStream\n {\n get { return mBaseReader.BaseStream; }\n }\n\n private BinaryReader mBaseReader;\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21374/" ]
123,920
<p>I'm writing by own blogging engine in PHP with a MYSQL backend database. MY question is: How would you go about making user comments and blog posts include newlines wherever they are appropriate?</p> <p>For example, if a user hits the return key in the message/comments box how would this translate into a new line that would show in the browser when the comment is viewed?</p>
[ { "answer_id": 123937, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 3, "selected": false, "text": "<br />" }, { "answer_id": 123944, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "\\n\\n </p><p> \\n <br>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
123,927
<p>I'm writing a setup program to install an application to a USB drive. The application is meant to be used only from USB drives, so it would save an extra step for the user by automatically selecting USB drive to install to.</p> <p>I might explore using Nullsoft or MSI for install, but since I'm mostly familiar with .NET I initially plan to try either custom .NET installer or setup component on .NET.</p> <p>Is it possible to determine the drive letter of a USB flash drive on Windows using .NET? How?</p>
[ { "answer_id": 123948, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 5, "selected": true, "text": "from driveInfo in DriveInfo.GetDrives()\nwhere driveInfo.DriveType == DriveType.Removable && driveInfo.IsReady\nselect driveInfo.RootDirectory.FullName\n" }, { "answer_id": 124025, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 4, "selected": false, "text": "// browse all USB WMI physical disks\n\nforeach(ManagementObject drive in new ManagementObjectSearcher(\n \"select * from Win32_DiskDrive where InterfaceType='USB'\").Get())\n{\n // associate physical disks with partitions\n\n foreach(ManagementObject partition in new ManagementObjectSearcher(\n \"ASSOCIATORS OF {Win32_DiskDrive.DeviceID='\" + drive[\"DeviceID\"]\n + \"'} WHERE AssocClass = \n Win32_DiskDriveToDiskPartition\").Get())\n {\n Console.WriteLine(\"Partition=\" + partition[\"Name\"]);\n\n // associate partitions with logical disks (drive letter volumes)\n\n foreach(ManagementObject disk in new ManagementObjectSearcher(\n \"ASSOCIATORS OF {Win32_DiskPartition.DeviceID='\"\n + partition[\"DeviceID\"]\n + \"'} WHERE AssocClass =\n Win32_LogicalDiskToPartition\").Get())\n {\n Console.WriteLine(\"Disk=\" + disk[\"Name\"]);\n }\n }\n\n // this may display nothing if the physical disk\n\n // does not have a hardware serial number\n\n Console.WriteLine(\"Serial=\"\n + new ManagementObject(\"Win32_PhysicalMedia.Tag='\"\n + drive[\"DeviceID\"] + \"'\")[\"SerialNumber\"]);\n}\n" }, { "answer_id": 124029, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 4, "selected": false, "text": "IList<String> fullNames = new List<String>();\nforeach (DriveInfo driveInfo in DriveInfo.GetDrives()) {\n if (driveInfo.DriveType == DriveType.Removable) {\n fullNames.Add(driveInfo.RootDirectory.FullName);\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124/" ]
123,936
<p>Some of my colleagues use special comments on their bug fixes, for example:</p> <pre><code>// 2008-09-23 John Doe - bug 12345 // &lt;short description&gt; </code></pre> <p>Does this make sense?<br> Do you comment bug fixes in a special way?</p> <p>Please let me know.</p>
[ { "answer_id": 123965, "author": "henriksen", "author_id": 6181, "author_profile": "https://Stackoverflow.com/users/6181", "pm_score": 2, "selected": false, "text": "// Glenn F. Henriksen (<email@company.no) - 2008-09-23\n// <Short description>\n" }, { "answer_id": 123977, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 2, "selected": false, "text": "// <date> [my name] - Bug xxxxx happens when the foo parameter is null, but\n// some customers want the behavior. Jump through some hoops to find a default value.\n" }, { "answer_id": 3248635, "author": "StormianRootSolver", "author_id": 339485, "author_profile": "https://Stackoverflow.com/users/339485", "pm_score": 0, "selected": false, "text": "// I KNOW this may look strange to you, but I have to use\n// this special implementation here - if you don't understand that,\n// maybe you are the wrong person for the job.\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ]
123,945
<p>I have a Excel macro that generates a this error whenever it gets input of a specific format. Does anyone knows <strong>in general</strong> what an <em>advise flag</em> is OR where can I find information on this type of error? Thanks</p> <blockquote> <p>Runtime error -2147221503 (80040001): Automation error, Invalid advise flags</p> </blockquote>
[ { "answer_id": 123965, "author": "henriksen", "author_id": 6181, "author_profile": "https://Stackoverflow.com/users/6181", "pm_score": 2, "selected": false, "text": "// Glenn F. Henriksen (<email@company.no) - 2008-09-23\n// <Short description>\n" }, { "answer_id": 123977, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 2, "selected": false, "text": "// <date> [my name] - Bug xxxxx happens when the foo parameter is null, but\n// some customers want the behavior. Jump through some hoops to find a default value.\n" }, { "answer_id": 3248635, "author": "StormianRootSolver", "author_id": 339485, "author_profile": "https://Stackoverflow.com/users/339485", "pm_score": 0, "selected": false, "text": "// I KNOW this may look strange to you, but I have to use\n// this special implementation here - if you don't understand that,\n// maybe you are the wrong person for the job.\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ]
123,958
<p>In python is it possible to get or set a logical directory (as opposed to an absolute one).</p> <p>For example if I have:</p> <pre><code>/real/path/to/dir </code></pre> <p>and I have</p> <pre><code>/linked/path/to/dir </code></pre> <p>linked to the same directory.</p> <p>using os.getcwd and os.chdir will always use the absolute path</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.chdir('/linked/path/to/dir') &gt;&gt;&gt; print os.getcwd() /real/path/to/dir </code></pre> <p>The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.</p>
[ { "answer_id": 123985, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 5, "selected": true, "text": "os.getcwd() getcwd() pwd os.environ['PWD'] getcwd import os\nfrom subprocess import Popen, PIPE\n\nclass CwdKeeper(object):\n def __init__(self):\n self._cwd = os.environ.get(\"PWD\")\n if self._cwd is None: # no environment. fall back to calling pwd on shell\n self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip()\n self._os_getcwd = os.getcwd\n self._os_chdir = os.chdir\n\n def chdir(self, path):\n if not self._cwd:\n return self._os_chdir(path)\n p = os.path.normpath(os.path.join(self._cwd, path))\n result = self._os_chdir(p)\n self._cwd = p\n os.environ[\"PWD\"] = p\n return result\n\n def getcwd(self):\n if not self._cwd:\n return self._os_getcwd()\n return self._cwd\n\ncwd = CwdKeeper()\nprint cwd.getcwd()\n# use only cwd.chdir and cwd.getcwd from now on. \n# monkeypatch os if you want:\nos.chdir = cwd.chdir\nos.getcwd = cwd.getcwd\n# now you can use os.chdir and os.getcwd as normal.\n" }, { "answer_id": 27951538, "author": "radtek", "author_id": 2023392, "author_profile": "https://Stackoverflow.com/users/2023392", "pm_score": 1, "selected": false, "text": "import os\nos.popen('pwd').read().strip('\\n')\n >>> import os\n>>> os.popen('pwd').read()\n'/home/projteam/staging/site/proj\\n'\n>>> os.popen('pwd').read().strip('\\n')\n'/home/projteam/staging/site/proj'\n>>> # Also works if PWD env var is set\n>>> os.getenv('PWD')\n'/home/projteam/staging/site/proj'\n>>> # This gets actual path, not symlinked path\n>>> import subprocess\n>>> p = subprocess.Popen('pwd', stdout=subprocess.PIPE)\n>>> p.communicate()[0] # returns non-symlink path\n'/home/projteam/staging/deploys/20150114-141114/site/proj\\n'\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3051/" ]
123,976
<p>What is the best way to encrypt an URL with parameters in Java?</p>
[ { "answer_id": 124036, "author": "Internet Friend", "author_id": 18037, "author_profile": "https://Stackoverflow.com/users/18037", "pm_score": 0, "selected": false, "text": "java.net.URLEncoder.encode" }, { "answer_id": 970876, "author": "Denis", "author_id": 52472, "author_profile": "https://Stackoverflow.com/users/52472", "pm_score": 2, "selected": false, "text": " import java.net.URLDecoder;\nimport java.net.URLEncoder;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKey;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.spec.PBEParameterSpec;\n\n/**\n * An easy to use class to encrypt and decrypt a string. Just call the simplest\n * constructor and the needed methods.\n * \n */\n\npublic class StringEncryptor {\nprivate Cipher encryptCipher;\nprivate Cipher decryptCipher;\nprivate sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();\nprivate sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();\n\nfinal private String charset = \"UTF-8\";\nfinal private String defaultEncryptionPassword = \"PAOSIDUFHQWER98234QWE378AHASDF93HASDF9238HAJSDF923\";\nfinal private byte[] defaultSalt = {\n\n(byte) 0xa3, (byte) 0x21, (byte) 0x24, (byte) 0x2c,\n\n(byte) 0xf2, (byte) 0xd2, (byte) 0x3e, (byte) 0x19 };\n\n/**\n * The simplest constructor which will use a default password and salt to\n * encode the string.\n * \n * @throws SecurityException\n */\npublic StringEncryptor() throws SecurityException {\n setupEncryptor(defaultEncryptionPassword, defaultSalt);\n}\n\n/**\n * Dynamic constructor to give own key and salt to it which going to be used\n * to encrypt and then decrypt the given string.\n * \n * @param encryptionPassword\n * @param salt\n */\npublic StringEncryptor(String encryptionPassword, byte[] salt) {\n setupEncryptor(encryptionPassword, salt);\n}\n\npublic void init(char[] pass, byte[] salt, int iterations) throws SecurityException {\n try {\n PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);\n\n SecretKeyFactory kf = SecretKeyFactory.getInstance(\"PBEWithMD5AndDES\");\n\n SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));\n\n encryptCipher = Cipher.getInstance(\"PBEWithMD5AndDES/CBC/PKCS5Padding\");\n\n encryptCipher.init(Cipher.ENCRYPT_MODE, k, ps);\n\n decryptCipher = Cipher.getInstance(\"PBEWithMD5AndDES/CBC/PKCS5Padding\");\n\n decryptCipher.init(Cipher.DECRYPT_MODE, k, ps);\n } catch (Exception e) {\n throw new SecurityException(\"Could not initialize CryptoLibrary: \" + e.getMessage());\n }\n}\n\n/**\n * \n * method to decrypt a string.\n * \n * @param str\n * Description of the Parameter\n * \n * @return String the encrypted string.\n * \n * @exception SecurityException\n * Description of the Exception\n */\n\npublic synchronized String encrypt(String str) throws SecurityException {\n try {\n\n byte[] utf8 = str.getBytes(charset);\n\n byte[] enc = encryptCipher.doFinal(utf8);\n\n return URLEncoder.encode(encoder.encode(enc),charset);\n }\n\n catch (Exception e)\n\n {\n throw new SecurityException(\"Could not encrypt: \" + e.getMessage());\n }\n}\n\n/**\n * \n * method to encrypting a string.\n * \n * @param str\n * Description of the Parameter\n * \n * @return String the encrypted string.\n * \n * @exception SecurityException\n * Description of the Exception\n */\n\npublic synchronized String decrypt(String str) throws SecurityException {\n try {\n\n byte[] dec = decoder.decodeBuffer(URLDecoder.decode(str,charset));\n byte[] utf8 = decryptCipher.doFinal(dec);\n\n return new String(utf8, charset);\n\n } catch (Exception e) {\n throw new SecurityException(\"Could not decrypt: \" + e.getMessage());\n }\n}\n\nprivate void setupEncryptor(String defaultEncryptionPassword, byte[] salt) {\n\n java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());\n\n char[] pass = defaultEncryptionPassword.toCharArray();\n\n int iterations = 3;\n\n init(pass, salt, iterations);\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1408/" ]
123,979
<p>I have created a bunch of movie clips which all have similar names and then after some other event I have built up a string like:</p> <pre><code>var clipName = "barLeft42" </code></pre> <p>which is held inside another movie clip called 'thing'.</p> <p>I have been able to get hold of a reference using:</p> <pre><code>var movieClip = Eval( "_root.thing." + clipName ) </code></pre> <p>But that feels bad - is there a better way?</p>
[ { "answer_id": 124010, "author": "Ronnie", "author_id": 193, "author_profile": "https://Stackoverflow.com/users/193", "pm_score": 3, "selected": true, "text": "_root.thing[ \"barLeft42\" ]\n" }, { "answer_id": 125290, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 0, "selected": false, "text": "eval var movieClip = _root.thing[ \"barLeft42\" ]\n var movieClipArray = new Array();\nfor (var i=0; i<45; i++) {\n var mc = _root.thing.createEmptyMovieClip( \"barLeft\"+i, i );\n // ...\n movieClipArray.push( mc );\n}\n\n// ...\n\nvar movieClip = movieClipArray[ 42 ];\n" }, { "answer_id": 133561, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "for (var i=0; i<99; i++) {\n var clipName = _root.thing[\"barLeft\"+i];\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21214/" ]
123,986
<p>I need my program to work only with certain USB Flash drives (from a single manufacturer) and ignore all other USB Flash drives (from any other manufacturers).</p> <p>is it possible to check that specific USB card is inserted on windows using .NET 2.0? how?</p> <p>if I find it through WMI, can I somehow determine which drive letter the USB drive is on?</p>
[ { "answer_id": 124149, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": true, "text": "Console.WriteLine(\"Manufacturer: {0}\", queryObj[\"Manufacturer\"]);\n...\nConsole.WriteLine(\" Name: {0}\", c[\"Name\"]); // here it will print drive letter\n namespace WMISample\n{\n using System;\n using System.Management;\n\n public class MyWMIQuery\n {\n public static void Main()\n {\n try\n {\n ManagementObjectSearcher searcher =\n new ManagementObjectSearcher(\"root\\\\CIMV2\",\n \"SELECT * FROM Win32_DiskDrive\");\n\n foreach (ManagementObject queryObj in searcher.Get())\n {\n Console.WriteLine(\"DeviceID: {0}\", queryObj[\"DeviceID\"]);\n Console.WriteLine(\"PNPDeviceID: {0}\", queryObj[\"PNPDeviceID\"]);\n Console.WriteLine(\"Manufacturer: {0}\", queryObj[\"Manufacturer\"]);\n Console.WriteLine(\"Model: {0}\", queryObj[\"Model\"]);\n foreach (ManagementObject b in queryObj.GetRelated(\"Win32_DiskPartition\"))\n {\n Console.WriteLine(\" Name: {0}\", b[\"Name\"]);\n foreach (ManagementBaseObject c in b.GetRelated(\"Win32_LogicalDisk\"))\n {\n Console.WriteLine(\" Name: {0}\", c[\"Name\"]); // here it will print drive letter\n }\n }\n // ...\n Console.WriteLine(\"--------------------------------------------\");\n } \n }\n catch (ManagementException e)\n {\n Console.WriteLine(e.StackTrace);\n }\n\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 124157, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 2, "selected": false, "text": "Win32_USBControllerDevice Win32_DiskDrive" }, { "answer_id": 124165, "author": "Curtis", "author_id": 454247, "author_profile": "https://Stackoverflow.com/users/454247", "pm_score": 2, "selected": false, "text": "Set Drives = GetObject(\"winmgmts:{impersonationLevel=impersonate,(Backup)}\").ExecQuery(\"select * from Win32_DiskDrive\")\nfor each drive in drives\nWscript.echo \"Drive Information:\" & vbnewline & _\n \"Availability: \" & drive.Availability & vbnewline & _\n \"BytesPerSector: \" & drive.BytesPerSector & vbnewline & _\n \"Caption: \" & drive.Caption & vbnewline & _\n \"CompressionMethod: \" & drive.CompressionMethod & vbnewline & _\n \"ConfigManagerErrorCode: \" & drive.ConfigManagerErrorCode & vbnewline & _\n \"ConfigManagerUserConfig: \" & drive.ConfigManagerUserConfig & vbnewline & _\n \"CreationClassName: \" & drive.CreationClassName & vbnewline & _\n \"DefaultBlockSize: \" & drive.DefaultBlockSize & vbnewline & _\n \"Description: \" & drive.Description & vbnewline & _\n \"DeviceID: \" & drive.DeviceID & vbnewline & _\n \"ErrorCleared: \" & drive.ErrorCleared & vbnewline & _\n \"ErrorDescription: \" & drive.ErrorDescription & vbnewline & _\n \"ErrorMethodology: \" & drive.ErrorMethodology & vbnewline & _\n \"Index: \" & drive.Index & vbnewline & _\n \"InterfaceType: \" & drive.InterfaceType & vbnewline & _\n \"LastErrorCode: \" & drive.LastErrorCode & vbnewline & _\n \"Manufacturer: \" & drive.Manufacturer & vbnewline & _\n \"MaxBlockSize: \" & drive.MaxBlockSize & vbnewline & _\n \"MaxMediaSize: \" & drive.MaxMediaSize & vbnewline & _\n \"MediaLoaded: \" & drive.MediaLoaded & vbnewline & _\n \"MediaType: \" & drive.MediaType & vbnewline & _\n \"MinBlockSize: \" & drive.MinBlockSize & vbnewline & _\n \"Model: \" & drive.Model & vbnewline & _\n \"Name: \" & drive.Name & vbnewline & _\n \"NeedsCleaning: \" & drive.NeedsCleaning & vbnewline & _\n \"NumberOfMediaSupported: \" & drive.NumberOfMediaSupported & vbnewline & _\n \"Partitions: \" & drive.Partitions & vbnewline & _\n \"PNPDeviceID: \" & drive.PNPDeviceID & vbnewline & _\n \"PowerManagementSupported: \" & drive.PowerManagementSupported & vbnewline & _\n \"SCSIBus: \" & drive.SCSIBus & vbnewline & _\n \"SCSILogicalUnit: \" & drive.SCSILogicalUnit & vbnewline & _\n \"SCSIPort: \" & drive.SCSIPort & vbnewline & _\n \"SCSITargetId: \" & drive.SCSITargetId & vbnewline & _\n \"SectorsPerTrack: \" & drive.SectorsPerTrack & vbnewline & _\n \"Signature: \" & drive.Signature & vbnewline & _\n \"Size: \" & drive.Size & vbnewline & _\n \"Status: \" & drive.Status & vbnewline & _\n \"StatusInfo: \" & drive.StatusInfo & vbnewline & _\n \"SystemCreationClassName: \" & drive.SystemCreationClassName & vbnewline & _\n \"SystemName: \" & drive.SystemName & vbnewline & _ \n \"TotalCylinders: \" & drive.TotalCylinders & vbnewline & _ \n \"TotalHeads: \" & drive.TotalHeads & vbnewline & _ \n \"TotalSectors: \" & drive.TotalSectors & vbnewline & _ \n \"TotalTracks: \" & drive.TotalTracks & vbnewline & _ \n \"TracksPerCylinder: \" & drive.TracksPerCylinder & vbnewline\nnext\n" }, { "answer_id": 124186, "author": "Donald", "author_id": 17584, "author_profile": "https://Stackoverflow.com/users/17584", "pm_score": 0, "selected": false, "text": "Option Explicit\nDim objWMIService, objItem, colItems, strComputer\n\n' On Error Resume Next\nstrComputer = \".\"\n\nSet objWMIService = GetObject(\"winmgmts:\\\\\" _\n& strComputer & \"\\root\\cimv2\")\nSet colItems = objWMIService.ExecQuery(_\n\"Select Manufacturer from Win32_DiskDrive\")\n\nFor Each objItem in colItems\nWscript.Echo \"Computer: \" & objItem.SystemName & VbCr & _\n \"Manufacturer: \" & objItem.Manufacturer & VbCr & _\n \"Model: \" & objItem.Model\nNext\n" }, { "answer_id": 124264, "author": "Curtis", "author_id": 454247, "author_profile": "https://Stackoverflow.com/users/454247", "pm_score": 1, "selected": false, "text": "Win32_DiskDrive" }, { "answer_id": 6939169, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 0, "selected": false, "text": "using namespace System;\nusing namespace System::Management;\n\nvoid GetUSBDeviceList()\n{\n try\n {\n ManagementObjectSearcher^ searcher =\n gcnew ManagementObjectSearcher(\"root\\\\CIMV2\",\n \"SELECT * FROM Win32_DiskDrive\");\n\n for each (ManagementObject^ queryObj in searcher->Get())\n {\n Console::WriteLine(\"DeviceID: {0}\", queryObj[\"DeviceID\"]);\n Console::WriteLine(\"PNPDeviceID: {0}\", queryObj[\"PNPDeviceID\"]);\n Console::WriteLine(\"Manufacturer: {0}\", queryObj[\"Manufacturer\"]);\n Console::WriteLine(\"Model: {0}\", queryObj[\"Model\"]);\n for each (ManagementObject^ b in queryObj->GetRelated(\"Win32_DiskPartition\"))\n {\n Console::WriteLine(\" Name: {0}\", b[\"Name\"]);\n for each (ManagementBaseObject^ c in b->GetRelated(\"Win32_LogicalDisk\"))\n {\n Console::WriteLine(\" Name: {0}\", c[\"Name\"]); // here it will print drive letter\n }\n }\n // ...\n Console::WriteLine(\"--------------------------------------------\");\n } \n }\n catch (ManagementException^ e)\n {\n Console::WriteLine(e->StackTrace);\n }\n\n Console::ReadLine();\n}\n System.Management" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124/" ]
123,994
<p>I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle this server side?</p> <p>Example:</p> <pre><code>http://localhost:3399/Base64.aspx?VLTrap=VkxUcmFwIHNldCB0byAiRkRTQT8+PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg== </code></pre> <p>Produces:</p> <pre><code>VkxUcmFwIHNldCB0byAiRkRTQT8 PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg== </code></pre> <p>People have suggested URLEncoding the querystring:</p> <pre><code>System.Web.HttpUtility.UrlEncode(yourString) </code></pre> <p>I can't do that as I have no control over the calling routine (which is working fine with other languages).</p> <p>There was also the suggestion of replacing spaces with a plus sign:</p> <pre><code>Request.QueryString["VLTrap"].Replace(" ", "+"); </code></pre> <p>I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what <em>other</em> characters might be malformed in addition to the plus sign.</p> <p><strong><em>My main goal is to intercept the QueryString before it is run through the decoder.</em></strong></p> <p>To this end I tried looking at Request.QueryString.toString() but this contained the same malformed information. Is there any way to look at the raw QueryString <em>before</em> it is URLDecoded?</p> <p>After further testing it appears that .Net expects everything coming in from the QuerString to be URL encoded but the browser does not automatically URL encode GET requests.</p>
[ { "answer_id": 124014, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 0, "selected": false, "text": "Request.QueryString[\"VLTrap\"].Replace(\" \", \"+\");\n" }, { "answer_id": 124027, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 5, "selected": true, "text": "argument.Replace(' ', '+') HttpRequest.ServerVariables[\"QUERY_STRING\"]" }, { "answer_id": 124037, "author": "henriksen", "author_id": 6181, "author_profile": "https://Stackoverflow.com/users/6181", "pm_score": 1, "selected": false, "text": "System.Web.HttpUtility.UrlEncode(yourString)" }, { "answer_id": 207745, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 4, "selected": false, "text": "Request.QueryString[\"VLTrap\"].Replace(\" \", \"+\");\n" }, { "answer_id": 4803682, "author": "Oaresome", "author_id": 541806, "author_profile": "https://Stackoverflow.com/users/541806", "pm_score": 2, "selected": false, "text": "Server.URLDecode Server.URLEncode + string tokenID = Server.UrlDecode(Request.QueryString[\"TokenID\"]);\n %2b + string tokenID = Server.UrlDecode(Request.QueryString[\"TokenID\"]);\ntokenID = tokenID.Replace(\" \", \"+\");\n" }, { "answer_id": 22792900, "author": "Jacob VanScoy", "author_id": 2073460, "author_profile": "https://Stackoverflow.com/users/2073460", "pm_score": 2, "selected": false, "text": "System.Uri.UnescapeDataString(yourString) +" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7819/" ]
123,999
<p>Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the <strong>viewport</strong>)?</p> <p>(The question refers to Firefox.)</p>
[ { "answer_id": 125106, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 10, "selected": true, "text": "function elementInViewport(el) {\n var top = el.offsetTop;\n var left = el.offsetLeft;\n var width = el.offsetWidth;\n var height = el.offsetHeight;\n\n while(el.offsetParent) {\n el = el.offsetParent;\n top += el.offsetTop;\n left += el.offsetLeft;\n }\n\n return (\n top >= window.pageYOffset &&\n left >= window.pageXOffset &&\n (top + height) <= (window.pageYOffset + window.innerHeight) &&\n (left + width) <= (window.pageXOffset + window.innerWidth)\n );\n}\n function elementInViewport2(el) {\n var top = el.offsetTop;\n var left = el.offsetLeft;\n var width = el.offsetWidth;\n var height = el.offsetHeight;\n\n while(el.offsetParent) {\n el = el.offsetParent;\n top += el.offsetTop;\n left += el.offsetLeft;\n }\n\n return (\n top < (window.pageYOffset + window.innerHeight) &&\n left < (window.pageXOffset + window.innerWidth) &&\n (top + height) > window.pageYOffset &&\n (left + width) > window.pageXOffset\n );\n}\n" }, { "answer_id": 7557433, "author": "Dan", "author_id": 139361, "author_profile": "https://Stackoverflow.com/users/139361", "pm_score": 11, "selected": false, "text": "function isElementInViewport (el) {\n\n // Special bonus for those using jQuery\n if (typeof jQuery === \"function\" && el instanceof jQuery) {\n el = el[0];\n }\n\n var rect = el.getBoundingClientRect();\n\n return (\n rect.top >= 0 &&\n rect.left >= 0 &&\n rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */\n rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */\n );\n}\n <body> function onVisibilityChange(el, callback) {\n var old_visible;\n return function () {\n var visible = isElementInViewport(el);\n if (visible != old_visible) {\n old_visible = visible;\n if (typeof callback == 'function') {\n callback();\n }\n }\n }\n}\n\nvar handler = onVisibilityChange(el, function() {\n /* Your code go here */\n});\n\n\n// jQuery\n$(window).on('DOMContentLoaded load resize scroll', handler);\n\n/* // Non-jQuery\nif (window.addEventListener) {\n addEventListener('DOMContentLoaded', handler, false);\n addEventListener('load', handler, false);\n addEventListener('scroll', handler, false);\n addEventListener('resize', handler, false);\n} else if (window.attachEvent) {\n attachEvent('onDOMContentLoaded', handler); // Internet Explorer 9+ :(\n attachEvent('onload', handler);\n attachEvent('onscroll', handler);\n attachEvent('onresize', handler);\n}\n*/\n handler() onrepaint DOMContentLoaded window.onload /* TODO: this looks like a very bad code */\nsetInterval(handler, 600);\n z-index overflow-scroll" }, { "answer_id": 12418814, "author": "ryanve", "author_id": 770127, "author_profile": "https://Stackoverflow.com/users/770127", "pm_score": 6, "selected": false, "text": "function inViewport (element) {\n if (!element) return false;\n if (1 !== element.nodeType) return false;\n\n var html = document.documentElement;\n var rect = element.getBoundingClientRect();\n\n return !!rect &&\n rect.bottom >= 0 &&\n rect.right >= 0 && \n rect.left <= html.clientWidth &&\n rect.top <= html.clientHeight;\n}\n true" }, { "answer_id": 14768915, "author": "rainyjune", "author_id": 2053738, "author_profile": "https://Stackoverflow.com/users/2053738", "pm_score": 2, "selected": false, "text": "function getViewportSize(w) {\n var w = w || window;\n if(w.innerWidth != null)\n return {w:w.innerWidth, h:w.innerHeight};\n var d = w.document;\n if (document.compatMode == \"CSS1Compat\") {\n return {\n w: d.documentElement.clientWidth,\n h: d.documentElement.clientHeight\n };\n }\n return { w: d.body.clientWidth, h: d.body.clientWidth };\n}\n\n\nfunction isViewportVisible(e) {\n var box = e.getBoundingClientRect();\n var height = box.height || (box.bottom - box.top);\n var width = box.width || (box.right - box.left);\n var viewport = getViewportSize();\n if(!height || !width)\n return false;\n if(box.top > viewport.h || box.bottom < 0)\n return false;\n if(box.right < 0 || box.left > viewport.w)\n return false;\n return true;\n}\n" }, { "answer_id": 15203639, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 8, "selected": false, "text": "clip isElementVisible() function isElementVisible(el) {\n var rect = el.getBoundingClientRect(),\n vWidth = window.innerWidth || document.documentElement.clientWidth,\n vHeight = window.innerHeight || document.documentElement.clientHeight,\n efp = function (x, y) { return document.elementFromPoint(x, y) }; \n\n // Return false if it's not in the viewport\n if (rect.right < 0 || rect.bottom < 0 \n || rect.left > vWidth || rect.top > vHeight)\n return false;\n\n // Return true if any of its four corners are visible\n return (\n el.contains(efp(rect.left, rect.top))\n || el.contains(efp(rect.right, rect.top))\n || el.contains(efp(rect.right, rect.bottom))\n || el.contains(efp(rect.left, rect.bottom))\n );\n}\n element.getBoundingClientRect() document.elementFromPoint() contains() document.elementFromPoint()" }, { "answer_id": 16270434, "author": "Walf", "author_id": 315024, "author_profile": "https://Stackoverflow.com/users/315024", "pm_score": 7, "selected": false, "text": "true function isElementInViewport(el) {\n var rect = el.getBoundingClientRect();\n\n return rect.bottom > 0 &&\n rect.right > 0 &&\n rect.left < (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ &&\n rect.top < (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */;\n}\n" }, { "answer_id": 21626820, "author": "Ally", "author_id": 837649, "author_profile": "https://Stackoverflow.com/users/837649", "pm_score": 3, "selected": false, "text": "var visibleY = function(el){\n var top = el.getBoundingClientRect().top, rect, el = el.parentNode;\n do {\n rect = el.getBoundingClientRect();\n if (top <= rect.bottom === false)\n return false;\n el = el.parentNode;\n } while (el != document.body);\n // Check it's within the document viewport\n return top <= document.documentElement.clientHeight;\n};\n" }, { "answer_id": 23234031, "author": "Eric Chen", "author_id": 3558652, "author_profile": "https://Stackoverflow.com/users/3558652", "pm_score": 5, "selected": false, "text": "function isElementOutViewport(el){\n var rect = el.getBoundingClientRect();\n return rect.bottom < 0 || rect.right < 0 || rect.left > window.innerWidth || rect.top > window.innerHeight;\n}\n" }, { "answer_id": 26039199, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 5, "selected": false, "text": "function isElementPartiallyInViewport(el)\n{\n // Special bonus for those using jQuery\n if (typeof jQuery !== 'undefined' && el instanceof jQuery) \n el = el[0];\n\n var rect = el.getBoundingClientRect();\n // DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }\n var windowHeight = (window.innerHeight || document.documentElement.clientHeight);\n var windowWidth = (window.innerWidth || document.documentElement.clientWidth);\n\n // http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap\n var vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);\n var horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);\n\n return (vertInView && horInView);\n}\n\n\n// http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport\nfunction isElementInViewport (el)\n{\n // Special bonus for those using jQuery\n if (typeof jQuery !== 'undefined' && el instanceof jQuery) \n el = el[0];\n\n var rect = el.getBoundingClientRect();\n var windowHeight = (window.innerHeight || document.documentElement.clientHeight);\n var windowWidth = (window.innerWidth || document.documentElement.clientWidth);\n\n return (\n (rect.left >= 0)\n && (rect.top >= 0)\n && ((rect.left + rect.width) <= windowWidth)\n && ((rect.top + rect.height) <= windowHeight)\n );\n}\n\n\nfunction fnIsVis(ele)\n{\n var inVpFull = isElementInViewport(ele);\n var inVpPartial = isElementPartiallyInViewport(ele);\n console.clear();\n console.log(\"Fully in viewport: \" + inVpFull);\n console.log(\"Partially in viewport: \" + inVpPartial);\n}\n <!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\">\n <meta name=\"description\" content=\"\">\n <meta name=\"author\" content=\"\">\n <title>Test</title>\n <!--\n <script src=\"http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js\"></script>\n <script src=\"scrollMonitor.js\"></script>\n -->\n\n <script type=\"text/javascript\">\n\n function isElementPartiallyInViewport(el)\n {\n // Special bonus for those using jQuery\n if (typeof jQuery !== 'undefined' && el instanceof jQuery) \n el = el[0];\n\n var rect = el.getBoundingClientRect();\n // DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }\n var windowHeight = (window.innerHeight || document.documentElement.clientHeight);\n var windowWidth = (window.innerWidth || document.documentElement.clientWidth);\n\n // http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap\n var vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);\n var horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);\n\n return (vertInView && horInView);\n }\n\n\n // http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport\n function isElementInViewport (el)\n {\n // Special bonus for those using jQuery\n if (typeof jQuery !== 'undefined' && el instanceof jQuery) \n el = el[0];\n\n var rect = el.getBoundingClientRect();\n var windowHeight = (window.innerHeight || document.documentElement.clientHeight);\n var windowWidth = (window.innerWidth || document.documentElement.clientWidth);\n\n return (\n (rect.left >= 0)\n && (rect.top >= 0)\n && ((rect.left + rect.width) <= windowWidth)\n && ((rect.top + rect.height) <= windowHeight)\n );\n }\n\n\n function fnIsVis(ele)\n {\n var inVpFull = isElementInViewport(ele);\n var inVpPartial = isElementPartiallyInViewport(ele);\n console.clear();\n console.log(\"Fully in viewport: \" + inVpFull);\n console.log(\"Partially in viewport: \" + inVpPartial);\n }\n\n\n // var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft,\n // var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;\n </script>\n</head>\n\n<body>\n <div style=\"display: block; width: 2000px; height: 10000px; background-color: green;\">\n\n <br /><br /><br /><br /><br /><br />\n <br /><br /><br /><br /><br /><br />\n <br /><br /><br /><br /><br /><br />\n\n <input type=\"button\" onclick=\"fnIsVis(document.getElementById('myele'));\" value=\"det\" />\n\n <br /><br /><br /><br /><br /><br />\n <br /><br /><br /><br /><br /><br />\n <br /><br /><br /><br /><br /><br />\n\n <div style=\"background-color: crimson; display: inline-block; width: 800px; height: 500px;\" ></div>\n <div id=\"myele\" onclick=\"fnIsVis(this);\" style=\"display: inline-block; width: 100px; height: 100px; background-color: hotpink;\">\n t\n </div>\n\n <br /><br /><br /><br /><br /><br />\n <br /><br /><br /><br /><br /><br />\n <br /><br /><br /><br /><br /><br />\n\n <input type=\"button\" onclick=\"fnIsVis(document.getElementById('myele'));\" value=\"det\" />\n </div>\n\n <!--\n <script type=\"text/javascript\">\n\n var element = document.getElementById(\"myele\");\n var watcher = scrollMonitor.create(element);\n\n watcher.lock();\n\n watcher.stateChange(function() {\n console.log(\"state changed\");\n // $(element).toggleClass('fixed', this.isAboveViewport)\n });\n </script>\n -->\n</body>\n</html>\n" }, { "answer_id": 27661928, "author": "Pirijan", "author_id": 2318064, "author_profile": "https://Stackoverflow.com/users/2318064", "pm_score": 2, "selected": false, "text": "$(function() {\n\n $(window).on('load resize scroll', function() {\n addClassToElementInViewport($('.bug-icon'), 'animate-bug-icon');\n addClassToElementInViewport($('.another-thing'), 'animate-thing');\n // repeat as needed ...\n });\n\n function addClassToElementInViewport(element, newClass) {\n if (inViewport(element)) {\n element.addClass(newClass);\n }\n }\n\n function inViewport(element) {\n if (typeof jQuery === \"function\" && element instanceof jQuery) {\n element = element[0];\n }\n var elementBounds = element.getBoundingClientRect();\n return (\n elementBounds.top >= 0 &&\n elementBounds.left >= 0 &&\n elementBounds.bottom <= $(window).height() &&\n elementBounds.right <= $(window).width()\n );\n }\n\n});\n" }, { "answer_id": 27742095, "author": "Lumic", "author_id": 3057243, "author_profile": "https://Stackoverflow.com/users/3057243", "pm_score": 1, "selected": false, "text": "function inView(element) {\n var box = element.getBoundingClientRect();\n return inViewBox(box);\n}\n\nfunction inViewBox(box) {\n return ((box.bottom < 0) || (box.top > getWindowSize().h)) ? false : true;\n}\n\n\nfunction getWindowSize() {\n return { w: document.body.offsetWidth || document.documentElement.offsetWidth || window.innerWidth, h: document.body.offsetHeight || document.documentElement.offsetHeight || window.innerHeight}\n}\n" }, { "answer_id": 28238393, "author": "Adam Rehal", "author_id": 4511714, "author_profile": "https://Stackoverflow.com/users/4511714", "pm_score": 3, "selected": false, "text": "var element = $(\"#element\");\nvar topOfElement = element.offset().top;\nvar bottomOfElement = element.offset().top + element.outerHeight(true);\nvar $window = $(window);\n\n$window.bind('scroll', function() {\n\n var scrollTopPosition = $window.scrollTop()+$window.height();\n var windowScrollTop = $window.scrollTop()\n\n if (windowScrollTop > topOfElement && windowScrollTop < bottomOfElement) {\n // Element is partially visible (above viewable area)\n console.log(\"Element is partially visible (above viewable area)\");\n\n } else if (windowScrollTop > bottomOfElement && windowScrollTop > topOfElement) {\n // Element is hidden (above viewable area)\n console.log(\"Element is hidden (above viewable area)\");\n\n } else if (scrollTopPosition < topOfElement && scrollTopPosition < bottomOfElement) {\n // Element is hidden (below viewable area)\n console.log(\"Element is hidden (below viewable area)\");\n\n } else if (scrollTopPosition < bottomOfElement && scrollTopPosition > topOfElement) {\n // Element is partially visible (below viewable area)\n console.log(\"Element is partially visible (below viewable area)\");\n\n } else {\n // Element is completely visible\n console.log(\"Element is completely visible\");\n }\n});\n" }, { "answer_id": 29851178, "author": "ton", "author_id": 2397613, "author_profile": "https://Stackoverflow.com/users/2397613", "pm_score": 3, "selected": false, "text": "/**\n * fullVisible=true only returns true if the all object rect is visible\n */\nfunction isReallyVisible(el, fullVisible) {\n if ( el.tagName == \"HTML\" )\n return true;\n var parentRect=el.parentNode.getBoundingClientRect();\n var rect = arguments[2] || el.getBoundingClientRect();\n return (\n ( fullVisible ? rect.top >= parentRect.top : rect.bottom > parentRect.top ) &&\n ( fullVisible ? rect.left >= parentRect.left : rect.right > parentRect.left ) &&\n ( fullVisible ? rect.bottom <= parentRect.bottom : rect.top < parentRect.bottom ) &&\n ( fullVisible ? rect.right <= parentRect.right : rect.left < parentRect.right ) &&\n isReallyVisible(el.parentNode, fullVisible, rect)\n );\n};\n" }, { "answer_id": 31772470, "author": "r3wt", "author_id": 2401804, "author_profile": "https://Stackoverflow.com/users/2401804", "pm_score": 5, "selected": false, "text": "$.fn.inView = function(){\n if(!this.length) \n return false;\n var rect = this.get(0).getBoundingClientRect();\n\n return (\n rect.top >= 0 &&\n rect.left >= 0 &&\n rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&\n rect.right <= (window.innerWidth || document.documentElement.clientWidth)\n );\n\n};\n\n// Additional examples for other use cases\n// Is true false whether an array of elements are all in view\n$.fn.allInView = function(){\n var all = [];\n this.forEach(function(){\n all.push( $(this).inView() );\n });\n return all.indexOf(false) === -1;\n};\n\n// Only the class elements in view\n$('.some-class').filter(function(){\n return $(this).inView();\n});\n\n// Only the class elements not in view\n$('.some-class').filter(function(){\n return !$(this).inView();\n});\n $(window).on('scroll',function(){\n\n if( $('footer').inView() ) {\n // Do cool stuff\n }\n});\n" }, { "answer_id": 32550413, "author": "www139", "author_id": 3011082, "author_profile": "https://Stackoverflow.com/users/3011082", "pm_score": 2, "selected": false, "text": "// Scrolling handlers...\nwindow.onscroll = function(){\n var elements = document.getElementById('whatever').getElementsByClassName('whatever');\n for(var i = 0; i != elements.length; i++)\n {\n if(elements[i].getBoundingClientRect().top <= window.innerHeight*0.75 &&\n elements[i].getBoundingClientRect().top > 0)\n {\n console.log(elements[i].nodeName + ' ' +\n elements[i].className + ' ' +\n elements[i].id +\n ' is in the viewport; proceed with whatever code you want to do here.');\n }\n};\n" }, { "answer_id": 35988595, "author": "Philzen", "author_id": 1246547, "author_profile": "https://Stackoverflow.com/users/1246547", "pm_score": -1, "selected": false, "text": "var parent = this.parentNode,\n parentComputedStyle = window.getComputedStyle(parent, null),\n parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width')),\n parentBorderLeftWidth = parseInt(parentComputedStyle.getPropertyValue('border-left-width')),\n overTop = this.offsetTop - parent.offsetTop < parent.scrollTop,\n overBottom = (this.offsetTop - parent.offsetTop + this.clientHeight - parentBorderTopWidth) > (parent.scrollTop + parent.clientHeight),\n overLeft = this.offsetLeft - parent.offsetLeft < parent.scrollLeft,\n overRight = (this.offsetLeft - parent.offsetLeft + this.clientWidth - parentBorderLeftWidth) > (parent.scrollLeft + parent.clientWidth),\n alignWithTop = overTop && !overBottom;\n this overTop overBottom" }, { "answer_id": 37998526, "author": "Domysee", "author_id": 3107430, "author_profile": "https://Stackoverflow.com/users/3107430", "pm_score": 4, "selected": false, "text": "Element.prototype.isVisible = function(percentX, percentY){\n var tolerance = 0.01; //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals\n if(percentX == null){\n percentX = 100;\n }\n if(percentY == null){\n percentY = 100;\n }\n\n var elementRect = this.getBoundingClientRect();\n var parentRects = [];\n var element = this;\n\n while(element.parentElement != null){\n parentRects.push(element.parentElement.getBoundingClientRect());\n element = element.parentElement;\n }\n\n var visibleInAllParents = parentRects.every(function(parentRect){\n var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);\n var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);\n var visiblePercentageX = visiblePixelX / elementRect.width * 100;\n var visiblePercentageY = visiblePixelY / elementRect.height * 100;\n return visiblePercentageX + tolerance > percentX && visiblePercentageY + tolerance > percentY;\n });\n return visibleInAllParents;\n};\n opacity: 0" }, { "answer_id": 41628998, "author": "Sander Jonk", "author_id": 5470653, "author_profile": "https://Stackoverflow.com/users/5470653", "pm_score": 0, "selected": false, "text": "function elementInViewport(el) {\n var elinfo = {\n \"top\":el.offsetTop,\n \"height\":el.offsetHeight,\n };\n\n if (elinfo.top + elinfo.height < window.pageYOffset || elinfo.top > window.pageYOffset + window.innerHeight) {\n return false;\n } else {\n return true;\n }\n\n}\n" }, { "answer_id": 44628557, "author": "Stevan Tosic", "author_id": 6166504, "author_profile": "https://Stackoverflow.com/users/6166504", "pm_score": 1, "selected": false, "text": "$(window).on('scroll', function () {\n\n var container = $('#sidebar');\n var containerHeight = container.height();\n var scrollPosition = $('#row1').offset().top - container.offset().top;\n\n if (containerHeight < scrollPosition) {\n console.log('not visible');\n } else {\n console.log('visible');\n }\n})\n" }, { "answer_id": 52552890, "author": "ssten", "author_id": 7379503, "author_profile": "https://Stackoverflow.com/users/7379503", "pm_score": 2, "selected": false, "text": "function inParentViewport(el, pa) {\n if (typeof jQuery === \"function\"){\n if (el instanceof jQuery)\n el = el[0];\n if (pa instanceof jQuery)\n pa = pa[0];\n }\n\n var e = el.getBoundingClientRect();\n var p = pa.getBoundingClientRect();\n\n return (\n e.bottom >= p.top &&\n e.right >= p.left &&\n e.top <= p.bottom &&\n e.left <= p.right\n );\n}\n" }, { "answer_id": 55181673, "author": "Randy Casburn", "author_id": 9078341, "author_profile": "https://Stackoverflow.com/users/9078341", "pm_score": 5, "selected": false, "text": "const buttonToHide = document.querySelector('button');\n\nconst hideWhenBoxInView = new IntersectionObserver((entries) => {\n if (entries[0].intersectionRatio <= 0) { // If not in view\n buttonToHide.style.display = \"inherit\";\n } else {\n buttonToHide.style.display = \"none\";\n }\n});\n\nhideWhenBoxInView.observe(document.getElementById('box')); header {\n position: fixed;\n top: 0;\n width: 100vw;\n height: 30px;\n background-color: lightgreen;\n}\n\n.wrapper {\n position: relative;\n margin-top: 600px;\n}\n\n#box {\n position: relative;\n left: 175px;\n width: 150px;\n height: 135px;\n background-color: lightblue;\n border: 2px solid;\n} <script src=\"https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver\"></script>\n<header>\n <button>NAVIGATION BUTTON TO HIDE</button>\n</header>\n <div class=\"wrapper\">\n <div id=\"box\">\n </div>\n </div>" }, { "answer_id": 55184434, "author": "JuanM.", "author_id": 3204227, "author_profile": "https://Stackoverflow.com/users/3204227", "pm_score": 2, "selected": false, "text": "function isVisible(elem) {\n var coords = elem.getBoundingClientRect();\n return Math.abs(coords.top) <= coords.height;\n}\n" }, { "answer_id": 57279138, "author": "leonheess", "author_id": 7910454, "author_profile": "https://Stackoverflow.com/users/7910454", "pm_score": 5, "selected": false, "text": "function isInView(el) {\n const box = el.getBoundingClientRect();\n return box.top < window.innerHeight && box.bottom >= 0;\n}\n" }, { "answer_id": 57904822, "author": "Berker Yüceer", "author_id": 861019, "author_profile": "https://Stackoverflow.com/users/861019", "pm_score": 2, "selected": false, "text": "visible visible parent element overflow-scroll // For checking element visibility from any sides\nisVisible(element)\n\n// For checking elements visibility in a parent you would like to check\nvar parent = document; // Assuming you check if 'element' inside 'document'\nisVisible(element, parent)\n\n// For checking elements visibility even if it's bigger than viewport\nisVisible(element, null, true) // Without parent choice\nisVisible(element, parent, true) // With parent choice\n crossSearchAlgorithm function isVisible(element, parent, crossSearchAlgorithm) {\n var rect = element.getBoundingClientRect(),\n prect = (parent != undefined) ? parent.getBoundingClientRect() : element.parentNode.getBoundingClientRect(),\n csa = (crossSearchAlgorithm != undefined) ? crossSearchAlgorithm : false,\n efp = function (x, y) { return document.elementFromPoint(x, y) };\n // Return false if it's not in the viewport\n if (rect.right < prect.left || rect.bottom < prect.top || rect.left > prect.right || rect.top > prect.bottom) {\n return false;\n }\n var flag = false;\n // Return true if left to right any border pixel reached\n for (var x = rect.left; x < rect.right; x++) {\n if (element.contains(efp(rect.top, x)) || element.contains(efp(rect.bottom, x))) {\n flag = true;\n break;\n }\n }\n // Return true if top to bottom any border pixel reached\n if (flag == false) {\n for (var y = rect.top; y < rect.bottom; y++) {\n if (element.contains(efp(rect.left, y)) || element.contains(efp(rect.right, y))) {\n flag = true;\n break;\n }\n }\n }\n if(csa) {\n // Another algorithm to check if element is centered and bigger than viewport\n if (flag == false) {\n var x = rect.left;\n var y = rect.top;\n // From top left to bottom right\n while(x < rect.right || y < rect.bottom) {\n if (element.contains(efp(x,y))) {\n flag = true;\n break;\n }\n if(x < rect.right) { x++; }\n if(y < rect.bottom) { y++; }\n }\n if (flag == false) {\n x = rect.right;\n y = rect.top;\n // From top right to bottom left\n while(x > rect.left || y < rect.bottom) {\n if (element.contains(efp(x,y))) {\n flag = true;\n break;\n }\n if(x > rect.left) { x--; }\n if(y < rect.bottom) { y++; }\n }\n }\n }\n }\n return flag;\n}\n\n// Check multiple elements visibility\ndocument.getElementById('container').addEventListener(\"scroll\", function() {\n var elementList = document.getElementsByClassName(\"element\");\n var console = document.getElementById('console');\n for (var i=0; i < elementList.length; i++) {\n // I did not define parent, so it will be element's parent\n if (isVisible(elementList[i])) {\n console.innerHTML = \"Element with id[\" + elementList[i].id + \"] is visible!\";\n break;\n } else {\n console.innerHTML = \"Element with id[\" + elementList[i].id + \"] is hidden!\";\n }\n }\n});\n\n// Dynamically added elements\nfor(var i=4; i <= 6; i++) {\n var newElement = document.createElement(\"div\");\n newElement.id = \"element\" + i;\n newElement.classList.add(\"element\");\n document.getElementById('container').appendChild(newElement);\n} #console { background-color: yellow; }\n#container {\n width: 300px;\n height: 100px;\n background-color: lightblue;\n overflow-y: auto;\n padding-top: 150px;\n margin: 45px;\n}\n.element {\n margin: 400px;\n width: 400px;\n height: 320px;\n background-color: green;\n}\n#element3 {\n position: relative;\n margin: 40px;\n width: 720px;\n height: 520px;\n background-color: green;\n}\n#element3::before {\n content: \"\";\n position: absolute;\n top: -10px;\n left: -10px;\n margin: 0px;\n width: 740px;\n height: 540px;\n border: 5px dotted green;\n background: transparent;\n} <div id=\"console\"></div>\n<div id=\"container\">\n <div id=\"element1\" class=\"element\"></div>\n <div id=\"element2\" class=\"element\"></div>\n <div id=\"element3\" class=\"element\"></div>\n</div> crossSearchAlgorithm visible function isVisible(element, parent, crossSearchAlgorithm) {\n var rect = element.getBoundingClientRect(),\n prect = (parent != undefined) ? parent.getBoundingClientRect() : element.parentNode.getBoundingClientRect(),\n csa = (crossSearchAlgorithm != undefined) ? crossSearchAlgorithm : false,\n efp = function (x, y) { return document.elementFromPoint(x, y) };\n // Return false if it's not in the viewport\n if (rect.right < prect.left || rect.bottom < prect.top || rect.left > prect.right || rect.top > prect.bottom) {\n return false;\n }\n var flag = false;\n // Return true if left to right any border pixel reached\n for (var x = rect.left; x < rect.right; x++) {\n if (element.contains(efp(rect.top, x)) || element.contains(efp(rect.bottom, x))) {\n flag = true;\n break;\n }\n }\n // Return true if top to bottom any border pixel reached\n if (flag == false) {\n for (var y = rect.top; y < rect.bottom; y++) {\n if (element.contains(efp(rect.left, y)) || element.contains(efp(rect.right, y))) {\n flag = true;\n break;\n }\n }\n }\n if(csa) {\n // Another algorithm to check if element is centered and bigger than viewport\n if (flag == false) {\n var x = rect.left;\n var y = rect.top;\n // From top left to bottom right\n while(x < rect.right || y < rect.bottom) {\n if (element.contains(efp(x,y))) {\n flag = true;\n break;\n }\n if(x < rect.right) { x++; }\n if(y < rect.bottom) { y++; }\n }\n if (flag == false) {\n x = rect.right;\n y = rect.top;\n // From top right to bottom left\n while(x > rect.left || y < rect.bottom) {\n if (element.contains(efp(x,y))) {\n flag = true;\n break;\n }\n if(x > rect.left) { x--; }\n if(y < rect.bottom) { y++; }\n }\n }\n }\n }\n return flag;\n}\n\n// Check multiple elements visibility\ndocument.getElementById('container').addEventListener(\"scroll\", function() {\n var elementList = document.getElementsByClassName(\"element\");\n var console = document.getElementById('console');\n for (var i=0; i < elementList.length; i++) {\n // I did not define parent so it will be element's parent\n // and it will do crossSearchAlgorithm\n if (isVisible(elementList[i],null,true)) {\n console.innerHTML = \"Element with id[\" + elementList[i].id + \"] is visible!\";\n break;\n } else {\n console.innerHTML = \"Element with id[\" + elementList[i].id + \"] is hidden!\";\n }\n }\n});\n// Dynamically added elements\nfor(var i=4; i <= 6; i++) {\n var newElement = document.createElement(\"div\");\n newElement.id = \"element\" + i;\n newElement.classList.add(\"element\");\n document.getElementById('container').appendChild(newElement);\n} #console { background-color: yellow; }\n#container {\n width: 300px;\n height: 100px;\n background-color: lightblue;\n overflow-y: auto;\n padding-top: 150px;\n margin: 45px;\n}\n.element {\n margin: 400px;\n width: 400px;\n height: 320px;\n background-color: green;\n}\n#element3 {\n position: relative;\n margin: 40px;\n width: 720px;\n height: 520px;\n background-color: green;\n}\n#element3::before {\n content: \"\";\n position: absolute;\n top: -10px;\n left: -10px;\n margin: 0px;\n width: 740px;\n height: 540px;\n border: 5px dotted green;\n background: transparent;\n} <div id=\"console\"></div>\n<div id=\"container\">\n <div id=\"element1\" class=\"element\"></div>\n <div id=\"element2\" class=\"element\"></div>\n <div id=\"element3\" class=\"element\"></div>\n</div>" }, { "answer_id": 58899168, "author": "Dakusan", "author_id": 698632, "author_profile": "https://Stackoverflow.com/users/698632", "pm_score": 3, "selected": false, "text": "var Rect = YOUR_ELEMENT.getBoundingClientRect();\nvar ElTop = Rect.top, ElBottom = Rect.bottom;\nvar WindowHeight = $(window).height();\nif(window.visualViewport) {\n ElTop -= window.visualViewport.offsetTop;\n ElBottom -= window.visualViewport.offsetTop;\n WindowHeight = window.visualViewport.height;\n}\nvar WithinScreen = (ElTop >= 0 && ElBottom <= WindowHeight);\n" }, { "answer_id": 60647142, "author": "Chris Pratt", "author_id": 654031, "author_profile": "https://Stackoverflow.com/users/654031", "pm_score": 1, "selected": false, "text": "IntersectionObserver const bounding = el.getBoundingClientRect();\nconst isVisible = (0 < bounding.top && bounding.top < (window.innerHeight || document.documentElement.clientHeight)) ||\n (0 < bounding.bottom && bounding.bottom < (window.innerHeight || document.documentElement.clientHeight));\n" }, { "answer_id": 67124330, "author": "cryss", "author_id": 1271313, "author_profile": "https://Stackoverflow.com/users/1271313", "pm_score": 0, "selected": false, "text": "export const visibleInParentViewport = (el) => {\n const elementRect = el.getBoundingClientRect();\n const parentRect = el.parentNode.getBoundingClientRect();\n\n return (\n elementRect.top >= parentRect.top &&\n elementRect.right >= parentRect.left &&\n elementRect.top + elementRect.height <= parentRect.bottom &&\n elementRect.left + elementRect.width <= parentRect.right\n );\n}\n" }, { "answer_id": 68262400, "author": "Ismail Farooq", "author_id": 2724173, "author_profile": "https://Stackoverflow.com/users/2724173", "pm_score": 6, "selected": false, "text": "const el = document.querySelector('#el')\nconst observer = new window.IntersectionObserver(([entry]) => {\n if (entry.isIntersecting) {\n console.log('ENTER')\n return\n }\n console.log('LEAVE')\n}, {\n root: null,\n threshold: 0.1, // set offset 0.1 means trigger if atleast 10% of element in viewport\n})\n\nobserver.observe(el); body {\n height: 300vh;\n}\n\n#el {\n margin-top: 100vh;\n} <div id=\"el\">this is element</div>" }, { "answer_id": 69430599, "author": "dirck", "author_id": 11134583, "author_profile": "https://Stackoverflow.com/users/11134583", "pm_score": -1, "selected": false, "text": "getBoundingClientRect fudgeY function intersectRect(r1, r2) {\n var r = {};\n r.left = r1.left < r2.left ? r2.left : r1.left;\n r.top = r1.top < r2.top ? r2.top : r1.top;\n r.right = r1.right < r2.right ? r1.right : r2.right;\n r.bottom = r1.bottom < r2.bottom ? r1.bottom : r2.bottom;\n if (r.left < r.right && r.top < r.bottom)\n return r;\n return null;\n}\n\nfunction innerRect(e) {\n var b,r;\n b = e.getBoundingClientRect();\n r = {};\n r.left = b.left;\n r.top = b.top;\n r.right = b.left + e.clientWidth;\n r.bottom = b.top + e.clientHeight;\n return r;\n}\n\nfunction isViewable(e, fracX, fracY, fudgeY) {\n // ref https://stackoverflow.com/a/37998526\n // intersect all the rects and then check the result once\n // innerRect: mind the scroll bars\n // fudgeY: handle \"sticky\" thead in parent table. Ugh.\n var r, pr, er;\n\n er = e.getBoundingClientRect();\n r = er;\n for (;;) {\n e = e.parentElement;\n if (!e)\n break;\n pr = innerRect(e);\n if (fudgeY)\n pr.top += fudgeY;\n r = intersectRect(r, pr);\n if (!r)\n return false;\n }\n\n if (fracX && ((r.right-r.left) / (er.right-er.left)) < (fracX-0.001))\n return false;\n if (fracY && ((r.bottom-r.top) / (er.bottom-er.top)) < (fracY-0.001))\n return false;\n return true;\n}\n" }, { "answer_id": 70476497, "author": "Arthur Shlain", "author_id": 2453148, "author_profile": "https://Stackoverflow.com/users/2453148", "pm_score": 2, "selected": false, "text": "/**\n * Returns Element placement information in Viewport\n * @link https://stackoverflow.com/a/70476497/2453148\n *\n * @typedef {object} ViewportInfo - Whether the element is…\n * @property {boolean} isInViewport - fully or partially in the viewport\n * @property {boolean} isPartiallyInViewport - partially in the viewport\n * @property {boolean} isInsideViewport - fully inside viewport\n * @property {boolean} isAroundViewport - completely covers the viewport\n * @property {boolean} isOnEdge - intersects the edge of viewport\n * @property {boolean} isOnTopEdge - intersects the top edge\n * @property {boolean} isOnRightEdge - intersects the right edge\n * @property {boolean} isOnBottomEdge - is intersects the bottom edge\n * @property {boolean} isOnLeftEdge - is intersects the left edge\n *\n * @param el Element\n * @return {Object} ViewportInfo\n */\nfunction getElementViewportInfo(el) {\n\n let result = {};\n\n let rect = el.getBoundingClientRect();\n let windowHeight = window.innerHeight || document.documentElement.clientHeight;\n let windowWidth = window.innerWidth || document.documentElement.clientWidth;\n\n let insideX = rect.left >= 0 && rect.left + rect.width <= windowWidth;\n let insideY = rect.top >= 0 && rect.top + rect.height <= windowHeight;\n\n result.isInsideViewport = insideX && insideY;\n\n let aroundX = rect.left < 0 && rect.left + rect.width > windowWidth;\n let aroundY = rect.top < 0 && rect.top + rect.height > windowHeight;\n\n result.isAroundViewport = aroundX && aroundY;\n\n let onTop = rect.top < 0 && rect.top + rect.height > 0;\n let onRight = rect.left < windowWidth && rect.left + rect.width > windowWidth;\n let onLeft = rect.left < 0 && rect.left + rect.width > 0;\n let onBottom = rect.top < windowHeight && rect.top + rect.height > windowHeight;\n\n let onY = insideY || aroundY || onTop || onBottom;\n let onX = insideX || aroundX || onLeft || onRight;\n\n result.isOnTopEdge = onTop && onX;\n result.isOnRightEdge = onRight && onY;\n result.isOnBottomEdge = onBottom && onX;\n result.isOnLeftEdge = onLeft && onY;\n\n result.isOnEdge = result.isOnLeftEdge || result.isOnRightEdge ||\n result.isOnTopEdge || result.isOnBottomEdge;\n\n let isInX =\n insideX || aroundX || result.isOnLeftEdge || result.isOnRightEdge;\n let isInY =\n insideY || aroundY || result.isOnTopEdge || result.isOnBottomEdge;\n\n result.isInViewport = isInX && isInY;\n\n result.isPartiallyInViewport =\n result.isInViewport && result.isOnEdge;\n\n return result;\n}\n" }, { "answer_id": 74051199, "author": "Ynod", "author_id": 15410792, "author_profile": "https://Stackoverflow.com/users/15410792", "pm_score": 0, "selected": false, "text": " const isHTMLElementInView = (element: HTMLElement) => {\n const rect = element?.getBoundingClientRect()\n\n if (!rect) return\n return rect.top <= window.innerHeight && rect.bottom >= 0\n }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21290/" ]
124,005
<p>I have an SSIS package that copies the data in a table from one SQL Server 2005 to another SQL Server 2005. I do this with a "Data Flow" task. In the package config file I expose the destination table name.</p> <p>Problem is when I change the destination table name in the config file (via notepad) I get the following error "vs_needsnewmetadata". I think I understand the problem... the destination table column mapping is fixed when I first set up the package.</p> <p>Question: what's the easiest way to do the above with an ssis package? </p> <p>I've read online about setting up the metadata programmatically and all but I'd like to avoid this. Also I wrote a C# console app that does everything just fine... all tables etc are specified in the app.config ... but apparently this solution isn't good enough.</p>
[ { "answer_id": 124461, "author": "ctrlShiftBryan", "author_id": 6161, "author_profile": "https://Stackoverflow.com/users/6161", "pm_score": 0, "selected": false, "text": "INSERT INTO server1.dbo.database1.table1(id,name)\nSELECT id, name FROM server2.dbo.database1.table1\n" }, { "answer_id": 13857057, "author": "Abhishek Jain", "author_id": 1900500, "author_profile": "https://Stackoverflow.com/users/1900500", "pm_score": 2, "selected": false, "text": "SrNo_prod SrNo_Prod P p" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
124,031
<p>Using MS SQL Server Management Studio 2005 - To Restore a Database:</p> <ul> <li>Restore Database</li> <li><code>(*) From Device:</code></li> <li>Click "<code>...</code>" Button</li> <li><code>Backup media: File</code> </li> <li>Click "<code>Add</code>" Button</li> <li>Popup Window: "<code>Locate Backup File</code>"</li> </ul> <p>That window Defaults to <code>C:\Program Files\Microsoft SQL Server\MSSQL.1\Backup</code></p> <p>How do I configure MS SQL Server Management Studio to look in <code>D:\data\databases\</code><br> instead of looking in <code>C:\Program Files\Microsoft SQL Server\MSSQL.1\Backup</code> ?</p>
[ { "answer_id": 124106, "author": "henriksen", "author_id": 6181, "author_profile": "https://Stackoverflow.com/users/6181", "pm_score": 5, "selected": true, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\MSSQL.1\\MSSQLServer\\BackupDirectory d:\\data\\databases" }, { "answer_id": 164267, "author": "jeremcc", "author_id": 1436, "author_profile": "https://Stackoverflow.com/users/1436", "pm_score": 2, "selected": false, "text": "Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\MSSQL.1\\MSSQLServer]\n\"BackupDirectory\"=\"D:\\\\data\\\\databases\\\\\"\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12923/" ]
124,035
<p>I recently converted a ruby library to a gem, which seemed to break the command line usability</p> <p>Worked fine as a library</p> <pre><code> $ ruby -r foobar -e 'p FooBar.question' # =&gt; "answer" </code></pre> <p>And as a gem, irb knows how to require a gem from command-line switches</p> <pre><code> $ irb -rubygems -r foobar irb(main):001:0&gt; FooBar.question # =&gt; "answer" </code></pre> <p>But the same fails for ruby itself:</p> <pre><code> $ ruby -rubygems -r foobar -e 'p FooBar.question' ruby: no such file to load -- foobar (LoadError) </code></pre> <p>must I now do this, which seems ugly: </p> <pre><code> ruby -rubygems -e 'require "foobar"; p FooBar.question' # =&gt; "answer" </code></pre> <p>Or is there a way to make the 2 switches work?</p> <p><em>Note</em>: I know the gem could add a bin/program for every useful method but I don't like to pollute the command line namespace unnecessarily</p>
[ { "answer_id": 124069, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 4, "selected": true, "text": "ruby -rubygems -r /usr/lib/ruby/gems/myhelpfulclass-0.0.1/lib/MyHelpfulClass -e \"puts MyHelpfulClass\"\n export RUBYLIB=/usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib\nruby -rubygems -r MyHelpfulClass -e \"puts MyHelpfulClass\"\n ruby -I /usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib \\\n -rubygems -r MyHelpfulClass -e \"puts MyHelpfulClass\"\n" }, { "answer_id": 14163894, "author": "Kelvin", "author_id": 498594, "author_profile": "https://Stackoverflow.com/users/498594", "pm_score": 0, "selected": false, "text": "-r $LOAD_PATH $LOAD_PATH irb irb $LOAD_PATH ruby -rubygems -e 'require \"foobar\"; p FooBar.question'\n ruby -rubygems -e '%w(rake rspec).each{|r| require r }'\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4615/" ]
124,066
<p>I've found a similar question on stack overflow, but it didn't really answer the question I have. I need to make sure that my asp.net application is formatting the date dd/mm/yyyy the same as my SQL Server 2005.</p> <p>How do I verify the date culture (if that's what it's called) of the server matches how I've programmed my app? Are there specific database settings and OS settings? Is it table-specific? I don't want to transpose my days and months.</p> <p>thank you</p>
[ { "answer_id": 124208, "author": "Jorge Alves", "author_id": 6195, "author_profile": "https://Stackoverflow.com/users/6195", "pm_score": 0, "selected": false, "text": "string sqlCmd = @\"SELECT *\n FROM MyTable\n WHERE MyDateField = CONVERT(datetime, '{0}', 101)\";\n\n// assuming myDateString is a string with a date in the local format\nsqlCmd = string.Format(sqlCmd,\n Convert.ToDateTime(myDateString).ToString(\"yyyyMMdd\"));\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5433/" ]
124,067
<p>In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# <code>System.Text.StringBuilder</code> and Java <code>java.lang.StringBuilder</code>.</p> <p>Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available?</p>
[ { "answer_id": 124084, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": -1, "selected": false, "text": "$a=\"hello \";\n$b=\"world\";\necho $a.$b;\n" }, { "answer_id": 124109, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 7, "selected": true, "text": "// This...\necho 'one', 'two';\n\n// Is the same as this\necho 'one';\necho 'two';\n // This...\necho 'one', 'two';\n\n// Is faster than this...\necho 'one' . 'two';\n $values = array( 'one', 'two', 'three' );\n$valueList = implode( ', ', $values );\n" }, { "answer_id": 124116, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "$string = 'abc';\n$string[2] = 'a'; // $string equals 'aba'\n$string[3] = 'd'; // $string equals 'abad'\n$string[5] = 'e'; // $string equals 'abad e' (fills character(s) in between with spaces)\n $string .= 'a';\n" }, { "answer_id": 124213, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 1, "selected": false, "text": "echo $a,$b,$c;\n echo $a . $b . $c;\n StringBuilder" }, { "answer_id": 124279, "author": "cori", "author_id": 8151, "author_profile": "https://Stackoverflow.com/users/8151", "pm_score": 0, "selected": false, "text": "$aString = 'oranges';\n$compareString = \"comparing apples to {$aString}!\";\necho $compareString\n comparing apples to oranges!\n echo \"You requested page id {$_POST['id']}\";\n" }, { "answer_id": 3498919, "author": "ossys", "author_id": 382560, "author_profile": "https://Stackoverflow.com/users/382560", "pm_score": 3, "selected": false, "text": "class StringBuilder {\n\n private $str = array();\n\n public function __construct() { }\n\n public function append($str) {\n $this->str[] = $str;\n }\n\n public function toString() {\n return implode($this->str);\n }\n\n}\n" }, { "answer_id": 16112845, "author": "nightcoder", "author_id": 94990, "author_profile": "https://Stackoverflow.com/users/94990", "pm_score": 4, "selected": false, "text": "$iterations = 10000;\n$stringToAppend = 'TESTSTR';\n$timer = new Timer(); // based on microtime()\n$s = '';\nfor($i = 0; $i < $iterations; $i++)\n{\n $s .= ($i . $stringToAppend);\n}\n$timer->VarDumpCurrentTimerValue();\n\n$timer->Restart();\n\n// Used purlogic's implementation.\n// I tried other implementations, but they are not faster\n$sb = new StringBuilder(); \n\nfor($i = 0; $i < $iterations; $i++)\n{\n $sb->append($i);\n $sb->append($stringToAppend);\n}\n$ss = $sb->toString();\n$timer->VarDumpCurrentTimerValue();\n const int iterations = 10000;\nconst string stringToAppend = \"TESTSTR\";\nstring s = \"\";\nvar timer = new Timer(); // based on StopWatch\n\nfor(int i = 0; i < iterations; i++)\n{\n s += (i + stringToAppend);\n}\n\ntimer.ShowCurrentTimerValue();\n\ntimer.Restart();\n\nvar sb = new StringBuilder();\n\nfor(int i = 0; i < iterations; i++)\n{\n sb.Append(i);\n sb.Append(stringToAppend);\n}\n\nstring ss = sb.ToString();\n\ntimer.ShowCurrentTimerValue();\n" }, { "answer_id": 16366498, "author": "Evilnode", "author_id": 236142, "author_profile": "https://Stackoverflow.com/users/236142", "pm_score": 5, "selected": false, "text": "<?php\nini_set('memory_limit', '1024M');\ndefine ('CORE_PATH', '/Users/foo');\ndefine ('DS', DIRECTORY_SEPARATOR);\n\n$numtests = 1000000;\n\nfunction test1($numtests)\n{\n $CORE_PATH = '/Users/foo';\n $DS = DIRECTORY_SEPARATOR;\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i < $numtests; $i++) {\n $a[] = sprintf('%s%sDesktop%sjunk.php', $CORE_PATH, $DS, $DS);\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 1: sprintf()\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\nfunction test2($numtests)\n{\n $CORE_PATH = '/Users/shigh';\n $DS = DIRECTORY_SEPARATOR;\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i < $numtests; $i++) {\n $a[] = $CORE_PATH . $DS . 'Desktop' . $DS . 'junk.php';\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 2: Concatenation\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\nfunction test3($numtests)\n{\n $CORE_PATH = '/Users/shigh';\n $DS = DIRECTORY_SEPARATOR;\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i < $numtests; $i++) {\n ob_start();\n echo $CORE_PATH,$DS,'Desktop',$DS,'junk.php';\n $aa = ob_get_contents();\n ob_end_clean();\n $a[] = $aa;\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 3: Buffering Method\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\nfunction test4($numtests)\n{\n $CORE_PATH = '/Users/shigh';\n $DS = DIRECTORY_SEPARATOR;\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i < $numtests; $i++) {\n $a[] = \"{$CORE_PATH}{$DS}Desktop{$DS}junk.php\";\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 4: Braced in-line variables\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\nfunction test5($numtests)\n{\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i < $numtests; $i++) {\n $CORE_PATH = CORE_PATH;\n $DS = DIRECTORY_SEPARATOR;\n $a[] = \"{$CORE_PATH}{$DS}Desktop{$DS}junk.php\";\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 5: Braced inline variables with loop-level assignments\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\ntest1($numtests);\ntest2($numtests);\ntest3($numtests);\ntest4($numtests);\ntest5($numtests);\n" }, { "answer_id": 39722317, "author": "Dakusan", "author_id": 698632, "author_profile": "https://Stackoverflow.com/users/698632", "pm_score": 2, "selected": false, "text": "$OneMB=str_repeat('x', 1024*1024);\n$Final=$OneMB.$OneMB.$OneMB.$OneMB.$OneMB;\nprint memory_get_peak_usage();\n $OneMB=str_repeat('x', 1024*1024);\n$Final=implode('', Array($OneMB, $OneMB, $OneMB, $OneMB, $OneMB));\nprint memory_get_peak_usage();\n <?\n//Please note, for the recursion test to go beyond 256, xdebug.max_nesting_level needs to be raised. You also may need to update your memory_limit depending on the number of iterations\n\n//Output the start memory\nprint 'Start: '.memory_get_usage().\"B<br><br>Below test results are in MB<br>\";\n\n//Our 1MB string\nglobal $OneMB, $NumIterations;\n$OneMB=str_repeat('x', 1024*1024);\n$NumIterations=500;\n\n//Run the tests\n$ConcatTest=RunTest('ConcatTest');\n$ImplodeTest=RunTest('ImplodeTest');\n$RecurseTest=RunTest('RecurseTest');\n\n//Output the results in a table\nOutputResults(\n Array('ConcatTest', 'ImplodeTest', 'RecurseTest'),\n Array($ConcatTest, $ImplodeTest, $RecurseTest)\n);\n\n//Start a test run by initializing the array that will hold the results and manipulating those results after the test is complete\nfunction RunTest($TestName)\n{\n $CurrentTestNums=Array();\n $TestStartMem=memory_get_usage();\n $StartTime=microtime(true);\n RunTestReal($TestName, $CurrentTestNums, $StrLen);\n $CurrentTestNums[]=memory_get_usage();\n\n //Subtract $TestStartMem from all other numbers\n foreach($CurrentTestNums as &$Num)\n $Num-=$TestStartMem;\n unset($Num);\n\n $CurrentTestNums[]=$StrLen;\n $CurrentTestNums[]=microtime(true)-$StartTime;\n\n return $CurrentTestNums;\n}\n\n//Initialize the test and store the memory allocated at the end of the test, with the result\nfunction RunTestReal($TestName, &$CurrentTestNums, &$StrLen)\n{\n $R=$TestName($CurrentTestNums);\n $CurrentTestNums[]=memory_get_usage();\n $StrLen=strlen($R);\n}\n\n//Concatenate 1MB string over and over onto a single string\nfunction ConcatTest(&$CurrentTestNums)\n{\n global $OneMB, $NumIterations;\n $Result='';\n for($i=0;$i<$NumIterations;$i++)\n {\n $Result.=$OneMB;\n $CurrentTestNums[]=memory_get_usage();\n }\n return $Result;\n}\n\n//Create an array of 1MB strings and then join w/ an implode\nfunction ImplodeTest(&$CurrentTestNums)\n{\n global $OneMB, $NumIterations;\n $Result=Array();\n for($i=0;$i<$NumIterations;$i++)\n {\n $Result[]=$OneMB;\n $CurrentTestNums[]=memory_get_usage();\n }\n return implode('', $Result);\n}\n\n//Recursively add strings onto each other\nfunction RecurseTest(&$CurrentTestNums, $TestNum=0)\n{\n Global $OneMB, $NumIterations;\n if($TestNum==$NumIterations)\n return '';\n\n $NewStr=RecurseTest($CurrentTestNums, $TestNum+1).$OneMB;\n $CurrentTestNums[]=memory_get_usage();\n return $NewStr;\n}\n\n//Output the results in a table\nfunction OutputResults($TestNames, $TestResults)\n{\n global $NumIterations;\n print '<table border=1 cellspacing=0 cellpadding=2><tr><th>Test Name</th><th>'.implode('</th><th>', $TestNames).'</th></tr>';\n $FinalNames=Array('Final Result', 'Clean');\n for($i=0;$i<$NumIterations+2;$i++)\n {\n $TestName=($i<$NumIterations ? $i : $FinalNames[$i-$NumIterations]);\n print \"<tr><th>$TestName</th>\";\n foreach($TestResults as $TR)\n printf('<td>%07.4f</td>', $TR[$i]/1024/1024);\n print '</tr>';\n }\n\n //Other result numbers\n print '<tr><th>Final String Size</th>';\n foreach($TestResults as $TR)\n printf('<td>%d</td>', $TR[$NumIterations+2]);\n print '</tr><tr><th>Runtime</th>';\n foreach($TestResults as $TR)\n printf('<td>%s</td>', $TR[$NumIterations+3]);\n print '</tr></table>';\n}\n?>\n" }, { "answer_id": 64179127, "author": "mdempfle", "author_id": 14138908, "author_profile": "https://Stackoverflow.com/users/14138908", "pm_score": 2, "selected": false, "text": "$currentTime = microtime(true);\n$str = '';\nfor ($i = 50000; $i > 0; $i--) {\n $str .= 'String concatenation. ';\n}\n$currentTime2 = microtime(true);\necho \"String 1: \" . ( $currentTime2 - $currentTime);\n\n$str = '';\nfor ($i = 50000; $i > 0; $i--) {\n $str = $str . 'String concatenation. ';\n}\n$currentTime3 = microtime(true);\necho \"<br>String 2: \" . ($currentTime3 - $currentTime2);\n\necho \"<br><br>Faktor: \" . (($currentTime3 - $currentTime2) / ( $currentTime2 - $currentTime));\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21388/" ]
124,076
<p>When I use traceroute, I often see abbreviations in the hostnames along the route, such as "ge", "so", "ic", "gw", "bb" etc. I can guess "bb" means backbone.</p> <p>Does anyone know what any these strings abbreviate, or know any other common abbreviations?</p>
[ { "answer_id": 23001209, "author": "Tech", "author_id": 3521618, "author_profile": "https://Stackoverflow.com/users/3521618", "pm_score": 0, "selected": false, "text": "so = sonet, pos = packet over sonet\nxe= ten gigabit\nge= gigabit" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19214/" ]
124,079
<p>I'd like to slice and dice large datafiles, up to a gig, in a fairly quick and efficient manner. If I use something like UNIX's "CUT", it's extremely fast, even in a CYGWIN environment. </p> <p>I've tried developing and benchmarking various Ruby scripts to process these files, and always end up with glacial results. </p> <p>What would you do in Ruby to make this not so dog slow?</p>
[ { "answer_id": 124088, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "counts = {}\ncounts.default = 0\n\nARGF.each_line do |line|\n if line =~ %r{GET /ongoing/When/\\d\\d\\dx/(\\d\\d\\d\\d/\\d\\d/\\d\\d/[^ .]+) }\n counts[$1] += 1\n end\nend\n\nkeys_by_count = counts.keys.sort { |a, b| counts[b] <=> counts[a] }\nkeys_by_count[0 .. 9].each do |key|\n puts \"#{counts[key]}: #{key}\"\nend\n" }, { "answer_id": 124282, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": 2, "selected": true, "text": "puts `cut somefile > foo.fil`\n# process each line of the output from cut\nf = File.new(\"foo.fil\")\nf.each{|line|\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21275/" ]
124,096
<p>I tend to implement UI functionality using fairly self-documenting void doSomething() methods, i.e. if the user presses this button then perform this action then enable this list box, disable that button, etc. Is this the best approach? Is there a better pattern for general UI management i.e. how to control when controls are enabled/disabled/etc. etc. depending on user input?</p> <p>Often I feel like I'm veering towards the 'big class that does everything' anti-pattern as so much seems to interact with the 'main' form class. Often, even if I'm including private state variables in the class that have been implemented using a relatively modular design, I'm still finding it grows so quickly it's ridiculous.</p> <p>So could people give me some good advice towards producing quality, testable, decoupled WinForms design without falling into these traps?</p>
[ { "answer_id": 124119, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "class Form1 : Form\n { \n void Button1_Click\n { \n Program.DoCommand1();\n }\n }\n\n\nstatic class Program\n{\n internal static void DoCommand1() {/* ... */}\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ]
124,108
<p>I am trying to mock-up an API and am using separate apps within Django to represent different web services. I would like App A to take in a link that corresponds to App B and parse the <code>json</code> response. </p> <p>Is there a way to dynamically construct the url to App B so that I can test the code in development and not change to much before going into production? The problem is that I can't use localhost as part of a link. </p> <p>I am currently using urllib, but eventually I would like to do something less hacky and better fitting with the web services <code>REST</code> paradigm.</p>
[ { "answer_id": 124119, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "class Form1 : Form\n { \n void Button1_Click\n { \n Program.DoCommand1();\n }\n }\n\n\nstatic class Program\n{\n internal static void DoCommand1() {/* ... */}\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
124,118
<p>We want to switch a web server from Windows 2003 to Windows 2003 Enterprise (64 bits) to use 8GB of RAM. Will IIS 6.0 and an ASPNET 1.1 application be able to benefit from the change?</p>
[ { "answer_id": 139790, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 3, "selected": true, "text": "cscript %SystemDrive%\\inetpub\\AdminScripts\\adsutil.vbs set w3svc/AppPools/Enable32bitAppOnWin64 1\n <system.web> \n <processModel memoryLimit=\"80\" />\n</system.web> \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
124,123
<p>Imagine I have the folling XML file:</p> <p>&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;</p> <p>I want to convert it into something like this:</p> <p>&lt;a&gt;beforemiddleafter&lt;/a&gt;</p> <p>In other words I want to get all the child nodes of a certain node, and move them to the parent node in order. This is like doing this command: "mv ./directory/* .", but for xml nodes.</p> <p>I'd like to do this in using unix command line tools. I've been trying with xmlstarlet, which is a powerful command line XML manipulator. I tried doing something like this, but it doesn't work</p> <p>echo "&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;" | xmlstarlet ed -m "//b/*" ".."</p> <p>Update: XSLT templates are fine, since they can be called from the command line.</p> <p>My goal here is 'remove the links from an XHTML page', in other words replace where the link was, with the contents of the link tag.</p>
[ { "answer_id": 124215, "author": "Rahul", "author_id": 16308, "author_profile": "https://Stackoverflow.com/users/16308", "pm_score": 2, "selected": false, "text": "<xsl:template match=\"a\"><a><xsl:apply-templates /></a></xsl:template>\n\n<xsl:template match=\"a/b\"><xsl:value-of select=\".\"/></xsl:template>\n <a>beforemiddleafter</a>\n" }, { "answer_id": 125545, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<test>\n<x>before<y>middle</y>after</x>\n<a>before<b>middle</b>after</a>\n<a>before<b>middle</b>after</a>\n<x>before<y>middle</y>after</x>\n<a>before<b>middle</b>after</a>\n<embedded>foo<a>before<b>middle</b>after</a>bar</embedded>\n</test>\n <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n </xsl:template>\n\n <xsl:template match=\"a\">\n <xsl:copy>\n <xsl:value-of select=\".\"/>\n </xsl:copy>\n </xsl:template>\n\n </xsl:stylesheet>\n xml tr collapse.xsl test.xml\n <?xml version=\"1.0\"?>\n<test>\n<x>before<y>middle</y>after</x>\n<a>beforemiddleafter</a>\n<a>beforemiddleafter</a>\n<x>before<y>middle</y>after</x>\n<a>beforemiddleafter</a>\n<embedded>foo<a>beforemiddleafter</a>bar</embedded>\n</test>\n" }, { "answer_id": 127249, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 0, "selected": false, "text": "file.xml <r>\n <a>start<b>middle</b>end</a>\n</r>\n template.xsl <xsl:template match=\"/\">\n <a><xsl:value-of select=\"r/a\" /></a>\n</xsl:template>\n output <a>startmiddleend</a>\n" }, { "answer_id": 132169, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 3, "selected": true, "text": "<a> <xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:h=\"http://www.w3.org/1999/xhtml\"\n exclude-result-prefixes=\"h\">\n\n<!-- Don't copy the <a> elements, just process their content -->\n<xsl:template match=\"h:a\">\n <xsl:apply-templates />\n</xsl:template>\n\n<!-- identity template; copies everything by default -->\n<xsl:template match=\"node()|@*\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\" />\n </xsl:copy>\n</xsl:template>\n\n</xsl:stylesheet>\n <a> <p>Here is <a href=\"....\">some <em>linked</em> text</a>.</p>\n <p>Here is some <em>linked</em> text.</p>\n <p> <a> <p>Here is <em>some <a href=\"...\">linked</a> text</em>.</p>\n" }, { "answer_id": 3174101, "author": "lmxy", "author_id": 382998, "author_profile": "https://Stackoverflow.com/users/382998", "pm_score": 1, "selected": false, "text": "xmlstr='<a>before<b>middle</b>after</a>'\nupdatestr=\"$(echo \"$xmlstr\" | xmlstarlet sel -T -t -m \"/a/b\" -v '../.' -n | sed -n '1{p;q;}')\"\necho \"$xmlstr\" | xmlstarlet ed -u \"/a\" -v \"$updatestr\"\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161922/" ]
124,143
<p>I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions.<br/> <strong>What is the main reason of the difference between Java and C# in throwing exceptions?</strong><br/> In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.</p>
[ { "answer_id": 124173, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 4, "selected": false, "text": "using" }, { "answer_id": 124175, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 6, "selected": true, "text": "try {\n // exception throwing code\n} catch(Exception e) {\n // either\n log.error(\"Error fooing bar\",e);\n // OR\n throw new RuntimeException(e);\n}\n" }, { "answer_id": 126122, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 7, "selected": false, "text": "using <exception>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68336/" ]
124,148
<p>Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue:</p> <pre><code>int i = 4; ... if (i == 10) doStuff(); </code></pre> <p>Later on you figure that you want the variable <em>i</em> to be either defined or undefined, so you change the above instantiation to:</p> <pre><code>Integer i = null; </code></pre> <p>Now the equality check fails.</p> <p>Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?</p>
[ { "answer_id": 124196, "author": "Michael Deardeuff", "author_id": 4931, "author_profile": "https://Stackoverflow.com/users/4931", "pm_score": 5, "selected": true, "text": "(i == 10) i.equals(TEN) i.equals(j) null null null" }, { "answer_id": 124202, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "if( i == 10 )\n if( i == 128 )\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
124,166
<p>What is the best way to make a <code>&lt;div&gt;</code> fade away after a given amount of time (without using some of the JavaScript libraries available).</p> <p>I'm looking for a very lightweight solution not requiring a huge JavaScript library to be sent to the browser.</p>
[ { "answer_id": 124294, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 2, "selected": false, "text": "var TimeToFade = 200.0;\n\nfunction fade(eid)\n{\n var element = document.getElementById(eid);\n if(element == null) return;\n\n if(element.FadeState == null)\n {\n if(element.style.opacity == null || element.style.opacity == ''\n || element.style.opacity == '1') {\n element.FadeState = 2;\n } else {\n element.FadeState = -2;\n }\n }\n\n if(element.FadeState == 1 || element.FadeState == -1) {\n element.FadeState = element.FadeState == 1 ? -1 : 1;\n element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;\n } else {\n element.FadeState = element.FadeState == 2 ? -1 : 1;\n element.FadeTimeLeft = TimeToFade;\n setTimeout(\"animateFade(\" + new Date().getTime()\n + \",'\" + eid + \"')\", 33);\n }\n}\n\nfunction animateFade(lastTick, eid)\n{\n var curTick = new Date().getTime();\n var elapsedTicks = curTick - lastTick;\n\n var element = document.getElementById(eid);\n\n if(element.FadeTimeLeft <= elapsedTicks) {\n element.style.opacity = element.FadeState == 1 ? '1' : '0';\n element.style.filter = 'alpha(opacity = '\n + (element.FadeState == 1 ? '100' : '0') + ')';\n element.FadeState = element.FadeState == 1 ? 2 : -2;\n element.style.display = \"none\";\n return;\n }\n\n element.FadeTimeLeft -= elapsedTicks;\n var newOpVal = element.FadeTimeLeft/TimeToFade;\n if(element.FadeState == 1) {\n newOpVal = 1 - newOpVal;\n }\n\n element.style.opacity = newOpVal;\n element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';\n\n setTimeout(\"animateFade(\" + curTick + \",'\" + eid + \"')\", 33);\n}\n <html><head>\n <script type=\"text/javascript\" src=\"fade.js\"></script>\n</head><body>\n <div id=\"fademe\" onclick=\"fade( 'fademe' )\">\n <p>This will fade when you click it</p>\n </div>\n</body></html>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
124,167
<p>Please explain to me why the very last <code>echo</code> statement is blank? I expect that <code>XCODE</code> is incremented in the while loop to a value of 1:</p> <pre><code>#!/bin/bash OUTPUT="name1 ip ip status" # normally output of another command with multi line output if [ -z "$OUTPUT" ] then echo "Status WARN: No messages from SMcli" exit $STATE_WARNING else echo "$OUTPUT"|while read NAME IP1 IP2 STATUS do if [ "$STATUS" != "Optimal" ] then echo "CRIT: $NAME - $STATUS" echo $((++XCODE)) else echo "OK: $NAME - $STATUS" fi done fi echo $XCODE </code></pre> <p>I've tried using the following statement instead of the <code>++XCODE</code> method</p> <pre><code>XCODE=`expr $XCODE + 1` </code></pre> <p>and it too won't print outside of the while statement. I think I'm missing something about variable scope here, but the ol' man page isn't showing it to me.</p>
[ { "answer_id": 124211, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": " #!/bin/bash\n OUTPUT=\"name1 ip ip status\"\n+export XCODE=0;\n if [ -z \"$OUTPUT\" ]\n----\n\n echo \"CRIT: $NAME - $STATUS\"\n- echo $((++XCODE))\n+ export XCODE=$(( $XCODE + 1 ))\n else\n\necho $XCODE\n" }, { "answer_id": 124321, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 8, "selected": true, "text": "echo" }, { "answer_id": 124349, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 7, "selected": false, "text": "while while ... do ... done <<< \"$OUTPUT\"\n while ... do ... done < <(echo \"$OUTPUT\")\n" }, { "answer_id": 5625161, "author": "freethinker", "author_id": 348749, "author_profile": "https://Stackoverflow.com/users/348749", "pm_score": 2, "selected": false, "text": "#!/bin/bash\nEXPORTFILE=/tmp/exportfile${RANDOM}\ncat /tmp/randomFile | while read line\ndo\n LINE=\"$LINE $line\"\n echo $LINE > $EXPORTFILE\ndone\nLINE=$(cat $EXPORTFILE)\n" }, { "answer_id": 26701823, "author": "Rammix", "author_id": 2161558, "author_profile": "https://Stackoverflow.com/users/2161558", "pm_score": 2, "selected": false, "text": "#!/bin/bash\ncat /some/file | while read line\ndo\n var=\"abc\"\n echo $var | xsel -i -p # redirect stdin to the X primary selection\ndone\nvar=$(xsel -o -p) # redirect back to stdout\necho $var\n xclip -i -selection clipboard xsel -i -p" }, { "answer_id": 27175062, "author": "sano", "author_id": 4300967, "author_profile": "https://Stackoverflow.com/users/4300967", "pm_score": 4, "selected": false, "text": "#!/bin/bash\ncat /tmp/randomFile | (while read line\ndo\n LINE=\"$LINE $line\"\ndone && echo $LINE )\n" }, { "answer_id": 39124140, "author": "Adrian May", "author_id": 2910747, "author_profile": "https://Stackoverflow.com/users/2910747", "pm_score": 2, "selected": false, "text": "ls -l | sed '/total/d ; s/ */\\t/g' | cut -f 5 | \n( SUM=0; while read SIZE; do SUM=$(($SUM+$SIZE)); done; echo \"$(($SUM/1024/1024/1024))GB\" )\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14230/" ]
124,170
<p>I'm doing a sitemap producer in Object Pascal and need a good function or lib to emulate the <a href="http://php.net/manual/en/function.parse-url.php" rel="nofollow noreferrer">parse_url</a> function on PHP.</p> <p>Does anyone know of any good ones?</p>
[ { "answer_id": 124200, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": " ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n 12 3 4 5 6 7 8 9\n $1 = http:\n $2 = http\n $3 = //www.ics.uci.edu\n $4 = www.ics.uci.edu\n $5 = /pub/ietf/uri/\n $6 = <undefined>\n $7 = <undefined>\n $8 = #Related\n $9 = Related\n http://www.ics.uci.edu/pub/ietf/uri/#Related\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
124,171
<p>I'd be very grateful if you could compare the winning <a href="http://www.cs.ucsd.edu/~sorourke/wf.pl" rel="nofollow noreferrer">O’Rourke's Perl solution</a> to <a href="http://effbot.org/zone/wide-finder.htm" rel="nofollow noreferrer">Lundh's Python solution</a>, as I don't know Perl good enough to understand what's going on there. More specifically I'd like to know what gave Perl version 3x advantage: algorithmic superiority, quality of C extensions, other factors?</p> <p><a href="http://www.tbray.org/ongoing/When/200x/2007/10/30/WF-Results" rel="nofollow noreferrer">Wide Finder: Results</a></p>
[ { "answer_id": 13300315, "author": "Mario Roy", "author_id": 1810910, "author_profile": "https://Stackoverflow.com/users/1810910", "pm_score": 2, "selected": false, "text": "Script....: baseline1 baseline2 wf_mce1 wf_mce2 wf_mce3 wf_mmap\nCold cache: 1.674 1.370 1.252 1.182 1.174 3.056\nWarm cache: 1.236 0.923 0.277 0.106 0.098 0.092\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20310/" ]
124,205
<p>I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In <code>MySQL</code> I would use <code>SHOW TABLES LIKE "Datasheet%"</code>, but in <code>T-SQL</code> this throws an error (it tries to look for a <code>SHOW</code> stored procedure and fails).</p> <p>Is this possible, and if so, how?</p>
[ { "answer_id": 124216, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 3, "selected": false, "text": "select * from information_schema.columns\nwhere table_name = 'yourTableName'\n information_schema" }, { "answer_id": 124220, "author": "PJB", "author_id": 5664, "author_profile": "https://Stackoverflow.com/users/5664", "pm_score": 3, "selected": false, "text": "SELECT * FROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME LIKE 'Datasheet%'\n" }, { "answer_id": 124223, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 2, "selected": false, "text": "SELECT table_name\nFROM information_schema.tables\nWHERE\ntable_name LIKE 'Datasheet%'\n" }, { "answer_id": 124224, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 7, "selected": true, "text": "Select Table_name as \"Table name\"\nFrom Information_schema.Tables\nWhere Table_type = 'BASE TABLE' and Objectproperty \n(Object_id(Table_name), 'IsMsShipped') = 0\n" }, { "answer_id": 124259, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 6, "selected": false, "text": "sp_tables 'Database_Name'\n" }, { "answer_id": 124439, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 2, "selected": false, "text": "MS information_schema" }, { "answer_id": 274085, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "SELECT * FROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME LIKE '%'\n" }, { "answer_id": 18039716, "author": "ducnguyen.lotus", "author_id": 2649830, "author_profile": "https://Stackoverflow.com/users/2649830", "pm_score": 4, "selected": false, "text": "USE your_database\ngo\nSp_tables\ngo\n" }, { "answer_id": 35698340, "author": "Chris", "author_id": 3032385, "author_profile": "https://Stackoverflow.com/users/3032385", "pm_score": 1, "selected": false, "text": "sp_tables 'Database_Name" }, { "answer_id": 56313344, "author": "Ramshad Abdulraheem", "author_id": 11137003, "author_profile": "https://Stackoverflow.com/users/11137003", "pm_score": 3, "selected": false, "text": "SELECT * FROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA='dbo'; \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21402/" ]
124,210
<p>In order to help my team write testable code, I came up with this simple list of best practices for making our C# code base more testable. (Some of the points refer to limitations of Rhino Mocks, a mocking framework for C#, but the rules may apply more generally as well.) Does anyone have any best practices that they follow?</p> <p>To maximize the testability of code, follow these rules:</p> <ol> <li><p><strong>Write the test first, then the code.</strong> Reason: This ensures that you write testable code and that every line of code gets tests written for it.</p></li> <li><p><strong>Design classes using dependency injection.</strong> Reason: You cannot mock or test what cannot be seen.</p></li> <li><p><strong>Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter.</strong> Reason: Allows the business logic to be tested while the parts that can't be tested (the UI) is minimized.</p></li> <li><p><strong>Do not write static methods or classes.</strong> Reason: Static methods are difficult or impossible to isolate and Rhino Mocks is unable to mock them.</p></li> <li><p><strong>Program off interfaces, not classes.</strong> Reason: Using interfaces clarifies the relationships between objects. An interface should define a service that an object needs from its environment. Also, interfaces can be easily mocked using Rhino Mocks and other mocking frameworks.</p></li> <li><p><strong>Isolate external dependencies.</strong> Reason: Unresolved external dependencies cannot be tested.</p></li> <li><p><strong>Mark as virtual the methods you intend to mock.</strong> Reason: Rhino Mocks is unable to mock non-virtual methods.</p></li> </ol>
[ { "answer_id": 125600, "author": "zadam", "author_id": 410357, "author_profile": "https://Stackoverflow.com/users/410357", "pm_score": 3, "selected": false, "text": "// ShouldExpectMethodCallWithVariable\nint value = 5;\nvar mock = new Mock<IFoo>();\n\nmock.Expect(x => x.Duplicate(value)).Returns(() => value * 2);\n\nAssert.AreEqual(value * 2, mock.Object.Duplicate(value));\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10475/" ]
124,240
<p>Been using <strong>PHP/MySQL</strong> for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using <code>mysql_fetch_object()</code> vs <code>mysql_fetch_assoc()</code> / <code>mysql_fetch_array()</code>.</p>
[ { "answer_id": 124262, "author": "Steve Paulo", "author_id": 9414, "author_profile": "https://Stackoverflow.com/users/9414", "pm_score": 2, "selected": false, "text": "mysql_fetch_array() mysql_fetch_object()" }, { "answer_id": 124270, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 0, "selected": false, "text": "mysql_fetch_row()" }, { "answer_id": 124285, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "while ($Row = mysql_fetch_object($rs)) {\n // ...do stuff...\n}\n" }, { "answer_id": 124308, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 6, "selected": true, "text": "while ($row = mysql_fetch_object($result)) {\n echo $row->user_id;\n echo $row->fullname;\n}\n while ($row = mysql_fetch_assoc($result)) {\n echo $row[\"userid\"];\n echo $row[\"fullname\"];\n}\n while ($row = mysql_fetch_array($result)) {\n echo $row[0];\n echo $row[1] ;\n}\n" }, { "answer_id": 124369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "mysql_fetch_object() mysql_fetch_array() mysql_fetch_row() mysql_fetch_object()" }, { "answer_id": 124488, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": -1, "selected": false, "text": "mysql_fetch_array()" }, { "answer_id": 1263021, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "mysql_fetch_array mysql_fetch_object tax-allowance user.id {} $row->{$column_name} $row[$column_name] stdClass mysql_fetch_assoc $object->property=$row['column1'];\n$object->property=$row[$column_name];\nforeach($row as $column_name=>$column_value){...}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2227/" ]
124,250
<p>Anybody know a nice way to restart a mongrel cluster via capistrano in a "rolling" style, eg, one mongrel at a time. Would be great to have a bit of wait time in there as well for each, to let the mongrel load the rails app up as well. </p> <p>I've done some searching, and haven't found too much, so looking for help before I dive into the mongrel_cluster gem myself.</p> <p>Thanks!</p>
[ { "answer_id": 124962, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 1, "selected": false, "text": "#!/bin/bash\nfor PIDFILE in /tmp/mongrel.*; do\n PID=$(cat ${PIDFILE})\n kill ${PID}\n ${RUN_MONGREL_CMD} ${PID}\n sleep 2\ndone\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14873/" ]
124,266
<p>What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.</p> <pre><code>$sortedObjectArary = sort($unsortedObjectArray, $Object-&gt;weight); </code></pre> <p>Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious.</p>
[ { "answer_id": 124283, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 7, "selected": true, "text": "function compare_weights($a, $b) { \n if($a->weight == $b->weight) {\n return 0;\n } \n return ($a->weight < $b->weight) ? -1 : 1;\n} \n\nusort($unsortedObjectArray, 'compare_weights');\n" }, { "answer_id": 124290, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "function objectWeightSort($lhs, $rhs)\n{\n if ($lhs->weight == $rhs->weight)\n return 0;\n\n if ($lhs->weight > $rhs->weight)\n return 1;\n\n return -1;\n}\n\nusort($unsortedObjectArray, \"objectWeightSort\");\n" }, { "answer_id": 124292, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "$sortedObjectArray = usort($unsortedObjectArray, 'sort_by_weight');\n\nfunction sort_by_weight($a, $b) {\n if ($a->weight == $b->weight) {\n return 0;\n } else if ($a->weight < $b->weight) {\n return -1;\n } else {\n return 1;\n }\n}\n" }, { "answer_id": 124464, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "class thingy\n{\n public $prop1;\n public $prop2;\n\n static $sortKey;\n\n public function __construct( $prop1, $prop2 )\n {\n $this->prop1 = $prop1;\n $this->prop2 = $prop2;\n }\n\n public static function sorter( $a, $b )\n {\n return strcasecmp( $a->{self::$sortKey}, $b->{self::$sortKey} );\n }\n\n public static function sortByProp( &$collection, $prop )\n {\n self::$sortKey = $prop;\n usort( $collection, array( __CLASS__, 'sorter' ) );\n }\n\n}\n\n$thingies = array(\n new thingy( 'red', 'blue' )\n , new thingy( 'apple', 'orange' )\n , new thingy( 'black', 'white' )\n , new thingy( 'democrat', 'republican' )\n);\n\nprint_r( $thingies );\n\nthingy::sortByProp( $thingies, 'prop1' );\n\nprint_r( $thingies );\n\nthingy::sortByProp( $thingies, 'prop2' );\n\nprint_r( $thingies );\n" }, { "answer_id": 1319936, "author": "Will Shaver", "author_id": 68567, "author_profile": "https://Stackoverflow.com/users/68567", "pm_score": 4, "selected": false, "text": "function osort(&$array, $prop)\n{\n usort($array, function($a, $b) use ($prop) {\n return $a->$prop > $b->$prop ? 1 : -1;\n }); \n}\n" }, { "answer_id": 4608732, "author": "Tom", "author_id": 564520, "author_profile": "https://Stackoverflow.com/users/564520", "pm_score": 2, "selected": false, "text": "function cmp( $a, $b )\n{ \n return $b->weight - $a->weight;\n} \n" }, { "answer_id": 10989148, "author": "biswarupadhikari", "author_id": 997163, "author_profile": "https://Stackoverflow.com/users/997163", "pm_score": 0, "selected": false, "text": "function PHPArrayObjectSorter($array,$sortBy,$direction='asc')\n{\n $sortedArray=array();\n $tmpArray=array();\n foreach($this->$array as $obj)\n {\n $tmpArray[]=$obj->$sortBy;\n }\n if($direction=='asc'){\n asort($tmpArray);\n }else{\n arsort($tmpArray);\n }\n\n foreach($tmpArray as $k=>$tmp){\n $sortedArray[]=$array[$k];\n }\n\n return $sortedArray;\n\n}\n $myAscSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,'asc');\n\n$myDescSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,'desc');\n" }, { "answer_id": 35612669, "author": "Ihor Burlachenko", "author_id": 543280, "author_profile": "https://Stackoverflow.com/users/543280", "pm_score": 0, "selected": false, "text": "use function \\nspl\\a\\sorted;\nuse function \\nspl\\op\\propertyGetter;\nuse function \\nspl\\op\\methodCaller;\n\n// Sort by property value\n$sortedByWeight = sorted($objects, propertyGetter('weight'));\n\n// Or sort by result of method call\n$sortedByWeight = sorted($objects, methodCaller('getWeight'));\n" }, { "answer_id": 71196507, "author": "Syscall", "author_id": 9193372, "author_profile": "https://Stackoverflow.com/users/9193372", "pm_score": 0, "selected": false, "text": "usort($array, fn(object $a, object $b): int => $a->weight <=> $b->weight);\n $array = [\n (object) ['weight' => 5],\n (object) ['weight' => 10],\n (object) ['weight' => 1],\n];\n\nusort($array, fn(object $a, object $b): int => $a->weight <=> $b->weight);\n// Now, $array is sorted by objects' weight.\n\n// display example :\necho json_encode($array);\n [{\"weight\":1},{\"weight\":5},{\"weight\":10}]\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8880/" ]
124,269
<p>What is the simplest SOAP example using Javascript?</p> <p>To be as useful as possible, the answer should:</p> <ul> <li>Be functional (in other words actually work)</li> <li>Send at least one parameter that can be set elsewhere in the code</li> <li>Process at least one result value that can be read elsewhere in the code</li> <li>Work with most modern browser versions</li> <li>Be as clear and as short as possible, without using an external library</li> </ul>
[ { "answer_id": 124663, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <GetInfoByZIP xmlns=\"http://www.webserviceX.NET\">\n <USZip>string</USZip>\n </GetInfoByZIP>\n </soap:Body>\n</soap:Envelope>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <soap:Body>\n <GetInfoByZIPResponse xmlns=\"http://www.webserviceX.NET\">\n <GetInfoByZIPResult>\n <NewDataSet xmlns=\"\">\n <Table>\n <CITY>...</CITY>\n <STATE>...</STATE>\n <ZIP>...</ZIP>\n <AREA_CODE>...</AREA_CODE>\n <TIME_ZONE>...</TIME_ZONE>\n </Table>\n </NewDataSet>\n </GetInfoByZIPResult>\n </GetInfoByZIPResponse>\n </soap:Body>\n</soap:Envelope>\n" }, { "answer_id": 1695390, "author": "Chris Stuart", "author_id": 205909, "author_profile": "https://Stackoverflow.com/users/205909", "pm_score": 6, "selected": false, "text": "var symbol = \"MSFT\"; \nvar xmlhttp = new XMLHttpRequest();\nxmlhttp.open(\"POST\", \"http://www.webservicex.net/stockquote.asmx?op=GetQuote\",true);\nxmlhttp.onreadystatechange=function() {\n if (xmlhttp.readyState == 4) {\n alert(xmlhttp.responseText);\n // http://www.terracoder.com convert XML to JSON \n var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);\n var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;\n // Result text is escaped XML string, convert string to XML object then convert to JSON object\n json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));\n alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text); \n }\n}\nxmlhttp.setRequestHeader(\"SOAPAction\", \"http://www.webserviceX.NET/GetQuote\");\nxmlhttp.setRequestHeader(\"Content-Type\", \"text/xml\");\nvar xml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' +\n '<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ' +\n 'xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ' +\n 'xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">' + \n '<soap:Body> ' +\n '<GetQuote xmlns=\"http://www.webserviceX.NET/\"> ' +\n '<symbol>' + symbol + '</symbol> ' +\n '</GetQuote> ' +\n '</soap:Body> ' +\n '</soap:Envelope>';\nxmlhttp.send(xml);\n// ...Include Google and Terracoder JS code here...\n" }, { "answer_id": 3738629, "author": "user423430", "author_id": 423430, "author_profile": "https://Stackoverflow.com/users/423430", "pm_score": 2, "selected": false, "text": "function fncAddTwoIntegers(a, b)\n{\n varoXmlHttp = new XMLHttpRequest();\n oXmlHttp.open(\"POST\",\n \"http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'\",\n false);\n oXmlHttp.setRequestHeader(\"Content-Type\", \"text/xml\");\n oXmlHttp.setRequestHeader(\"SOAPAction\", \"http://tempuri.org/AddTwoIntegers\");\n oXmlHttp.send(\" \\\n<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \\\nxmlns:xsd='http://www.w3.org/2001/XMLSchema' \\\n xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \\\n <soap:Body> \\\n <AddTwoIntegers xmlns='http://tempuri.org/'> \\\n <IntegerOne>\" + a + \"</IntegerOne> \\\n <IntegerTwo>\" + b + \"</IntegerTwo> \\\n </AddTwoIntegers> \\\n </soap:Body> \\\n</soap:Envelope> \\\n\");\n return oXmlHttp.responseXML.selectSingleNode(\"//AddTwoIntegersResult\").text;\n}\n" }, { "answer_id": 11404133, "author": "stackoverflow128", "author_id": 1039677, "author_profile": "https://Stackoverflow.com/users/1039677", "pm_score": 9, "selected": true, "text": "<html>\n<head>\n <title>SOAP JavaScript Client Test</title>\n <script type=\"text/javascript\">\n function soap() {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open('POST', 'https://somesoapurl.com/', true);\n\n // build SOAP request\n var sr =\n '<?xml version=\"1.0\" encoding=\"utf-8\"?>' +\n '<soapenv:Envelope ' + \n 'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ' +\n 'xmlns:api=\"http://127.0.0.1/Integrics/Enswitch/API\" ' +\n 'xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ' +\n 'xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">' +\n '<soapenv:Body>' +\n '<api:some_api_call soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">' +\n '<username xsi:type=\"xsd:string\">login_username</username>' +\n '<password xsi:type=\"xsd:string\">password</password>' +\n '</api:some_api_call>' +\n '</soapenv:Body>' +\n '</soapenv:Envelope>';\n\n xmlhttp.onreadystatechange = function () {\n if (xmlhttp.readyState == 4) {\n if (xmlhttp.status == 200) {\n alert(xmlhttp.responseText);\n // alert('done. use firebug/console to see network response');\n }\n }\n }\n // Send the POST request\n xmlhttp.setRequestHeader('Content-Type', 'text/xml');\n xmlhttp.send(sr);\n // send request\n // ...\n }\n </script>\n</head>\n<body>\n <form name=\"Demo\" action=\"\" method=\"post\">\n <div>\n <input type=\"button\" value=\"Soap\" onclick=\"soap();\" />\n </div>\n </form>\n</body>\n</html> <!-- typo -->\n" }, { "answer_id": 16495780, "author": "Hkachhia", "author_id": 1220955, "author_profile": "https://Stackoverflow.com/users/1220955", "pm_score": 3, "selected": false, "text": "<html>\n <head>\n <title>Calling Web Service from jQuery</title>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function () {\n $(\"#btnCallWebService\").click(function (event) {\n var wsUrl = \"http://abc.com/services/soap/server1.php\";\n var soapRequest ='<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Body> <getQuote xmlns:impl=\"http://abc.com/services/soap/server1.php\"> <symbol>' + $(\"#txtName\").val() + '</symbol> </getQuote> </soap:Body></soap:Envelope>';\n alert(soapRequest)\n $.ajax({\n type: \"POST\",\n url: wsUrl,\n contentType: \"text/xml\",\n dataType: \"xml\",\n data: soapRequest,\n success: processSuccess,\n error: processError\n });\n\n });\n });\n\n function processSuccess(data, status, req) { alert('success');\n if (status == \"success\")\n $(\"#response\").text($(req.responseXML).find(\"Result\").text());\n\n alert(req.responseXML);\n }\n\n function processError(data, status, req) {\n alert('err'+data.state);\n //alert(req.responseText + \" \" + status);\n } \n\n </script>\n</head>\n<body>\n <h3>\n Calling Web Services with jQuery/AJAX\n </h3>\n Enter your name:\n <input id=\"txtName\" type=\"text\" />\n <input id=\"btnCallWebService\" value=\"Call web service\" type=\"button\" />\n <div id=\"response\" ></div>\n</body>\n</html>\n" }, { "answer_id": 25885366, "author": "Nick", "author_id": 4049436, "author_profile": "https://Stackoverflow.com/users/4049436", "pm_score": 0, "selected": false, "text": "function SoapQuery(){\n var namespace = \"http://tempuri.org/\";\n var site = \"http://server.com/Service.asmx\";\n var xmlhttp = new ActiveXObject(\"Msxml2.ServerXMLHTTP.6.0\");\n xmlhttp.setOption(2, 13056 ); /* if use standard proxy */\n var args,fname = arguments.callee.caller.toString().match(/ ([^\\(]+)/)[1]; /*Имя вызвавшей ф-ции*/\n try { args = arguments.callee.caller.arguments.callee.toString().match(/\\(([^\\)]+)/)[1].split(\",\"); \n } catch (e) { args = Array();};\n xmlhttp.open('POST',site,true); \n var i, ret = \"\", q = '<?xml version=\"1.0\" encoding=\"utf-8\"?>'+\n '<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">'+\n '<soap:Body><'+fname+ ' xmlns=\"'+namespace+'\">';\n for (i=0;i<args.length;i++) q += \"<\" + args[i] + \">\" + arguments.callee.caller.arguments[i] + \"</\" + args[i] + \">\";\n q += '</'+fname+'></soap:Body></soap:Envelope>';\n // Send the POST request\n xmlhttp.setRequestHeader(\"MessageType\",\"CALL\");\n xmlhttp.setRequestHeader(\"SOAPAction\",namespace + fname);\n xmlhttp.setRequestHeader('Content-Type', 'text/xml');\n //WScript.Echo(\"Запрос XML:\" + q);\n xmlhttp.send(q);\n if (xmlhttp.waitForResponse(5000)) ret = xmlhttp.responseText;\n return ret;\n };\n\n\n\n\n\nfunction GetForm(prefix,post_vars){return SoapQuery();};\nfunction SendOrder2(guid,order,fio,phone,mail){return SoapQuery();};\n\nfunction SendOrder(guid,post_vars){return SoapQuery();};\n" }, { "answer_id": 26917422, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 4, "selected": false, "text": "$.soap({\n url: 'http://my.server.com/soapservices/',\n method: 'helloWorld',\n\n data: {\n name: 'Remy Blom',\n msg: 'Hi!'\n },\n\n success: function (soapResponse) {\n // do stuff with soapResponse\n // if you want to have the response as JSON use soapResponse.toJSON();\n // or soapResponse.toString() to get XML string\n // or soapResponse.toXML() to get XML DOM\n },\n error: function (SOAPResponse) {\n // show error\n }\n});\n" }, { "answer_id": 32747597, "author": "geekasso", "author_id": 1766113, "author_profile": "https://Stackoverflow.com/users/1766113", "pm_score": 3, "selected": false, "text": "$.soap({\nurl: 'http://my.server.com/soapservices/',\nmethod: 'helloWorld',\n\ndata: {\n name: 'Remy Blom',\n msg: 'Hi!'\n},\n\nsuccess: function (soapResponse) {\n // do stuff with soapResponse\n // if you want to have the response as JSON use soapResponse.toJSON();\n // or soapResponse.toString() to get XML string\n // or soapResponse.toXML() to get XML DOM\n},\nerror: function (SOAPResponse) {\n // show error\n}\n});\n <soap:Envelope\nxmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <helloWorld>\n <name>Remy Blom</name>\n <msg>Hi!</msg>\n </helloWorld>\n </soap:Body>\n</soap:Envelope>\n" }, { "answer_id": 39073092, "author": "ChokYeeFan", "author_id": 3754672, "author_profile": "https://Stackoverflow.com/users/3754672", "pm_score": 0, "selected": false, "text": "\"Content-Type\": \"text/xml; charset=utf-8\"\n function callSoap(){\nvar url = \"http://www.webservicex.com/stockquote.asmx\";\nvar soapXml = \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:web=\\\"http://www.webserviceX.NET/\\\"> \"+\n \"<soapenv:Header/> \"+\n \"<soapenv:Body> \"+\n \"<web:GetQuote> \"+\n \"<web:symbol></web:symbol> \"+\n \"</web:GetQuote> \"+\n \"</soapenv:Body> \"+\n \"</soapenv:Envelope> \";\n\n return $http({\n url: url, \n method: \"POST\", \n data: soapXml, \n headers: { \n \"Content-Type\": \"text/xml; charset=utf-8\"\n } \n })\n .then(callSoapComplete)\n .catch(function(message){\n return message;\n });\n\n function callSoapComplete(data, status, headers, config) {\n // Convert to JSON Ojbect from xml\n // var x2js = new X2JS();\n // var str2json = x2js.xml_str2json(data.data);\n // return str2json;\n return data.data;\n\n }\n\n}\n" }, { "answer_id": 49648585, "author": "Yuci", "author_id": 2700356, "author_profile": "https://Stackoverflow.com/users/2700356", "pm_score": 2, "selected": false, "text": "const XMLHttpRequest = require(\"xmlhttprequest\").XMLHttpRequest;\nconst DOMParser = require('xmldom').DOMParser;\n\nfunction parseXml(text) {\n let parser = new DOMParser();\n let xmlDoc = parser.parseFromString(text, \"text/xml\");\n Array.from(xmlDoc.getElementsByTagName(\"reference\")).forEach(function (item) {\n console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);\n });\n\n}\n\nfunction soapRequest(url, payload) {\n let xmlhttp = new XMLHttpRequest();\n xmlhttp.open('POST', url, true);\n\n // build SOAP request\n xmlhttp.onreadystatechange = function () {\n if (xmlhttp.readyState == 4) {\n if (xmlhttp.status == 200) {\n parseXml(xmlhttp.responseText);\n }\n }\n }\n\n // Send the POST request\n xmlhttp.setRequestHeader('Content-Type', 'text/xml');\n xmlhttp.send(payload);\n}\n\nsoapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap', \n `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <S:Header />\n <S:Body>\n <ns4:getReferences xmlns:ns4=\"http://webservice.cdb.ebi.ac.uk/\"\n xmlns:ns2=\"http://www.scholix.org\"\n xmlns:ns3=\"https://www.europepmc.org/data\">\n <id>C7886</id>\n <source>CTX</source>\n <offSet>0</offSet>\n <pageSize>25</pageSize>\n <email>ukpmc-phase3-wp2b---do-not-reply@europepmc.org</email>\n </ns4:getReferences>\n </S:Body>\n </S:Envelope>`);\n npm install xmlhttprequest\nnpm install xmldom\n node soap-node.js\n Title: Perspective: Sustaining the big-data ecosystem.\nTitle: Making proteomics data accessible and reusable: current state of proteomics databases and repositories.\nTitle: ProteomeXchange provides globally coordinated proteomics data submission and dissemination.\nTitle: Toward effective software solutions for big biology.\nTitle: The NIH Big Data to Knowledge (BD2K) initiative.\nTitle: Database resources of the National Center for Biotechnology Information.\nTitle: Europe PMC: a full-text literature database for the life sciences and platform for innovation.\nTitle: Bio-ontologies-fast and furious.\nTitle: BioPortal: ontologies and integrated data resources at the click of a mouse.\nTitle: PubMed related articles: a probabilistic topic-based model for content similarity.\nTitle: High-Impact Articles-Citations, Downloads, and Altmetric Score.\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15985/" ]
124,291
<p>I need to do some simple timezone calculation in mod_perl. DateTime isn't an option. What I need to do is easily accomplished by setting $ENV{TZ} and using localtime and POSIX::mktime, but under a threaded MPM, I'd need to make sure only one thread at a time was mucking with the environment. (I'm not concerned about other uses of localtime, etc.)</p> <p>How can I use a mutex or other locking strategy to serialize (in the non-marshalling sense) access to the environment? The <a href="http://perl.apache.org/docs/2.0/api/APR/ThreadMutex.html" rel="nofollow noreferrer">docs</a> I've looked at don't explain well enough how I would create a mutex for just this use. Maybe there's something I'm just not getting about how you create mutexes in general.</p> <p>Update: yes, I am aware of the need for using Env::C to set TZ.</p>
[ { "answer_id": 125010, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 1, "selected": false, "text": "{\n local $ENV{TZ} = whatever_I_need_it_to_be();\n\n # Do calculations here.\n}\n local Paul\n" }, { "answer_id": 125533, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 2, "selected": false, "text": "BEGIN {\n my $mutex;\n\n sub that {\n $mutex ||= APR::ThreadMutex->new( $r->pool() );\n $mutex->lock();\n\n $ENV{TZ}= ...;\n ...\n\n $mutex->unlock();\n }\n}\n BEGIN {\n my $mutex;\n\n sub that {\n my $autoLock= APR::ThreadMutex->autoLock( \\$mutex );\n ...\n # Mutex automatically released when $autoLock destroyed\n }\n}\n" }, { "answer_id": 127321, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 2, "selected": false, "text": "/* * XXX: what we do here might change:\n * - make it optional for %ENV to be tied to r->subprocess_env\n * - make it possible to modify environ\n * - we could allow modification of environ if mpm isn't threaded\n * - we could allow modification of environ if variable isn't a CGI\n * variable (still could cause problems)\n */\n/*\n * problems we are trying to solve:\n * - environ is shared between threads\n * + Perl does not serialize access to environ\n * + even if it did, CGI variables cannot be shared between threads!\n * problems we create by trying to solve above problems:\n * - a forked process will not inherit the current %ENV\n * - C libraries might rely on environ, e.g. DBD::Oracle\n */\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17389/" ]
124,295
<p>Everything I have read says that when making a managed stored procedure, to right click in Visual Studio and choose deploy. That works fine, but what if I want to deploy it outside of Visual Studio to a number of different locations? I tried creating the assembly with the dll the project built in SQL, and while it did add the assembly, it did not create the procedures out of the assembly. Has anyone figured out how to do this in SQL directly, without using Visual Studio?</p>
[ { "answer_id": 124528, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 4, "selected": true, "text": "create assembly [YOUR_ASSEMBLY]\nfrom '(PATH_TO_DLL)'\n create proc [YOUR_FUNCTION]\nas\nexternal name [YOUR_ASSEMBLY].[NAME_SPACE].[YOUR_METHOD]\n" }, { "answer_id": 2874274, "author": "Grhm", "author_id": 204690, "author_profile": "https://Stackoverflow.com/users/204690", "pm_score": 2, "selected": false, "text": "StoredProcedures My.Name.Space [My.Name.Space.StoredProcedures] [StoredProcedures] CREATE PROCEDURE [YOUR_FUNCTION] \n( \n @parameter1 int,\n @parameter2 nvarchar\n) \nWITH EXECUTE AS CALLER \nAS\nEXTERNAL NAME [YOUR_ASSEMBLY].[StoredProcedures].[YOUR_FUNCTION] \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539/" ]
124,296
<p>Let's say that I have a widget that displays summary information about how many posts or comments that I have on a site.</p> <p>What's the cleanest way to persist this information across controllers? </p> <p>Including the instance variables in the application controller seems like a bad idea. Having a before filter that loads the data for each controller smells like code duplication. </p> <p>Do I have to use a plugin like the Cells Plugin (<a href="http://cells.rubyforge.org/" rel="nofollow noreferrer">http://cells.rubyforge.org/</a>) or is there a simpler way of doing it?</p>
[ { "answer_id": 128626, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "def load_sidebar\n @posts = Post.find(:all)\nend\n before_filter :load_sidebar, :only => [ :index ] #load from application.rb file\n" }, { "answer_id": 129246, "author": "jdl", "author_id": 9465, "author_profile": "https://Stackoverflow.com/users/9465", "pm_score": 0, "selected": false, "text": "def load_sidebar\n @posts = Post.find(:all)\nend\n def load_sidebar\n @post_count = Post.count(:id)\nend\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
124,299
<p>So I'm using hibernate and working with an application that manages time. What is the best way to deal with times in a 24 hour clock?</p> <p>I do not need to worry about TimeZone issues at the beginning of this application but it would be best to ensure that this functionality is built in at the beginning.</p> <p>I'm using hibernate as well, just as an fyi</p>
[ { "answer_id": 125025, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 0, "selected": false, "text": "java.util.Date Calendar @Temporal" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129162/" ]
124,313
<p>I'm working on an application that is supposed to create products (like shipping insurance policies) when PayPal Instant Payment Notifications are received. Unfortunately, PayPal sometimes sends duplicate notifications. Furthermore, there is another third-party that is performing web-service updates simultaneously when they get updates from PayPal as well.</p> <p>Here is a basic diagram of the database tables involved.</p> <pre><code>// table "package" // columns packageID, policyID, other data... // // table "insurancepolicy" // columns policyID, coverageAmount, other data... </code></pre> <p>Here is a basic diagram of what I want to do:</p> <pre><code>using (SqlConnection conn = new SqlConnection(...)) { sqlTransaction sqlTrans = conn.BeginTransaction(IsolationLevel.RepeatableRead); // Calls a stored procedure that checks if the foreign key in the transaction table has a value. if (PackageDB.HasInsurancePolicy(packageID, conn)) { sqlTrans.Commit(); return false; } // Insert row in foreign table. int policyID = InsurancePolicyDB.Insert(coverageAmount, conn); if (policyID &lt;= 0) { sqlTrans.Rollback(); return false; } // Assign foreign key to parent table. If this fails, roll back everything. bool assigned = PackageDB.AssignPolicyID(packageID, policyID, conn); if (!assigned) { sqlTrans.Rollback(); return false; } } </code></pre> <p>If there are two (or more) threads (or processes or applications) doing this at the same time, I want the first thread to lock the "package" row while it has no policyID, until the policy is created and the policyID is assigned to the package table. Then the lock would be released after the policyID is assigned to the package table. It is my hope that the other thread which is calling this same code will pause when it reads the package row to make sure it doesn't have a policyID first. When the first transaction's lock is released, it is my hope that the second transaction will see the policyID is there and therefore return without inserting any rows into the policy table.</p> <p>Note: Because of the CRUD database design, each the stored procedures involved either Read (select), Create (insert), or Update.</p> <p>Is this the right use of RepeatableRead transaction isolation?</p> <p>Thanks.</p>
[ { "answer_id": 124763, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": true, "text": "insert into Policy begin tran (read committed)\n\n/* tentatively insert new Policy */\ninsert Policy\n\n/* attach Package to Policy if it's still free */\nupdate Package\n set Package.policy_id = @policy_id\n where Package.package_id = @package_id and Package.policy_id is null\n\nif @@rowcount > 0\n commit\nelse\n rollback\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16454/" ]
124,325
<p>I'm trying to grasp the concept of .NET Generics and actually use them in my own code but I keep running into a problem.</p> <p>Can someone try to explain to me why the following setup does not compile?</p> <pre><code>public class ClassA { ClassB b = new ClassB(); public void MethodA&lt;T&gt;(IRepo&lt;T&gt; repo) where T : ITypeEntity { b.MethodB(repo); } } public class ClassB { IRepo&lt;ITypeEntity&gt; repo; public void MethodB(IRepo&lt;ITypeEntity&gt; repo) { this.repo = repo; } } </code></pre> <p>I get the following error:<br> cannot convert from IRepo&lt;'T> to IRepo&lt;'ITypeEntity></p> <p>MethodA gets called with a IRepo&lt;'DetailType> object parameter where DetailType inherits from ITypeEntity.</p> <p>I keep thinking that this should compile as I'm constraining T within MethodA to be of type ITypeEntity.</p> <p>Any thoughts or feedback would be extremely helpful.</p> <p>Thanks.</p> <p><b>Edit:</b> Nick R has a great suggestion but unfortunately in my context, I don't have the option of making ClassA Generic. ClassB could be though.</p>
[ { "answer_id": 124388, "author": "Smashery", "author_id": 14902, "author_profile": "https://Stackoverflow.com/users/14902", "pm_score": 0, "selected": false, "text": "Class<B> Class<A> T ITypeEntity IRepo<T> IRepo<ITypeEntity>" }, { "answer_id": 124418, "author": "Nick Randell", "author_id": 5932, "author_profile": "https://Stackoverflow.com/users/5932", "pm_score": 2, "selected": false, "text": "public interface IRepo<TRepo>\n{\n}\n\npublic interface ITypeEntity\n{\n}\n\n\npublic class ClassA<T> where T : ITypeEntity\n{\n ClassB<T> b = new ClassB<T>();\n public void MethodA(IRepo<T> repo)\n {\n b.MethodB(repo);\n }\n}\npublic class ClassB<T> where T : ITypeEntity\n{\n IRepo<T> repo;\n public void MethodB(IRepo<T> repo)\n {\n this.repo = repo;\n }\n}\n" }, { "answer_id": 124423, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 1, "selected": false, "text": "IRepo<T> IRepo<ITypeEntity> IRepo<T> IRepo<ITypeEntity> ITypeEntity where MethodA Dictionary<<K, V> Dictionary<K, V> IComparer<T>" }, { "answer_id": 124514, "author": "Lucas Wilson-Richter", "author_id": 1157, "author_profile": "https://Stackoverflow.com/users/1157", "pm_score": 3, "selected": true, "text": "myType<TypeA> a; // This should be a myType<TypeB>, even if it contains only TypeA's\n\npublic void MethodB(myType<TypeB> b){ /* do stuff */ }\n\npublic void Main()\n{\n MethodB(a);\n}\n public void MethodA<T>(IList<T> list) where T : ITypeEntity\n{\n IList<T> myIList = new List<T>();\n\n foreach(T item in list)\n {\n myIList.Add(item);\n }\n\n b.MethodB(myIList);\n}\n" }, { "answer_id": 124628, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "T IIF<T>(bool Expression, T TruePart, T FalsePart)\n{\n return Expression ? TruePart : FalsePart;\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384853/" ]
124,326
<p>JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the reverse, and add a function to an "object"?</p> <p>This works:</p> <pre><code>var foo = function() { return 1; }; foo.baz = "qqqq"; </code></pre> <p>At this point, <code>foo()</code> calls the function, and <code>foo.baz</code> has the value "qqqq".</p> <p>However, if you do the property assignment part first, how do you subsequently assign a function to the variable?</p> <pre><code>var bar = { baz: "qqqq" }; </code></pre> <p>What can I do now to arrange for <code>bar.baz</code> to have the value "qqqq" <em>and</em> <code>bar()</code> to call the function?</p>
[ { "answer_id": 124359, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": -1, "selected": false, "text": "var three = 3;\nthree = 4;\nassert(three === 3);\n // assigns an anonymous function to the variable \"foo\"\nvar foo = function() { return 1; }; \n// assigns a string to the property \"baz\" on the object \n// referenced by \"foo\" (which, in this case, happens to be a function)\nfoo.baz = \"qqqq\";\n" }, { "answer_id": 124387, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 5, "selected": false, "text": "function functionize( obj , func )\n{ \n out = func; \n for( i in obj ){ out[i] = obj[i]; } ; \n return out; \n}\n\nx = { a: 1, b: 2 }; \nx = functionize( x , function(){ return \"hello world\"; } );\nx() ==> \"hello world\" \n x={}\nx() \n x = 1\n x[50] = 5\n print x[50] \n" }, { "answer_id": 124402, "author": "Avner", "author_id": 1476, "author_profile": "https://Stackoverflow.com/users/1476", "pm_score": 1, "selected": false, "text": "var xxx = function()...\n for (var p in bar) { xxx[p] = bar[p]; }\n bar = xxx;\n" }, { "answer_id": 124533, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 6, "selected": true, "text": "//these do the same thing\nvar foo = new Object();\nvar bar = {};\n var foo = new Function();\nvar bar = function(){};\nfunction baz(){};\n" }, { "answer_id": 4028231, "author": "JKempton", "author_id": 488150, "author_profile": "https://Stackoverflow.com/users/488150", "pm_score": -1, "selected": false, "text": "var bar = { \n baz: \"qqqq\",\n runFunc: function() {\n return 1;\n }\n};\n\nalert(bar.baz); // should produce qqqq\nalert(bar.runFunc()); // should produce 1\n function Bar() {\n this.baz = \"qqqq\";\n this.runFunc = function() {\n return 1;\n }\n}\n\nnBar = new Bar(); \n\nalert(nBar.baz); // should produce qqqq\nalert(nBar.runFunc()); // should produce 1\n" }, { "answer_id": 6098553, "author": "Ekim", "author_id": 725589, "author_profile": "https://Stackoverflow.com/users/725589", "pm_score": 2, "selected": false, "text": "alert([Array, Boolean, Date, Function, Number, Object, RegExp, String].join('\\n\\n'))\n function Array() {\n [native code]\n}\n\nfunction Boolean() {\n [native code]\n}\n\nfunction Date() {\n [native code]\n}\n\nfunction Function() {\n [native code]\n}\n\nfunction Number() {\n [native code]\n}\n\nfunction Object() {\n [native code]\n}\n\nfunction RegExp() {\n [native code]\n}\n\nfunction String() {\n [native code]\n}\n function Function() { [native code] } 1[50]=5 alert([\n [].prop=\"a\",\n true.sna=\"fu\",\n (new Date()).tar=\"fu\",\n function(){}.fu=\"bar\",\n 123[40]=4,\n {}.forty=2,\n /(?:)/.forty2=\"life\",\n \"abc\".def=\"ghi\"\n].join(\"\\t\"))\n a fu fu bar 4 2 life ghi\n = x=new Number(1); x[50]=5; alert(x[50]);\n prototyping alert( 123 . x = \"not\" );\n\nalert( (123). x = \"Yes!\" ); /* ()'s elevate to full object status */\n" }, { "answer_id": 8798525, "author": "Daniel Wozniak", "author_id": 1140071, "author_profile": "https://Stackoverflow.com/users/1140071", "pm_score": 1, "selected": false, "text": "var A = function(foo) { \n var B = function() { \n return A.prototype.constructor.apply(B, arguments);\n };\n B.prototype = A.prototype; \n return B; \n}; \n" }, { "answer_id": 37777039, "author": "Morvael", "author_id": 1286358, "author_profile": "https://Stackoverflow.com/users/1286358", "pm_score": 1, "selected": false, "text": "var parentObj = {}\n\nparentObj.createFunc = function (model)\n{\n // allow it to be instantiated\n parentObj[model._type] = function()\n {\n return (function (model)\n {\n // jQuery used to clone the model\n var that = $.extend(true, null, model);\n return that;\n })(model);\n }\n}\n var data = { _type: \"Example\", foo: \"bar\" };\nparentObject.createFunc(data);\nvar instance = new parentObject.Example();\n var parentObj = {};\n// base model contains client only stuff\nparentObj.baseModel =\n{\n parameter1: null,\n parameter2: null,\n parameterN: null, \n func1: function ()\n {\n return this.parameter2;\n },\n func2: function (inParams) \n {\n return this._variable2;\n }\n}\n\n// create a troop type\nparentObj.createModel = function (data)\n{\n var model = $.extend({}, parentObj.baseModel, data);\n // allow it to be instantiated\n parentObj[model._type] = function(parameter1, parameter2, parameterN)\n {\n return (function (model)\n {\n var that = $.extend(true, null, model);\n that.parameter1 = parameter1;\n that.parameter2 = parameter2;\n that.parameterN = parameterN;\n return that;\n })(model);\n }\n}\n // models received from an AJAX call\nvar models = [\n{ _type=\"Foo\", _variable1: \"FooVal\", _variable2: \"FooVal\" },\n{ _type=\"Bar\", _variable1: \"BarVal\", _variable2: \"BarVal\" },\n{ _type=\"FooBar\", _variable1: \"FooBarVal\", _variable2: \"FooBarVal\" }\n];\n\nfor(var i = 0; i < models.length; i++)\n{\n parentObj.createFunc(models[i]);\n}\n var test1 = new parentObj.Foo(1,2,3);\nvar test2 = new parentObj.Bar(\"a\",\"b\",\"c\");\nvar test3 = new parentObj.FooBar(\"x\",\"y\",\"z\");\n\n// test1.parameter1 == 1\n// test1._variable1 == \"FooVal\"\n// test1.func1() == 2\n\n// test2.parameter2 == \"a\"\n// test2._variable2 == \"BarVal\"\n// test2.func2() == \"BarVal\"\n\n// etc\n" }, { "answer_id": 74324345, "author": "Xavi", "author_id": 53926, "author_profile": "https://Stackoverflow.com/users/53926", "pm_score": 0, "selected": false, "text": "let bar = { baz: \"qqqq\" };\nbar = Object.assign(() => console.log(\"do something\"), bar)\n Object.assign bar" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11543/" ]
124,332
<p>I am using the RSA Algorithm for encryption/decryption, and in order to decrypt the files you have to deal with some pretty big values. More specifically, things like </p> <pre><code>P = C^d % n = 62^65 % 133 </code></pre> <p>Now that is really the only calculations that ill be doing. I have tried using Matt McCutchen's BigInteger Library, but I am getting a lot of compiler errors during linking, such as:</p> <pre><code>encryption.o(.text+0x187):encryption.cpp: undefined reference to `BigInteger::BigInteger(int)' encryption.o(.text+0x302):encryption.cpp: undefined reference to `operator&lt;&lt;(std::ostream&amp;, BigInteger const&amp;)' encryption.o(.text$_ZNK10BigIntegermlERKS_[BigInteger::operator*(BigInteger const&amp;) const]+0x63):encryption.cpp: undefined reference to `BigInteger::multiply(BigInteger const&amp;, BigInteger const&amp;)' </code></pre> <p>So I was wondering what would be the best way to go about handling the really big integers that come out of the RSA Algorithm.</p> <p>I heard that a possibility would be to declare your variables as a double long, so...</p> <pre><code>long long decryptedCharacter; </code></pre> <p>but I'm not sure exactly how big of an integer that can store.</p> <hr> <p>Well for example, I try to compile and run the following program using dev C++:</p> <pre><code>#include iostream #include "bigint\BigIntegerLibrary.hh" using namespace std; int main() { BigInteger a = 65536; cout &lt;&lt; (a * a * a * a * a * a * a * a); return 0; } </code></pre> <p>then I get those errors.</p> <p>Derek, I thought that by including the <code>BigIntegerLibrary.hh</code> file, that the compiler would go through and compile all the necessary files that it will use.</p> <p>How should I try and compile the program above in order to resolve the linking errors?</p>
[ { "answer_id": 124345, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n\nint main(void) {\n printf(\"%d\\n\", sizeof(long long));\n\n return 0;\n}\n" }, { "answer_id": 124475, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 4, "selected": false, "text": "BigInteger::BigInteger(int)" }, { "answer_id": 2329997, "author": "Vlad", "author_id": 280741, "author_profile": "https://Stackoverflow.com/users/280741", "pm_score": 2, "selected": false, "text": "long long mod_exp (long long n, long long e, long long mod)\n{\n if(e == 1)\n {\n return (n % mod);\n }\n else\n {\n if((e % 2) == 1)\n {\n long long temp = mod_exp(n, (e-1)/2, mod);\n return ((n * temp * temp) % mod);\n }\n else\n {\n long long temp = mod_exp(n, e/2, mod);\n return ((temp*temp) % mod); \n }\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
124,336
<p>I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking.</p> <pre><code>public class SomeBaseClass { public string GetBaseClassName {get;set;} public bool BooleanEvaluator {get;set;} } public class SomeDerivedClass : SomeBaseClass { public void Insert(SqlConnection connection) { //...random connection stuff cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar; //... } } public static void Main(object[] args) { SomeBaseClass baseClass = new SomeBaseClass(); SomeDerivedClass derClass = (SomeDerivedClass)baseClass; derClass.Insert(new sqlConnection()); } </code></pre> <p>I know this seems goofy but is there any way to accomplish something of this sort?</p>
[ { "answer_id": 124429, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": false, "text": "SomeBaseClass class = new SomeBaseClass();\nSomeDerivedClass derClass = (SomeDerivedClass)class; \n class SomeDerivedClass SomeBaseClass SomeDerivedClass" }, { "answer_id": 124684, "author": "Rob Fonseca-Ensor", "author_id": 21433, "author_profile": "https://Stackoverflow.com/users/21433", "pm_score": 4, "selected": false, "text": "public class BooleanHolder{ \n public bool BooleanEvaluator {get;set;}\n}\n\npublic class DatabaseInserter{\n BooleanHolder holder;\n\n public DatabaseInserter(BooleanHolder holder){\n this.holder = holder;\n }\n\n public void Insert(SqlConnection connection) {\n ...random connection stuff\n cmd.Parameters[\"IsItTrue\"].Value = holder.BooleanEvalutar;\n ...\n }\n}\n\npublic static void Main(object[] args) {\n BooleanHolder h = new BooleanHolder();\n DatabaseInserter derClass = new DatabaseInserter(h);\n derClass.Insert(new sqlConnection);\n}\n" }, { "answer_id": 2067325, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SomeDerivedClass derClass = class as SomeDerivedClass; //derClass is null if it isnt SomeDerivedClass\nif(class is SomeDerivedClass)\n ;\n" }, { "answer_id": 9687011, "author": "lbergnehr", "author_id": 647901, "author_profile": "https://Stackoverflow.com/users/647901", "pm_score": 0, "selected": false, "text": "class InternalDbType {\n public string Name { get; set; }\n public DateTime Date { get; set; }\n // Many more properties here...\n}\n\nclass SimpleDTO {\n public string Name { get; set; }\n // Many more properties here...\n}\n\nclass ComplexDTO : SimpleDTO {\n public string Date { get; set; }\n}\n\nstatic class InternalDbTypeExtensions {\n public static TDto ToDto<TDto>(this InternalDbType obj) where TDto : SimpleDTO, new() {\n var dto = new TDto {\n Name = obj.Name\n }\n }\n}\n" }, { "answer_id": 10404302, "author": "Donny V.", "author_id": 1231, "author_profile": "https://Stackoverflow.com/users/1231", "pm_score": 3, "selected": false, "text": "SomeDerivedClass layer = JsonConvert.DeserializeObject<SomeDerivedClass>(JsonConvert.SerializeObject(BaseClassObject));\n" }, { "answer_id": 12598540, "author": "Rob Sedgwick", "author_id": 1033684, "author_profile": "https://Stackoverflow.com/users/1033684", "pm_score": 4, "selected": false, "text": "private class ExtendedClass //: BaseClass - like to inherit but can't\n{\n public readonly BaseClass bc = null;\n public ExtendedClass(BaseClass b)\n {\n this.bc = b;\n }\n\n public int ExtendedProperty\n {\n get\n {\n }\n }\n}\n" }, { "answer_id": 15987692, "author": "Ark-kun", "author_id": 1497385, "author_profile": "https://Stackoverflow.com/users/1497385", "pm_score": 3, "selected": false, "text": "[System.Runtime.CompilerServices.SpecialName]\npublic static Derived op_Implicit(Base a) { ... }\n\n[System.Runtime.CompilerServices.SpecialName]\npublic static Derived op_Explicit(Base a) { ... }\n" }, { "answer_id": 25422648, "author": "johnnycardy", "author_id": 1842618, "author_profile": "https://Stackoverflow.com/users/1842618", "pm_score": 0, "selected": false, "text": "SomeDerivedClass public static T ToDerived<T>(this SomeBaseClass baseClass) \n where T:SomeBaseClass, new()\n{\n return new T()\n {\n BooleanEvaluator = baseClass.BooleanEvaluator,\n GetBaseClassName = baseClass.GetBaseClassName\n };\n}\n SomeBaseClass b = new SomeBaseClass();\nSomeDerivedClass c = b.ToDerived<SomeDerivedClass>();\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ]
124,358
<p>Although my question might seem abstract I hope it's not. Suppose I develop an application, an ASP.NET MVC site and later I am tasked to build an Winforms client for this application how much and how can I reuse from the existing application?</p> <p>I defined the models, I defined controllers and views. They all work well.</p> <p>Now the boss comes asking for a Winforms client and I am hoping I can reuse the models and the controllers (provided I put them in different assemblies) and not reuse just the views (ASPX views).</p> <p>Can this be done? How?</p>
[ { "answer_id": 124452, "author": "zadam", "author_id": 410357, "author_profile": "https://Stackoverflow.com/users/410357", "pm_score": 4, "selected": true, "text": "public interface IRuntimeContext\n{\n void TransferTo(string destination);\n}\n public class AspNetRuntimeContext\n{\n public void TransferTo(string destination)\n {\n Response.Redirect(destination);\n }\n}\n public class WinformsRuntimeContext\n{\n public void TransferTo(string destination)\n {\n var r = GetFormByName(destination);\n r.Show();\n }\n}\n public class SomePresenter\n{\n private readonly runtimeContext;\n public SomePresenter(IRuntimeContext runtimeContext)\n {\n this.runtimeContext = runtimeContext;\n }\n\n public void SomeAction()\n {\n // do some work\n\n // then transfer control to another page/form\n runtimeContext.TransferTo(\"somewhereElse\");\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ]
124,360
<p>I know there are several plugins that do asynchronous processing. Which one is the best one and why?</p> <p>The ones I know about are:</p> <ul> <li><a href="http://backgroundrb.rubyforge.org/" rel="noreferrer">BackgrounDRb</a></li> </ul>
[ { "answer_id": 125968, "author": "Olly", "author_id": 1174, "author_profile": "https://Stackoverflow.com/users/1174", "pm_score": 3, "selected": false, "text": "script/runner" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9594/" ]
124,374
<p>I need to recursively search directories and replace a string (say <a href="http://development:port/URI" rel="nofollow noreferrer">http://development:port/URI</a>) with another (say <a href="http://production:port/URI" rel="nofollow noreferrer">http://production:port/URI</a>) in all the files where ever it's found. Can anyone help?</p> <p>It would be much better if that script can print out the files that it modified and takes the search/replace patterns as input parameters.</p> <p>Regards.</p>
[ { "answer_id": 124404, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": true, "text": "find . -type f | xargs grep -l development | xargs perl -i.bak -p -e 's(http://development)(http://production)g'\n find . -type f | while read file\ndo\n grep development $file && echo \"modifying $file\" && perl -i.bak -p -e 's(http://development)(http://prodution)g' $file\ndone\n" }, { "answer_id": 132247, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "zsh sed -i 's:pattern:target:g' ./**\n" }, { "answer_id": 1439657, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "find . -type f | fgrep -v .svn | xargs sed -i 's/pattern/replacement/g'\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1408/" ]
124,378
<p>I'm running my workstation on Server 2008 and a few servers in Hyper-V VM's on that server. I connect to my corporate LAN using VPN from the main OS (the host) but my VM's aren't seeing the servers in the corporate LAN. Internet and local access to my home network work fine. Each of the VMs has one virtual network adapter. </p> <p>What should I try to make it work?</p> <p>Maybe I need to provide more details, please ask if needed.</p> <p><strong>More details:</strong></p> <ul> <li>cannot start multiple VPN connections </li> <li>not using NAT through the host</li> <li>VM gets IP address from the home network router (DHCP)</li> </ul>
[ { "answer_id": 129541, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "route ADD 10.0.0.0 MASK 255.0.0.0 192.168.1.30\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21420/" ]
124,392
<p>I am calling a PHP-Script belonging to a MySQL/PHP web application using FF3. I run XAMPP on localhost. All I get is this:</p> <blockquote> <p>Connection Interrupted<br> The connection to the server was reset while the page was loading. The network link was interrupted while negotiating a connection. Please try again.</p> </blockquote>
[ { "answer_id": 6134271, "author": "DevByStarlight", "author_id": 735533, "author_profile": "https://Stackoverflow.com/users/735533", "pm_score": 3, "selected": false, "text": "Parent: child process exited with status 3221225477 -- Restarting set GLOBAL storage_engine='InnoDb';" }, { "answer_id": 12046674, "author": "Augustine Arthur", "author_id": 1612940, "author_profile": "https://Stackoverflow.com/users/1612940", "pm_score": 0, "selected": false, "text": "libmysql.dll apache\\bin" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
124,396
<p>Is it the case that the entire restful verb is under a single all encompassing transaction? That is to say, if I raise a Error in the validation or callbacks at any point in the handling of a UPDATE, DELETE, or CREATE operation, is every database operation that I may have performed in previous callbacks also rolled back? Succinctly, does raising a Error on any callback or validation make it such that no change at all occurs in the database for that verb action?</p>
[ { "answer_id": 124489, "author": "Michael Deardeuff", "author_id": 4931, "author_profile": "https://Stackoverflow.com/users/4931", "pm_score": 1, "selected": false, "text": "Student.transaction do\n Course.transaction do\n course.enroll(student)\n student.units += course.units\n end\nend\n" }, { "answer_id": 124494, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 2, "selected": false, "text": "def create\n Model.transaction do\n Model.create!(params[:model])\n Model.association.create!(params[:association])\n end\n rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid\n flash[:notice] = \"That record could not be saved.\"\n render :action => \"new\"\nend\n" }, { "answer_id": 124563, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": true, "text": "around_filter" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21317/" ]
124,405
<p>I am writing some code and trying to speed it up using SIMD intrinsics SSE2/3. My code is of such nature that I need to load some data into an XMM register and act on it many times. When I'm looking at the assembler code generated, it seems that GCC keeps flushing the data back to the memory, in order to reload something else in XMM0 and XMM1. I am compiling for x86-64 so I have 15 registers. Why is GCC using only two and what can I do to ask it to use more? Is there any way that I can "pin" some value in a register? I added the "register" keyword to my variable definition, but the generated assembly code is identical.</p>
[ { "answer_id": 72275425, "author": "Peter Cordes", "author_id": 224132, "author_profile": "https://Stackoverflow.com/users/224132", "pm_score": 0, "selected": false, "text": "int gcc -O3 -march=native -O0 register int foo; register __m128 bar;" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18308/" ]
124,411
<p>But here's an example:</p> <pre><code>Dim desiredType as Type if IsNumeric(desiredType) then ... </code></pre> <p><strong>EDIT:</strong> I only know the Type, not the Value as a string.</p> <p>Ok, so unfortunately I have to cycle through the TypeCode.</p> <p>But this is a nice way to do it:</p> <pre><code> if ((desiredType.IsArray)) return 0; switch (Type.GetTypeCode(desiredType)) { case 3: case 6: case 7: case 9: case 11: case 13: case 14: case 15: return 1; } ;return 0; </code></pre>
[ { "answer_id": 124443, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 5, "selected": false, "text": "Type.GetTypeCode() TypeCode typeCode = Type.GetTypeCode(desiredType);\n\nif (typeCode == TypeCode.Double || typeCode == TypeCode.Integer || ...)\n return true;\n" }, { "answer_id": 124477, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "if (Microsoft.VisualBasic.Information.IsNumeric(\"5\"))\n{\n //Do Something\n}\n public static bool Isumeric (object Expression)\n{\n bool f;\n ufloat64 a;\n long l;\n\n IConvertible iConvertible = null;\n if ( ((Expression is IConvertible)))\n {\n iConvertible = (IConvertible) Expression;\n }\n\n if (iConvertible == null)\n{\n if ( ((Expression is char[])))\n {\n Expression = new String ((char[]) Expression);\n goto IL_002d; // hopefully inserted by optimizer\n }\n return 0;\n}\nIL_002d:\nTypeCode typeCode = iConvertible.GetTypeCode ();\nif ((typeCode == 18) || (typeCode == 4))\n{\n string str = iConvertible.ToString (null);\n try\n {\n if ( (StringType.IsHexOrOctValue (str, l)))\n {\n f = true;\n return f;\n }\n}\ncatch (Exception )\n{\n f = false;\n return f;\n};\nreturn DoubleType.TryParse (str, a);\n}\nreturn Utils.IsNumericTypeCode (typeCode);\n}\n\ninternal static bool IsNumericType (Type typ)\n{\nbool f;\nTypeCode typeCode;\nif ( (typ.IsArray))\n{\n return 0;\n}\nswitch (Type.GetTypeCode (typ))\n{\ncase 3: \ncase 6: \ncase 7: \ncase 9: \ncase 11: \ncase 13: \ncase 14: \ncase 15: \n return 1;\n};\nreturn 0;\n}\n" }, { "answer_id": 124505, "author": "Mike Post", "author_id": 20788, "author_profile": "https://Stackoverflow.com/users/20788", "pm_score": -1, "selected": false, "text": "public bool IsInteger(Type t)\n{\n int i;\n return t.IsValueType && int.TryParse(t.ToString(), out i);\n}\n" }, { "answer_id": 2449131, "author": "Mike", "author_id": 294153, "author_profile": "https://Stackoverflow.com/users/294153", "pm_score": 2, "selected": false, "text": "''// Return true if a type is a numeric type.\nPrivate Function IsNumericType(ByVal this As Type) As Boolean\n ''// All the numeric types have bits 11xx set whereas non numeric do not.\n ''// That is if you include char type which is 4(decimal) = 100(binary).\n If this.IsArray Then Return False\n If (Type.GetTypeCode(this) And &HC) > 0 Then Return True\n Return False\nEnd Function\n" }, { "answer_id": 5182747, "author": "Suraj", "author_id": 356790, "author_profile": "https://Stackoverflow.com/users/356790", "pm_score": 8, "selected": true, "text": "/// <summary>\n/// Determines if a type is numeric. Nullable numeric types are considered numeric.\n/// </summary>\n/// <remarks>\n/// Boolean is not considered numeric.\n/// </remarks>\npublic static bool IsNumericType( Type type )\n{\n if (type == null)\n {\n return false;\n }\n\n switch (Type.GetTypeCode(type))\n {\n case TypeCode.Byte:\n case TypeCode.Decimal:\n case TypeCode.Double:\n case TypeCode.Int16:\n case TypeCode.Int32:\n case TypeCode.Int64:\n case TypeCode.SByte:\n case TypeCode.Single:\n case TypeCode.UInt16:\n case TypeCode.UInt32:\n case TypeCode.UInt64:\n return true;\n case TypeCode.Object:\n if ( type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))\n {\n return IsNumericType(Nullable.GetUnderlyingType(type));\n }\n return false;\n }\n return false;\n}\n\n\n\n/// <summary>\n/// Tests the IsNumericType method.\n/// </summary>\n[Fact]\npublic void IsNumericTypeTest()\n{\n // Non-numeric types\n Assert.False(TypeHelper.IsNumericType(null));\n Assert.False(TypeHelper.IsNumericType(typeof(object)));\n Assert.False(TypeHelper.IsNumericType(typeof(DBNull)));\n Assert.False(TypeHelper.IsNumericType(typeof(bool)));\n Assert.False(TypeHelper.IsNumericType(typeof(char)));\n Assert.False(TypeHelper.IsNumericType(typeof(DateTime)));\n Assert.False(TypeHelper.IsNumericType(typeof(string)));\n\n // Arrays of numeric and non-numeric types\n Assert.False(TypeHelper.IsNumericType(typeof(object[])));\n Assert.False(TypeHelper.IsNumericType(typeof(DBNull[])));\n Assert.False(TypeHelper.IsNumericType(typeof(bool[])));\n Assert.False(TypeHelper.IsNumericType(typeof(char[])));\n Assert.False(TypeHelper.IsNumericType(typeof(DateTime[])));\n Assert.False(TypeHelper.IsNumericType(typeof(string[])));\n Assert.False(TypeHelper.IsNumericType(typeof(byte[])));\n Assert.False(TypeHelper.IsNumericType(typeof(decimal[])));\n Assert.False(TypeHelper.IsNumericType(typeof(double[])));\n Assert.False(TypeHelper.IsNumericType(typeof(short[])));\n Assert.False(TypeHelper.IsNumericType(typeof(int[])));\n Assert.False(TypeHelper.IsNumericType(typeof(long[])));\n Assert.False(TypeHelper.IsNumericType(typeof(sbyte[])));\n Assert.False(TypeHelper.IsNumericType(typeof(float[])));\n Assert.False(TypeHelper.IsNumericType(typeof(ushort[])));\n Assert.False(TypeHelper.IsNumericType(typeof(uint[])));\n Assert.False(TypeHelper.IsNumericType(typeof(ulong[])));\n\n // numeric types\n Assert.True(TypeHelper.IsNumericType(typeof(byte)));\n Assert.True(TypeHelper.IsNumericType(typeof(decimal)));\n Assert.True(TypeHelper.IsNumericType(typeof(double)));\n Assert.True(TypeHelper.IsNumericType(typeof(short)));\n Assert.True(TypeHelper.IsNumericType(typeof(int)));\n Assert.True(TypeHelper.IsNumericType(typeof(long)));\n Assert.True(TypeHelper.IsNumericType(typeof(sbyte)));\n Assert.True(TypeHelper.IsNumericType(typeof(float)));\n Assert.True(TypeHelper.IsNumericType(typeof(ushort)));\n Assert.True(TypeHelper.IsNumericType(typeof(uint)));\n Assert.True(TypeHelper.IsNumericType(typeof(ulong)));\n\n // Nullable non-numeric types\n Assert.False(TypeHelper.IsNumericType(typeof(bool?)));\n Assert.False(TypeHelper.IsNumericType(typeof(char?)));\n Assert.False(TypeHelper.IsNumericType(typeof(DateTime?)));\n\n // Nullable numeric types\n Assert.True(TypeHelper.IsNumericType(typeof(byte?)));\n Assert.True(TypeHelper.IsNumericType(typeof(decimal?)));\n Assert.True(TypeHelper.IsNumericType(typeof(double?)));\n Assert.True(TypeHelper.IsNumericType(typeof(short?)));\n Assert.True(TypeHelper.IsNumericType(typeof(int?)));\n Assert.True(TypeHelper.IsNumericType(typeof(long?)));\n Assert.True(TypeHelper.IsNumericType(typeof(sbyte?)));\n Assert.True(TypeHelper.IsNumericType(typeof(float?)));\n Assert.True(TypeHelper.IsNumericType(typeof(ushort?)));\n Assert.True(TypeHelper.IsNumericType(typeof(uint?)));\n Assert.True(TypeHelper.IsNumericType(typeof(ulong?)));\n\n // Testing with GetType because of handling with non-numerics. See:\n // http://msdn.microsoft.com/en-us/library/ms366789.aspx\n\n // Using GetType - non-numeric\n Assert.False(TypeHelper.IsNumericType((new object()).GetType()));\n Assert.False(TypeHelper.IsNumericType(DBNull.Value.GetType()));\n Assert.False(TypeHelper.IsNumericType(true.GetType()));\n Assert.False(TypeHelper.IsNumericType('a'.GetType()));\n Assert.False(TypeHelper.IsNumericType((new DateTime(2009, 1, 1)).GetType()));\n Assert.False(TypeHelper.IsNumericType(string.Empty.GetType()));\n\n // Using GetType - numeric types\n // ReSharper disable RedundantCast\n Assert.True(TypeHelper.IsNumericType((new byte()).GetType()));\n Assert.True(TypeHelper.IsNumericType(43.2m.GetType()));\n Assert.True(TypeHelper.IsNumericType(43.2d.GetType()));\n Assert.True(TypeHelper.IsNumericType(((short)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((int)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((long)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((sbyte)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(2f.GetType()));\n Assert.True(TypeHelper.IsNumericType(((ushort)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((uint)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((ulong)2).GetType()));\n // ReSharper restore RedundantCast\n\n // Using GetType - nullable non-numeric types\n bool? nullableBool = true;\n Assert.False(TypeHelper.IsNumericType(nullableBool.GetType()));\n char? nullableChar = ' ';\n Assert.False(TypeHelper.IsNumericType(nullableChar.GetType()));\n DateTime? nullableDateTime = new DateTime(2009, 1, 1);\n Assert.False(TypeHelper.IsNumericType(nullableDateTime.GetType()));\n\n // Using GetType - nullable numeric types\n byte? nullableByte = 12;\n Assert.True(TypeHelper.IsNumericType(nullableByte.GetType()));\n decimal? nullableDecimal = 12.2m;\n Assert.True(TypeHelper.IsNumericType(nullableDecimal.GetType()));\n double? nullableDouble = 12.32;\n Assert.True(TypeHelper.IsNumericType(nullableDouble.GetType()));\n short? nullableInt16 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableInt16.GetType()));\n short? nullableInt32 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableInt32.GetType()));\n short? nullableInt64 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableInt64.GetType()));\n sbyte? nullableSByte = 12;\n Assert.True(TypeHelper.IsNumericType(nullableSByte.GetType()));\n float? nullableSingle = 3.2f;\n Assert.True(TypeHelper.IsNumericType(nullableSingle.GetType()));\n ushort? nullableUInt16 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableUInt16.GetType()));\n ushort? nullableUInt32 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableUInt32.GetType()));\n ushort? nullableUInt64 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableUInt64.GetType()));\n}\n" }, { "answer_id": 6090167, "author": "Mark Jones", "author_id": 703178, "author_profile": "https://Stackoverflow.com/users/703178", "pm_score": 3, "selected": false, "text": " /// <summary>\n /// Determines whether the supplied object is a .NET numeric system type\n /// </summary>\n /// <param name=\"val\">The object to test</param>\n /// <returns>true=Is numeric; false=Not numeric</returns>\n public static bool IsNumeric(ref object val)\n {\n if (val == null)\n return false;\n\n // Test for numeric type, returning true if match\n if \n (\n val is double || val is float || val is int || val is long || val is decimal || \n val is short || val is uint || val is ushort || val is ulong || val is byte || \n val is sbyte\n )\n return true;\n\n // Not numeric\n return false;\n }\n" }, { "answer_id": 21204229, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 2, "selected": false, "text": "System.Dynamic.Utils.TypeUtils System.Decimal Decimal System.Char internal static bool IsNumeric(Type type)\n{\n type = type.GetNonNullableType();\n if (!type.IsEnum)\n {\n switch (Type.GetTypeCode(type))\n {\n case TypeCode.Char:\n case TypeCode.SByte:\n case TypeCode.Byte:\n case TypeCode.Int16:\n case TypeCode.UInt16:\n case TypeCode.Int32:\n case TypeCode.UInt32:\n case TypeCode.Int64:\n case TypeCode.UInt64:\n case TypeCode.Single:\n case TypeCode.Double:\n return true;\n }\n }\n return false;\n}\n\n//where GetNonNullableType is defined as\n\ninternal static Type GetNonNullableType(this Type type)\n{\n if (type.IsNullableType())\n {\n return type.GetGenericArguments()[0];\n }\n return type;\n}\n\n//where IsNullableType is defined as\n\ninternal static bool IsNullableType(this Type type)\n{\n return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);\n}\n" }, { "answer_id": 31709198, "author": "Todd Menier", "author_id": 62600, "author_profile": "https://Stackoverflow.com/users/62600", "pm_score": 3, "selected": false, "text": "public static class ReflectionExtensions\n{\n public static bool IsNullable(this Type type) {\n return\n type != null &&\n type.IsGenericType && \n type.GetGenericTypeDefinition() == typeof(Nullable<>);\n }\n\n public static bool IsNumeric(this Type type) {\n if (type == null || type.IsEnum)\n return false;\n\n if (IsNullable(type))\n return IsNumeric(Nullable.GetUnderlyingType(type));\n\n switch (Type.GetTypeCode(type)) {\n case TypeCode.Byte:\n case TypeCode.Decimal:\n case TypeCode.Double:\n case TypeCode.Int16:\n case TypeCode.Int32:\n case TypeCode.Int64:\n case TypeCode.SByte:\n case TypeCode.Single:\n case TypeCode.UInt16:\n case TypeCode.UInt32:\n case TypeCode.UInt64:\n return true;\n default:\n return false;\n }\n }\n}\n" }, { "answer_id": 42654355, "author": "Josh T.", "author_id": 935365, "author_profile": "https://Stackoverflow.com/users/935365", "pm_score": 3, "selected": false, "text": "public static bool IsNumeric(Type type)\n{\n var t = Nullable.GetUnderlyingType(type) ?? type;\n return t.IsPrimitive || t == typeof(decimal);\n}\n char return (t.IsPrimitive || t == typeof(decimal)) && t != typeof(char);\n public static bool IsNumeric<T>(this T value)\n{\n var t = Nullable.GetUnderlyingType(value.GetType()) ?? value.GetType();\n return t.IsPrimitive || t == typeof(decimal);\n}\n" }, { "answer_id": 57396862, "author": "labilbe", "author_id": 1195872, "author_profile": "https://Stackoverflow.com/users/1195872", "pm_score": 1, "selected": false, "text": "typeof(decimal?).IsNumericType()\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
124,417
<p>I want to write a query like this:</p> <pre><code>SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice) FROM Order o </code></pre> <p>But this isn't how the <code>MAX</code> function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows. </p> <p>Does anyone know how to do it my way?</p>
[ { "answer_id": 124441, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 7, "selected": false, "text": "SELECT\n o.OrderId,\n CASE WHEN o.NegotiatedPrice > o.SuggestedPrice THEN o.NegotiatedPrice \n ELSE o.SuggestedPrice\n END\nFROM Order o\n" }, { "answer_id": 124448, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 2, "selected": false, "text": "select case when o.NegotiatedPrice > o.SuggestedPrice \nthen o.NegotiatedPrice\nelse o.SuggestedPrice\nend\n" }, { "answer_id": 124449, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "SELECT o.OrderID\nCASE WHEN o.NegotiatedPrice > o.SuggestedPrice THEN\n o.NegotiatedPrice\nELSE\n o.SuggestedPrice\nEND AS Price\n" }, { "answer_id": 124471, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "SELECT OrderId, MAX(Price) as Price FROM (\n SELECT o.OrderId, o.NegotiatedPrice as Price FROM Order o\n UNION ALL\n SELECT o.OrderId, o.SuggestedPrice as Price FROM Order o\n) as A\nGROUP BY OrderId\n" }, { "answer_id": 124474, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 9, "selected": true, "text": "User-Defined Function CASE UDF create function dbo.InlineMax(@val1 int, @val2 int)\nreturns int\nas\nbegin\n if @val1 > @val2\n return @val1\n return isnull(@val2,@val1)\nend\n SELECT o.OrderId, dbo.InlineMax(o.NegotiatedPrice, o.SuggestedPrice) \nFROM Order o\n" }, { "answer_id": 125112, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "SELECT o.OrderId, \n CASE WHEN ISNULL(o.NegotiatedPrice, o.SuggestedPrice) > ISNULL(o.SuggestedPrice, o.NegotiatedPrice)\n THEN ISNULL(o.NegotiatedPrice, o.SuggestedPrice)\n ELSE ISNULL(o.SuggestedPrice, o.NegotiatedPrice)\n END\nFROM Order o\n" }, { "answer_id": 126301, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 3, "selected": false, "text": "create function dbo.HigherArgumentOrNull(@val1 int, @val2 int)\nreturns int\nas\nbegin\n if @val1 >= @val2\n return @val1\n if @val1 < @val2\n return @val2\n\n return NULL\nend\n" }, { "answer_id": 196992, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "create table #t (a int, b int) \n\ninsert #t\nselect 1,2 union all \nselect 3,4 union all\nselect 5,2\n\n-- option 1 - A case statement\nselect case when a > b then a else b end\nfrom #t\n\n-- option 2 - A union statement \nselect a from #t where a >= b \nunion all \nselect b from #t where b > a \n\n-- option 3 - A udf\ncreate function dbo.GREATEST\n( \n @a as sql_variant,\n @b as sql_variant\n)\nreturns sql_variant\nbegin \n declare @max sql_variant \n if @a is null or @b is null return null\n if @b > @a return @b \n return @a \nend\n\n\nselect dbo.GREATEST(a,b)\nfrom #t\n create table #t (id int IDENTITY(1,1), a int, b int)\ninsert #t\nselect 1,2 union all\nselect 3,4 union all\nselect 5,2\n\nselect id, max(val)\nfrom #t\n unpivot (val for col in (a, b)) as unpvt\ngroup by id\n" }, { "answer_id": 293804, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 8, "selected": false, "text": "-- the following expression calculates ==> max(@val1, @val2)\nSELECT 0.5 * ((@val1 + @val2) + ABS(@val1 - @val2)) \n" }, { "answer_id": 2874486, "author": "jbeanky", "author_id": 313030, "author_profile": "https://Stackoverflow.com/users/313030", "pm_score": 5, "selected": false, "text": "DECLARE @MAX INT\n@MAX = (SELECT MAX(VALUE) \n FROM (SELECT 1 AS VALUE UNION \n SELECT 2 AS VALUE) AS T1)\n" }, { "answer_id": 2991347, "author": "andrewc", "author_id": 360618, "author_profile": "https://Stackoverflow.com/users/360618", "pm_score": 2, "selected": false, "text": "CREATE FUNCTION [dbo].[fnMax] (@p1 INT, @p2 INT)\nRETURNS INT\nAS BEGIN\n\n DECLARE @Result INT\n\n SET @p2 = COALESCE(@p2, @p1)\n\n SELECT\n @Result = (\n SELECT\n CASE WHEN @p1 > @p2 THEN @p1\n ELSE @p2\n END\n )\n\n RETURN @Result\n\nEND\n" }, { "answer_id": 3989370, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 4, "selected": false, "text": "MAX ;WITH [Order] AS\n(\nSELECT 1 AS OrderId, 100 AS NegotiatedPrice, 110 AS SuggestedPrice UNION ALL\nSELECT 2 AS OrderId, 1000 AS NegotiatedPrice, 50 AS SuggestedPrice\n)\nSELECT\n o.OrderId, \n (SELECT MAX(price)FROM \n (SELECT o.NegotiatedPrice AS price \n UNION ALL SELECT o.SuggestedPrice) d) \n AS MaxPrice \nFROM [Order] o\n" }, { "answer_id": 5045785, "author": "jsmink", "author_id": 623704, "author_profile": "https://Stackoverflow.com/users/623704", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION fnGreatestInt (@Int1 int, @Int2 int )\nRETURNS int\nAS\nBEGIN\n\n IF @Int1 >= ISNULL(@Int2,@Int1)\n RETURN @Int1\n ELSE\n RETURN @Int2\n\n RETURN NULL --Never Hit\n\nEND\n" }, { "answer_id": 9449247, "author": "MikeTeeVee", "author_id": 555798, "author_profile": "https://Stackoverflow.com/users/555798", "pm_score": 9, "selected": false, "text": "SELECT o.OrderId,\n (SELECT MAX(Price)\n FROM (VALUES (o.NegotiatedPrice),(o.SuggestedPrice)) AS AllPrices(Price))\nFROM Order o\n" }, { "answer_id": 21991746, "author": "Uri Abramson", "author_id": 1176547, "author_profile": "https://Stackoverflow.com/users/1176547", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION InlineMax\n(\n @p1 sql_variant,\n @p2 sql_variant\n) RETURNS sql_variant\nAS\nBEGIN\n RETURN CASE \n WHEN @p1 IS NULL AND @p2 IS NOT NULL THEN @p2 \n WHEN @p2 IS NULL AND @p1 IS NOT NULL THEN @p1\n WHEN @p1 > @p2 THEN @p1\n ELSE @p2 END\nEND;\n" }, { "answer_id": 24436112, "author": "SetFreeByTruth", "author_id": 1317792, "author_profile": "https://Stackoverflow.com/users/1317792", "pm_score": 3, "selected": false, "text": "IIF SELECT \n o.OrderId, \n IIF( ISNULL( o.NegotiatedPrice, 0 ) > ISNULL( o.SuggestedPrice, 0 ),\n o.NegotiatedPrice, \n o.SuggestedPrice \n )\nFROM \n Order o\n IIF NULL boolean_expression IIF false_value NULL" }, { "answer_id": 34133888, "author": "Steve Ford", "author_id": 1750324, "author_profile": "https://Stackoverflow.com/users/1750324", "pm_score": 1, "selected": false, "text": "SELECT \n o.OrderId, \n IIF( o.NegotiatedPrice >= o.SuggestedPrice,\n o.NegotiatedPrice, \n ISNULL(o.SuggestedPrice, o.NegiatedPrice) \n )\nFROM \n Order o\n" }, { "answer_id": 37934405, "author": "Xin", "author_id": 4468648, "author_profile": "https://Stackoverflow.com/users/4468648", "pm_score": 7, "selected": false, "text": "IIF(a>b, a, b)\n null a>b b" }, { "answer_id": 40221106, "author": "scradam", "author_id": 2208301, "author_profile": "https://Stackoverflow.com/users/2208301", "pm_score": 2, "selected": false, "text": "case\n when a >= b then a\n else isnull(b,a)\nend\n" }, { "answer_id": 43523581, "author": "mohghaderi", "author_id": 3174969, "author_profile": "https://Stackoverflow.com/users/3174969", "pm_score": 2, "selected": false, "text": "SELECT\n o.OrderId,\n CASE WHEN (o.NegotiatedPrice > o.SuggestedPrice OR o.SuggestedPrice IS NULL) \n THEN o.NegotiatedPrice \n ELSE o.SuggestedPrice\n END As MaxPrice\nFROM Order o\n" }, { "answer_id": 46074573, "author": "jahu", "author_id": 2123652, "author_profile": "https://Stackoverflow.com/users/2123652", "pm_score": 2, "selected": false, "text": "IIF(a IS NULL OR b IS NULL, ISNULL(a,b), IIF(a > b, a, b))\n IIF(a IS NULL OR b IS NULL, ISNULL(a,b), IIF(a < b, a, b))\n" }, { "answer_id": 46567873, "author": "error", "author_id": 4499525, "author_profile": "https://Stackoverflow.com/users/4499525", "pm_score": 2, "selected": false, "text": "select OrderId, (\n select max([Price]) from (\n select NegotiatedPrice [Price]\n union all\n select SuggestedPrice\n ) p\n) from [Order]\n" }, { "answer_id": 47255555, "author": "maxymoo", "author_id": 839957, "author_profile": "https://Stackoverflow.com/users/839957", "pm_score": -1, "selected": false, "text": "SELECT array_max(ARRAY[o.NegotiatedPrice, o.SuggestedPrice])\n" }, { "answer_id": 52296106, "author": "Tom Arleth", "author_id": 84996, "author_profile": "https://Stackoverflow.com/users/84996", "pm_score": 3, "selected": false, "text": "SELECT o.OrderId, \n--MAX(o.NegotiatedPrice, o.SuggestedPrice) \n(SELECT MAX(v) FROM (VALUES (o.NegotiatedPrice), (o.SuggestedPrice)) AS value(v)) as ChoosenPrice \nFROM Order o\n" }, { "answer_id": 54653461, "author": "ashraf mohammed", "author_id": 1719872, "author_profile": "https://Stackoverflow.com/users/1719872", "pm_score": 2, "selected": false, "text": " -- Simple way without \"functions\" or \"IF\" or \"CASE\"\n -- Query to select maximum value\n SELECT o.OrderId\n ,(SELECT MAX(v)\n FROM (VALUES (o.NegotiatedPrice), (o.SuggestedPrice)) AS value(v)) AS MaxValue\n FROM Order o;\n" }, { "answer_id": 54679193, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 1, "selected": false, "text": "SELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)\n DECLARE @A AS INT\nDECLARE @B AS INT\n\nSELECT @A = 2, @B = 1\nSELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)\n-- 2\n\nSELECT @A = 2, @B = 3\nSELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)\n-- 3\n\nSELECT @A = 2, @B = NULL\nSELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)\n-- 2 \n\nSELECT @A = NULL, @B = 1\nSELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)\n-- 1\n" }, { "answer_id": 54679549, "author": "LukStorms", "author_id": 4003419, "author_profile": "https://Stackoverflow.com/users/4003419", "pm_score": 4, "selected": false, "text": "IIF ISNULL COALESCE IIF(col1 >= col2, col1, ISNULL(col2, col1)) \n IIF(col1 >= col2, col1, COALESCE(col2, col1, 0)) \n -- use table variable for testing purposes\ndeclare @Order table \n(\n OrderId int primary key identity(1,1),\n NegotiatedPrice decimal(10,2),\n SuggestedPrice decimal(10,2)\n);\n\n-- Sample data\ninsert into @Order (NegotiatedPrice, SuggestedPrice) values\n(0, 1),\n(2, 1),\n(3, null),\n(null, 4);\n\n-- Query\nSELECT \n o.OrderId, o.NegotiatedPrice, o.SuggestedPrice, \n IIF(o.NegotiatedPrice >= o.SuggestedPrice, o.NegotiatedPrice, ISNULL(o.SuggestedPrice, o.NegotiatedPrice)) AS MaxPrice\nFROM @Order o\n OrderId NegotiatedPrice SuggestedPrice MaxPrice\n1 0,00 1,00 1,00\n2 2,00 1,00 2,00\n3 3,00 NULL 3,00\n4 NULL 4,00 4,00\n SELECT t.*\n, ca.[Maximum]\n, ca.[Minimum], ca.[Total], ca.[Average]\nFROM SomeTable t\nCROSS APPLY (\n SELECT \n MAX(v.col) AS [Maximum], \n MIN(v.col) AS [Minimum], \n SUM(v.col) AS [Total], \n AVG(v.col) AS [Average]\n FROM (VALUES (t.Col1), (t.Col2), (t.Col3), (t.Col4)) v(col)\n) ca\n" }, { "answer_id": 59072570, "author": "Desert Eagle", "author_id": 4197965, "author_profile": "https://Stackoverflow.com/users/4197965", "pm_score": -1, "selected": false, "text": "-- DROP FUNCTION IF EXISTS InlineMax;\nDELIMITER //\nCREATE FUNCTION InlineMax(val1 INT, val2 INT) RETURNS INT AS\nDECLARE\n val3 INT = 0;\nBEGIN\n IF val1 > val2 THEN\n RETURN val1;\n ELSE\n RETURN val2;\n END IF; \nEND //\nDELIMITER ;\n\nSELECT InlineMax(1,2) as test;\n" }, { "answer_id": 64327483, "author": "Chris Rogers", "author_id": 716476, "author_profile": "https://Stackoverflow.com/users/716476", "pm_score": 4, "selected": false, "text": "SELECT Max(v) FROM (VALUES (1), (2), (3)) AS value(v)\n" }, { "answer_id": 67096351, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 3, "selected": false, "text": "GREATEST ( expression1 [ ,...expressionN ] ) \n SELECT o.OrderId, GREATEST(o.NegotiatedPrice, o.SuggestedPrice)\nFROM Order o\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
124,453
<p>I know this is a subjective question, but why does Hibernate seem to be designed for short lived sessions? Generally in my apps I create DAOs to abstract my data layer, but since I can't predict how the entity objects are going to be used some of its collections are lazy loaded, or I should say fail to load once the session is closed.</p> <p>Why did they not design it so that it would automatically re-open the session, or have sessions always stay open?</p>
[ { "answer_id": 125021, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 2, "selected": false, "text": "lazy=false" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
124,455
<p>I've got a Lua program that seems to be slower than it ought to be. I suspect the issue is that I'm adding values to an associative array one at a time and the table has to allocate new memory each time. </p> <p>There did seem to be a table.setn function, but it fails under Lua 5.1.3:</p> <pre><code>stdin:1: 'setn' is obsolete stack traceback: [C]: in function 'setn' stdin:1: in main chunk [C]: ? </code></pre> <p>I gather from the Google searching I've done that this function was depreciated in Lua 5.1, but I can't find what (if anything) replaced the functionality.</p> <p>Do you know how to pre-size a table in Lua?</p> <p>Alternatively, is there some other way to avoid memory allocation when you add an object to a table?</p>
[ { "answer_id": 124536, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 3, "selected": false, "text": "void lua_createtable (lua_State *L, int narr, int nrec);\n" }, { "answer_id": 146902, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "static int new_sized_table( lua_State *L )\n{\n int asize = lua_tointeger( L, 1 );\n int hsize = lua_tointeger( L, 2 );\n lua_createtable( L, asize, hsize );\n return( 1 );\n}\n\n...\n\nlua_pushcfunction( L, new_sized_table );\nlua_setglobal( L, \"sized_table\" );\n array = function(size) return sized_table(size,0) end\n\na = array(10)\n lua.c" }, { "answer_id": 1487761, "author": "GhassanPL", "author_id": 1536, "author_profile": "https://Stackoverflow.com/users/1536", "pm_score": 1, "selected": false, "text": "local tab = { 0, 1, 2, 3, 4, 5, ... , n }\n n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
124,457
<p>I have limited experience with .net. My app throws an error this.dateTimeFormat is undefined which I tracked down to a known ajax bug. The workaround posted said to:</p> <p>"Register the following as a startup script:"</p> <pre><code>Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { if (!this._upperAbbrMonths) { this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); } return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); }; </code></pre> <p>So how do I do this? Do I add the script to the bottom of my aspx file?</p>
[ { "answer_id": 124470, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 4, "selected": true, "text": "string str = @\"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { \n if (!this._upperAbbrMonths) { \n this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);\n }\n return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));\n };\";\n\nif(!ClientScriptManager.IsStartupScriptRegistered(\"MyScript\"){\n ClientScriptManager.RegisterStartupScript(this.GetType(), \"MyScript\", str, true)\n}\n" }, { "answer_id": 365079, "author": "Cyril Gupta", "author_id": 33052, "author_profile": "https://Stackoverflow.com/users/33052", "pm_score": 2, "selected": false, "text": "string str = @\"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { \n if (!this._upperAbbrMonths) { \n this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);\n }\n return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));\n };\";\n\nClientScriptManager cs = Page.ClientScript;\nif(!cs.IsStartupScriptRegistered(\"MyScript\"))\n{\n cs.RegisterStartupScript(this.GetType(), \"MyScript\", str, true);\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
124,462
<p>Is there a way in PHP to make asynchronous HTTP calls? I don't care about the response, I just want to do something like <code>file_get_contents()</code>, but not wait for the request to finish before executing the rest of my code. This would be super useful for setting off "events" of a sort in my application, or triggering long processes.</p> <p>Any ideas?</p>
[ { "answer_id": 124557, "author": "Internet Friend", "author_id": 18037, "author_profile": "https://Stackoverflow.com/users/18037", "pm_score": 5, "selected": false, "text": "wget exec('bash -c \"wget -O (url goes here) > /dev/null 2>&1 &\"');\n" }, { "answer_id": 2258567, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 5, "selected": false, "text": "while(ob_get_level()) ob_end_clean();\nheader('Connection: close');\nignore_user_abort();\nob_start();\necho('Connection Closed');\n$size = ob_get_length();\nheader(\"Content-Length: $size\");\nob_end_flush();\nflush();\n" }, { "answer_id": 2437612, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 4, "selected": false, "text": "/**\n * Asynchronously execute/include a PHP file. Does not record the output of the file anywhere. \n *\n * @param string $filename file to execute, relative to calling script\n * @param string $options (optional) arguments to pass to file via the command line\n */ \nfunction asyncInclude($filename, $options = '') {\n exec(\"/path/to/php -f {$filename} {$options} >> /dev/null &\");\n}\n" }, { "answer_id": 2924987, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 6, "selected": true, "text": "function post_without_wait($url, $params)\n{\n foreach ($params as $key => &$val) {\n if (is_array($val)) $val = implode(',', $val);\n $post_params[] = $key.'='.urlencode($val);\n }\n $post_string = implode('&', $post_params);\n\n $parts=parse_url($url);\n\n $fp = fsockopen($parts['host'],\n isset($parts['port'])?$parts['port']:80,\n $errno, $errstr, 30);\n\n $out = \"POST \".$parts['path'].\" HTTP/1.1\\r\\n\";\n $out.= \"Host: \".$parts['host'].\"\\r\\n\";\n $out.= \"Content-Type: application/x-www-form-urlencoded\\r\\n\";\n $out.= \"Content-Length: \".strlen($post_string).\"\\r\\n\";\n $out.= \"Connection: Close\\r\\n\\r\\n\";\n if (isset($post_string)) $out.= $post_string;\n\n fwrite($fp, $out);\n fclose($fp);\n}\n" }, { "answer_id": 9199961, "author": "user1031143", "author_id": 1031143, "author_profile": "https://Stackoverflow.com/users/1031143", "pm_score": 2, "selected": false, "text": "<?\n$urls = array_fill(0, 100, 'http://google.com/blank.html');\n\nfunction execinbackground($cmd) { \n if (substr(php_uname(), 0, 7) == \"Windows\"){ \n pclose(popen(\"start /B \". $cmd, \"r\")); \n } \n else { \n exec($cmd . \" > /dev/null &\"); \n } \n} \nfwite(fopen(\"urls.txt\",\"w\"),implode(\"\\n\",$urls);\nexecinbackground(\"nodejs urlscript.js urls.txt\");\n// { do your work while get requests being executed.. }\n?>\n var https = require('https');\nvar url = require('url');\nvar http = require('http');\nvar fs = require('fs');\nvar dosya = process.argv[2];\nvar logdosya = 'log.txt';\nvar count=0;\nhttp.globalAgent.maxSockets = 300;\nhttps.globalAgent.maxSockets = 300;\n\nsetTimeout(timeout,100000); // maximum execution time (in ms)\n\nfunction trim(string) {\n return string.replace(/^\\s*|\\s*$/g, '')\n}\n\nfs.readFile(process.argv[2], 'utf8', function (err, data) {\n if (err) {\n throw err;\n }\n parcala(data);\n});\n\nfunction parcala(data) {\n var data = data.split(\"\\n\");\n count=''+data.length+'-'+data[1];\n data.forEach(function (d) {\n req(trim(d));\n });\n /*\n fs.unlink(dosya, function d() {\n console.log('<%s> file deleted', dosya);\n });\n */\n}\n\n\nfunction req(link) {\n var linkinfo = url.parse(link);\n if (linkinfo.protocol == 'https:') {\n var options = {\n host: linkinfo.host,\n port: 443,\n path: linkinfo.path,\n method: 'GET'\n };\nhttps.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});\n } else {\n var options = {\n host: linkinfo.host,\n port: 80,\n path: linkinfo.path,\n method: 'GET'\n }; \nhttp.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});\n }\n}\n\n\nprocess.on('exit', onExit);\n\nfunction onExit() {\n log();\n}\n\nfunction timeout()\n{\nconsole.log(\"i am too far gone\");process.exit();\n}\n\nfunction log() \n{\n var fd = fs.openSync(logdosya, 'a+');\n fs.writeSync(fd, dosya + '-'+count+'\\n');\n fs.closeSync(fd);\n}\n" }, { "answer_id": 22139782, "author": "Tony", "author_id": 2967960, "author_profile": "https://Stackoverflow.com/users/2967960", "pm_score": 3, "selected": false, "text": "$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);\n\n$client->on(\"connect\", function($cli) {\n $cli->send(\"hello world\\n\");\n});\n\n$client->on(\"receive\", function($cli, $data){\n echo \"Receive: $data\\n\";\n});\n\n$client->on(\"error\", function($cli){\n echo \"connect fail\\n\";\n});\n\n$client->on(\"close\", function($cli){\n echo \"close\\n\";\n});\n\n$client->connect('127.0.0.1', 9501, 0.5);\n" }, { "answer_id": 23643333, "author": "i am ArbZ", "author_id": 3339625, "author_profile": "https://Stackoverflow.com/users/3339625", "pm_score": 1, "selected": false, "text": " <?php\n parse_str(\"email=myemail@ehehehahaha.com&subject=this is just a test\");\n $_POST['email']=$email;\n $_POST['subject']=$subject;\n echo HTTP_POST(\"http://example.com/mail.php\",$_POST);***\n\n exit;\n ?>\n <?php\n /*********HTTP POST using FSOCKOPEN **************/\n // by ArbZ\n\nfunction HTTP_Post($URL,$data, $referrer=\"\") {\n\n // parsing the given URL\n $URL_Info=parse_url($URL);\n\n // Building referrer\n if($referrer==\"\") // if not given use this script as referrer\n $referrer=$_SERVER[\"SCRIPT_URI\"];\n\n // making string from $data\n foreach($data as $key=>$value)\n $values[]=\"$key=\".urlencode($value);\n $data_string=implode(\"&\",$values);\n\n // Find out which port is needed - if not given use standard (=80)\n if(!isset($URL_Info[\"port\"]))\n $URL_Info[\"port\"]=80;\n\n // building POST-request: HTTP_HEADERs\n $request.=\"POST \".$URL_Info[\"path\"].\" HTTP/1.1\\n\";\n $request.=\"Host: \".$URL_Info[\"host\"].\"\\n\";\n $request.=\"Referer: $referer\\n\";\n $request.=\"Content-type: application/x-www-form-urlencoded\\n\";\n $request.=\"Content-length: \".strlen($data_string).\"\\n\";\n $request.=\"Connection: close\\n\";\n $request.=\"\\n\";\n $request.=$data_string.\"\\n\";\n\n $fp = fsockopen($URL_Info[\"host\"],$URL_Info[\"port\"]);\n fputs($fp, $request);\n while(!feof($fp)) {\n $result .= fgets($fp, 128);\n }\n fclose($fp); //$eco = nl2br();\n\n\n function getTextBetweenTags($string, $tagname) {\n $pattern = \"/<$tagname ?.*>(.*)<\\/$tagname>/\";\n preg_match($pattern, $string, $matches);\n return $matches[1];\n }\n //STORE THE FETCHED CONTENTS to a VARIABLE, because its way better and fast...\n $str = $result;\n $txt = getTextBetweenTags($str, \"span\"); $eco = $txt; $result = explode(\"&\",$result);\n return $result[1];\n <span style=background-color:LightYellow;color:blue>\".trim($_GET['em']).\"</span>\n </pre> \"; \n}\n</pre>\n" }, { "answer_id": 24130860, "author": "AlexTR", "author_id": 3538145, "author_profile": "https://Stackoverflow.com/users/3538145", "pm_score": 1, "selected": false, "text": "<?php\n function curlGet($target){\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $target);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n $result = curl_exec ($ch);\n curl_close ($ch);\n return $result;\n }\n\n // Its the next 3 lines that do the magic\n ignore_user_abort(true);\n header(\"Connection: close\"); header(\"Content-Length: 0\");\n echo str_repeat(\"s\", 100000); flush();\n\n $i = $_GET['i'];\n if(!is_numeric($i)) $i = 1;\n if($i > 4) exit;\n if($i == 1) file_put_contents('storage.txt', '');\n\n file_put_contents('storage.txt', file_get_contents('storage.txt') . time() . \"\\n\");\n\n sleep(5);\n curlGet($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?i=' . ($i + 1));\n curlGet($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?i=' . ($i + 1));\n" }, { "answer_id": 28646425, "author": "RafaSashi", "author_id": 2456038, "author_profile": "https://Stackoverflow.com/users/2456038", "pm_score": 3, "selected": false, "text": "CURL CURLOPT_TIMEOUT_MS ignore_user_abort(true) function async_curl($background_process=''){\n\n //-------------get curl contents----------------\n\n $ch = curl_init($background_process);\n curl_setopt_array($ch, array(\n CURLOPT_HEADER => 0,\n CURLOPT_RETURNTRANSFER =>true,\n CURLOPT_NOSIGNAL => 1, //to timeout immediately if the value is < 1000 ms\n CURLOPT_TIMEOUT_MS => 50, //The maximum number of mseconds to allow cURL functions to execute\n CURLOPT_VERBOSE => 1,\n CURLOPT_HEADER => 1\n ));\n $out = curl_exec($ch);\n\n //-------------parse curl contents----------------\n\n //$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);\n //$header = substr($out, 0, $header_size);\n //$body = substr($out, $header_size);\n\n curl_close($ch);\n\n return true;\n}\n\nasync_curl('http://example.com/background_process_1.php');\n ignore_user_abort(true);\n\n//do something...\n" }, { "answer_id": 28765271, "author": "hanshenrik", "author_id": 1067003, "author_profile": "https://Stackoverflow.com/users/1067003", "pm_score": 2, "selected": false, "text": "class async_file_get_contents extends Thread{\n public $ret;\n public $url;\n public $finished;\n public function __construct($url) {\n $this->finished=false;\n $this->url=$url;\n }\n public function run() {\n $this->ret=file_get_contents($this->url);\n $this->finished=true;\n }\n}\n$afgc=new async_file_get_contents(\"http://example.org/file.ext\");\n" }, { "answer_id": 30314855, "author": "stil", "author_id": 1420356, "author_profile": "https://Stackoverflow.com/users/1420356", "pm_score": 4, "selected": false, "text": "<?php\n$request = new cURL\\Request('http://yahoo.com/');\n$request->getOptions()->set(CURLOPT_RETURNTRANSFER, true);\n\n// Specify function to be called when your request is complete\n$request->addListener('complete', function (cURL\\Event $event) {\n $response = $event->response;\n $httpCode = $response->getInfo(CURLINFO_HTTP_CODE);\n $html = $response->getContent();\n echo \"\\nDone.\\n\";\n});\n\n// Loop below will run as long as request is processed\n$timeStart = microtime(true);\nwhile ($request->socketPerform()) {\n printf(\"Running time: %dms \\r\", (microtime(true) - $timeStart)*1000);\n // Here you can do anything else, while your request is in progress\n}\n" }, { "answer_id": 40927321, "author": "Ruslan Osmanov", "author_id": 1646322, "author_profile": "https://Stackoverflow.com/users/1646322", "pm_score": 2, "selected": false, "text": "<?php\nclass MyHttpClient {\n /// @var EventBase\n protected $base;\n /// @var array Instances of EventHttpConnection\n protected $connections = [];\n\n public function __construct() {\n $this->base = new EventBase();\n }\n\n /**\n * Dispatches all pending requests (events)\n *\n * @return void\n */\n public function run() {\n $this->base->dispatch();\n }\n\n public function __destruct() {\n // Destroy connection objects explicitly, don't wait for GC.\n // Otherwise, EventBase may be free'd earlier.\n $this->connections = null;\n }\n\n /**\n * @brief Adds a pending HTTP request\n *\n * @param string $address Hostname, or IP\n * @param int $port Port number\n * @param array $headers Extra HTTP headers\n * @param int $cmd A EventHttpRequest::CMD_* constant\n * @param string $resource HTTP request resource, e.g. '/page?a=b&c=d'\n *\n * @return EventHttpRequest|false\n */\n public function addRequest($address, $port, array $headers,\n $cmd = EventHttpRequest::CMD_GET, $resource = '/')\n {\n $conn = new EventHttpConnection($this->base, null, $address, $port);\n $conn->setTimeout(5);\n\n $req = new EventHttpRequest([$this, '_requestHandler'], $this->base);\n\n foreach ($headers as $k => $v) {\n $req->addHeader($k, $v, EventHttpRequest::OUTPUT_HEADER);\n }\n $req->addHeader('Host', $address, EventHttpRequest::OUTPUT_HEADER);\n $req->addHeader('Connection', 'close', EventHttpRequest::OUTPUT_HEADER);\n if ($conn->makeRequest($req, $cmd, $resource)) {\n $this->connections []= $conn;\n return $req;\n }\n\n return false;\n }\n\n\n /**\n * @brief Handles an HTTP request\n *\n * @param EventHttpRequest $req\n * @param mixed $unused\n *\n * @return void\n */\n public function _requestHandler($req, $unused) {\n if (is_null($req)) {\n echo \"Timed out\\n\";\n } else {\n $response_code = $req->getResponseCode();\n\n if ($response_code == 0) {\n echo \"Connection refused\\n\";\n } elseif ($response_code != 200) {\n echo \"Unexpected response: $response_code\\n\";\n } else {\n echo \"Success: $response_code\\n\";\n $buf = $req->getInputBuffer();\n echo \"Body:\\n\";\n while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {\n echo $s, PHP_EOL;\n }\n }\n }\n }\n}\n\n\n$address = \"my-host.local\";\n$port = 80;\n$headers = [ 'User-Agent' => 'My-User-Agent/1.0', ];\n\n$client = new MyHttpClient();\n\n// Add pending requests\nfor ($i = 0; $i < 10; $i++) {\n $client->addRequest($address, $port, $headers,\n EventHttpRequest::CMD_GET, '/test.php?a=' . $i);\n}\n\n// Dispatch pending requests\n$client->run();\n <?php\necho 'GET: ', var_export($_GET, true), PHP_EOL;\necho 'User-Agent: ', $_SERVER['HTTP_USER_AGENT'] ?? '(none)', PHP_EOL;\n php http-client.php\n Success: 200\nBody:\nGET: array (\n 'a' => '1',\n)\nUser-Agent: My-User-Agent/1.0\nSuccess: 200\nBody:\nGET: array (\n 'a' => '0',\n)\nUser-Agent: My-User-Agent/1.0\nSuccess: 200\nBody:\nGET: array (\n 'a' => '3',\n)\n...\n EvIo <?php\nclass MyHttpRequest {\n /// @var MyHttpClient\n private $http_client;\n /// @var string\n private $address;\n /// @var string HTTP resource such as /page?get=param\n private $resource;\n /// @var string HTTP method such as GET, POST etc.\n private $method;\n /// @var int\n private $service_port;\n /// @var resource Socket\n private $socket;\n /// @var double Connection timeout in seconds.\n private $timeout = 10.;\n /// @var int Chunk size in bytes for socket_recv()\n private $chunk_size = 20;\n /// @var EvTimer\n private $timeout_watcher;\n /// @var EvIo\n private $write_watcher;\n /// @var EvIo\n private $read_watcher;\n /// @var EvTimer\n private $conn_watcher;\n /// @var string buffer for incoming data\n private $buffer;\n /// @var array errors reported by sockets extension in non-blocking mode.\n private static $e_nonblocking = [\n 11, // EAGAIN or EWOULDBLOCK\n 115, // EINPROGRESS\n ];\n\n /**\n * @param MyHttpClient $client\n * @param string $host Hostname, e.g. google.co.uk\n * @param string $resource HTTP resource, e.g. /page?a=b&c=d\n * @param string $method HTTP method: GET, HEAD, POST, PUT etc.\n * @throws RuntimeException\n */\n public function __construct(MyHttpClient $client, $host, $resource, $method) {\n $this->http_client = $client;\n $this->host = $host;\n $this->resource = $resource;\n $this->method = $method;\n\n // Get the port for the WWW service\n $this->service_port = getservbyname('www', 'tcp');\n\n // Get the IP address for the target host\n $this->address = gethostbyname($this->host);\n\n // Create a TCP/IP socket\n $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);\n if (!$this->socket) {\n throw new RuntimeException(\"socket_create() failed: reason: \" .\n socket_strerror(socket_last_error()));\n }\n\n // Set O_NONBLOCK flag\n socket_set_nonblock($this->socket);\n\n $this->conn_watcher = $this->http_client->getLoop()\n ->timer(0, 0., [$this, 'connect']);\n }\n\n public function __destruct() {\n $this->close();\n }\n\n private function freeWatcher(&$w) {\n if ($w) {\n $w->stop();\n $w = null;\n }\n }\n\n /**\n * Deallocates all resources of the request\n */\n private function close() {\n if ($this->socket) {\n socket_close($this->socket);\n $this->socket = null;\n }\n\n $this->freeWatcher($this->timeout_watcher);\n $this->freeWatcher($this->read_watcher);\n $this->freeWatcher($this->write_watcher);\n $this->freeWatcher($this->conn_watcher);\n }\n\n /**\n * Initializes a connection on socket\n * @return bool\n */\n public function connect() {\n $loop = $this->http_client->getLoop();\n\n $this->timeout_watcher = $loop->timer($this->timeout, 0., [$this, '_onTimeout']);\n $this->write_watcher = $loop->io($this->socket, Ev::WRITE, [$this, '_onWritable']);\n\n return socket_connect($this->socket, $this->address, $this->service_port);\n }\n\n /**\n * Callback for timeout (EvTimer) watcher\n */\n public function _onTimeout(EvTimer $w) {\n $w->stop();\n $this->close();\n }\n\n /**\n * Callback which is called when the socket becomes wriable\n */\n public function _onWritable(EvIo $w) {\n $this->timeout_watcher->stop();\n $w->stop();\n\n $in = implode(\"\\r\\n\", [\n \"{$this->method} {$this->resource} HTTP/1.1\",\n \"Host: {$this->host}\",\n 'Connection: Close',\n ]) . \"\\r\\n\\r\\n\";\n\n if (!socket_write($this->socket, $in, strlen($in))) {\n trigger_error(\"Failed writing $in to socket\", E_USER_ERROR);\n return;\n }\n\n $loop = $this->http_client->getLoop();\n $this->read_watcher = $loop->io($this->socket,\n Ev::READ, [$this, '_onReadable']);\n\n // Continue running the loop\n $loop->run();\n }\n\n /**\n * Callback which is called when the socket becomes readable\n */\n public function _onReadable(EvIo $w) {\n // recv() 20 bytes in non-blocking mode\n $ret = socket_recv($this->socket, $out, 20, MSG_DONTWAIT);\n\n if ($ret) {\n // Still have data to read. Append the read chunk to the buffer.\n $this->buffer .= $out;\n } elseif ($ret === 0) {\n // All is read\n printf(\"\\n<<<<\\n%s\\n>>>>\", rtrim($this->buffer));\n fflush(STDOUT);\n $w->stop();\n $this->close();\n return;\n }\n\n // Caught EINPROGRESS, EAGAIN, or EWOULDBLOCK\n if (in_array(socket_last_error(), static::$e_nonblocking)) {\n return;\n }\n\n $w->stop();\n $this->close();\n }\n}\n\n/////////////////////////////////////\nclass MyHttpClient {\n /// @var array Instances of MyHttpRequest\n private $requests = [];\n /// @var EvLoop\n private $loop;\n\n public function __construct() {\n // Each HTTP client runs its own event loop\n $this->loop = new EvLoop();\n }\n\n public function __destruct() {\n $this->loop->stop();\n }\n\n /**\n * @return EvLoop\n */\n public function getLoop() {\n return $this->loop;\n }\n\n /**\n * Adds a pending request\n */\n public function addRequest(MyHttpRequest $r) {\n $this->requests []= $r;\n }\n\n /**\n * Dispatches all pending requests\n */\n public function run() {\n $this->loop->run();\n }\n}\n\n\n/////////////////////////////////////\n// Usage\n$client = new MyHttpClient();\nforeach (range(1, 10) as $i) {\n $client->addRequest(new MyHttpRequest($client, 'my-host.local', '/test.php?a=' . $i, 'GET'));\n}\n$client->run();\n http://my-host.local/test.php $_GET <?php\necho 'GET: ', var_export($_GET, true), PHP_EOL;\n php http-client.php <<<<\nHTTP/1.1 200 OK\nServer: nginx/1.10.1\nDate: Fri, 02 Dec 2016 12:39:54 GMT\nContent-Type: text/html; charset=UTF-8\nTransfer-Encoding: chunked\nConnection: close\nX-Powered-By: PHP/7.0.13-pl0-gentoo\n\n1d\nGET: array (\n 'a' => '3',\n)\n\n0\n>>>>\n<<<<\nHTTP/1.1 200 OK\nServer: nginx/1.10.1\nDate: Fri, 02 Dec 2016 12:39:54 GMT\nContent-Type: text/html; charset=UTF-8\nTransfer-Encoding: chunked\nConnection: close\nX-Powered-By: PHP/7.0.13-pl0-gentoo\n\n1d\nGET: array (\n 'a' => '2',\n)\n\n0\n>>>>\n...\n EINPROGRESS EAGAIN EWOULDBLOCK errno error_reporting(E_ERROR);\n file_get_contents()" }, { "answer_id": 51239043, "author": "Simon East", "author_id": 195835, "author_profile": "https://Stackoverflow.com/users/195835", "pm_score": 4, "selected": false, "text": "use GuzzleHttp\\Client;\nuse GuzzleHttp\\Promise;\n\n$client = new Client(['base_uri' => 'http://httpbin.org/']);\n\n// Initiate each request but do not block\n$promises = [\n 'image' => $client->getAsync('/image'),\n 'png' => $client->getAsync('/image/png'),\n 'jpeg' => $client->getAsync('/image/jpeg'),\n 'webp' => $client->getAsync('/image/webp')\n];\n\n// Wait on all of the requests to complete. Throws a ConnectException\n// if any of the requests fail\n$results = Promise\\unwrap($promises);\n\n// Wait for the requests to complete, even if some of them fail\n$results = Promise\\settle($promises)->wait();\n\n// You can access each result using the key provided to the unwrap\n// function.\necho $results['image']['value']->getHeader('Content-Length')[0]\necho $results['png']['value']->getHeader('Content-Length')[0]\n" }, { "answer_id": 53962684, "author": "Sergey Shuchkin", "author_id": 594867, "author_profile": "https://Stackoverflow.com/users/594867", "pm_score": 1, "selected": false, "text": "$ composer require shuchkin/react-http-client\n // get.php\n$loop = \\React\\EventLoop\\Factory::create();\n\n$http = new \\Shuchkin\\ReactHTTP\\Client( $loop );\n\n$http->get( 'https://tools.ietf.org/rfc/rfc2068.txt' )->then(\n function( $content ) {\n echo $content;\n },\n function ( \\Exception $ex ) {\n echo 'HTTP error '.$ex->getCode().' '.$ex->getMessage();\n }\n);\n\n$loop->run();\n $ php get.php\n" }, { "answer_id": 57717357, "author": "Vedmant", "author_id": 1753349, "author_profile": "https://Stackoverflow.com/users/1753349", "pm_score": 2, "selected": false, "text": "<?php\n\nuse function Amp\\ParallelFunctions\\parallelMap;\nuse function Amp\\Promise\\wait;\n\n$responses = wait(parallelMap([\n 'https://google.com/',\n 'https://github.com/',\n 'https://stackoverflow.com/',\n], function ($url) {\n return file_get_contents($url);\n}));\n /**\n * Get domains with all needed data\n */\n protected function getDomainsWithdata(): Collection\n {\n return $this->opensrs->getDomains()->parallelMap(function ($domain) {\n $contact = $this->opensrs->getDomainContact($domain);\n $contact['domain'] = $domain;\n return $contact;\n }, 10);\n }\n" }, { "answer_id": 61295170, "author": "nacholibre", "author_id": 1047510, "author_profile": "https://Stackoverflow.com/users/1047510", "pm_score": 1, "selected": false, "text": "use Symfony\\Component\\HttpClient\\HttpClient;\n\n$client = HttpClient::create();\n$response1 = $client->request('GET', 'https://website1');\n$response2 = $client->request('GET', 'https://website1');\n$response3 = $client->request('GET', 'https://website1');\n//these 3 calls with return immediately\n//but the requests will fire to the website1 webserver\n\n$response1->getContent(); //this will block until content is fetched\n$response2->getContent(); //same \n$response3->getContent(); //same\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10680/" ]
124,492
<p>I need a short code snippet to get a directory listing from an HTTP server.</p> <p>Thanks</p>
[ { "answer_id": 124498, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "HtmlDocument doc = new HtmlDocument();\ndoc.Load(strURL);\nforeach(HtmlNode link in doc.DocumentElement.SelectNodes(\"//a@href\")\n{\nHtmlAttribute att = link\"href\";\n//do something with att.Value;\n}\n" }, { "answer_id": 124522, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": true, "text": "namespace Example\n{\n using System;\n using System.Net;\n using System.IO;\n using System.Text.RegularExpressions;\n\n public class MyExample\n {\n public static string GetDirectoryListingRegexForUrl(string url)\n {\n if (url.Equals(\"http://www.ibiblio.org/pub/\"))\n {\n return \"<a href=\\\".*\\\">(?<name>.*)</a>\";\n }\n throw new NotSupportedException();\n }\n public static void Main(String[] args)\n {\n string url = \"http://www.ibiblio.org/pub/\";\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n {\n string html = reader.ReadToEnd();\n Regex regex = new Regex(GetDirectoryListingRegexForUrl(url));\n MatchCollection matches = regex.Matches(html);\n if (matches.Count > 0)\n {\n foreach (Match match in matches)\n {\n if (match.Success)\n {\n Console.WriteLine(match.Groups[\"name\"]);\n }\n }\n }\n }\n }\n\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 15031372, "author": "Seyed", "author_id": 2100595, "author_profile": "https://Stackoverflow.com/users/2100595", "pm_score": 2, "selected": false, "text": "<AHREF=\\\\\"\\S+\\\">(?<name>\\S+)</A>\n <AHREF=\\\\\"\\S+\\\">(?<name>\\S+)</A>" }, { "answer_id": 19304169, "author": "Avinash patil", "author_id": 2413635, "author_profile": "https://Stackoverflow.com/users/2413635", "pm_score": 3, "selected": false, "text": "public static class GetallFilesFromHttp\n{\n public static string GetDirectoryListingRegexForUrl(string url)\n {\n if (url.Equals(\"http://ServerDirPath/\"))\n {\n return \"\\\\\\\"([^\\\"]*)\\\\\\\"\"; \n }\n throw new NotSupportedException();\n }\n public static void ListDiractory()\n {\n string url = \"http://ServerDirPath/\";\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n {\n string html = reader.ReadToEnd();\n\n Regex regex = new Regex(GetDirectoryListingRegexForUrl(url));\n MatchCollection matches = regex.Matches(html);\n if (matches.Count > 0)\n {\n foreach (Match match in matches)\n {\n if (match.Success)\n {\n Console.WriteLine(match.ToString());\n }\n }\n }\n }\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 26414275, "author": "Jake Drew", "author_id": 1533306, "author_profile": "https://Stackoverflow.com/users/1533306", "pm_score": 2, "selected": false, "text": "public static string[] GetFiles(string url)\n{\n List<string> files = new List<string>(500);\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n {\n string html = reader.ReadToEnd();\n\n Regex regex = new Regex(\"<a href=\\\".*\\\">(?<name>.*)</a>\");\n MatchCollection matches = regex.Matches(html);\n\n if (matches.Count > 0)\n {\n foreach (Match match in matches)\n {\n if (match.Success)\n {\n string[] matchData = match.Groups[0].ToString().Split('\\\"');\n files.Add(matchData[1]);\n }\n }\n }\n }\n }\n return files.ToArray();\n}\n public static string[] getFtpFolderItems(string ftpURL)\n{\n FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL);\n request.Method = WebRequestMethods.Ftp.ListDirectory;\n\n //You could add Credentials, if needed \n //request.Credentials = new NetworkCredential(\"anonymous\", \"password\");\n\n FtpWebResponse response = (FtpWebResponse)request.GetResponse();\n\n Stream responseStream = response.GetResponseStream();\n StreamReader reader = new StreamReader(responseStream);\n\n return reader.ReadToEnd().Split(\"\\r\\n\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
124,585
<p>This question is specifically related to overriding the equals() method for objects with a large number of fields. First off, let me say that this large object cannot be broken down into multiple components without violating OO principles, so telling me "no class should have more than x fields" won't help. </p> <p>Moving on, the problem came to fruition when I forgot to check one of the fields for equality. Therefore, my equals method was incorrect. Then I thought to use reflection:</p> <pre><code>--code removed because it was too distracting-- </code></pre> <p>The purpose of this post isn't necessarily to refactor the code (this isn't even the code I am using), but instead to get input on whether or not this is a good idea. </p> <p><strong>Pros:</strong></p> <ul> <li>If a new field is added, it is automatically included<br> </li> <li>The method is much more terse than 30 if statements</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>If a new field is added, it is automatically included, sometimes this is undesirable</li> <li>Performance: This has to be slower, I don't feel the need to break out a profiler</li> <li>Whitelisting certain fields to ignore in the comparison is a little ugly<br></li> </ul> <p>Any thoughts?</p>
[ { "answer_id": 124598, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 5, "selected": true, "text": "equals() equals() hashCode()" }, { "answer_id": 124640, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "this obj obj if ( ! obj instanceof myClass ) return false; obj this null obj if ( obj == null ) return false; null null Field.get(obj) == Field.get(this) if ( Field.get(obj) == null || Field.get(this) == null ) return false; null equals() foundMismatch [HashCodeBuilder][1] [EqualsBuilder][2]" }, { "answer_id": 126654, "author": "daveb", "author_id": 11858, "author_profile": "https://Stackoverflow.com/users/11858", "pm_score": 3, "selected": false, "text": " public boolean equals(Object obj) {\n return EqualsBuilder.reflectionEquals(this, obj);\n }\n" }, { "answer_id": 173982, "author": "Wouter Lievens", "author_id": 7927, "author_profile": "https://Stackoverflow.com/users/7927", "pm_score": 1, "selected": false, "text": "@IgnoreEquals\nString fieldThatShouldNotBeCompared;\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402777/" ]
124,604
<p>Coming from a Perl 5 background, what are the advantages of moving to Perl 6 or Python?</p>
[ { "answer_id": 4294670, "author": "user502515", "author_id": 502515, "author_profile": "https://Stackoverflow.com/users/502515", "pm_score": 2, "selected": false, "text": "s/whatever/somethingelse/e" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
124,606
<p>I have a function that I use called sqlf(), it emulates prepared statements. For instance I can do things like:</p> <pre> $sql = sqlf("SELECT * FROM Users WHERE name= :1 AND email= :2",'Big "John"','bj@example.com') ; </pre> <p>For various reasons, I cannot use prepared statements, but I would like to emulate them. The problem that I run into is with queries like</p> <pre> $sql = sqlf("SELECT * FROM Users WHERE id IN (:1)",array(1,2,3) ); </pre> <p>My code works, but it fails with empty arrays, e.g. the following throws a mysql error:</p> <pre> SELECT * FROM Users WHERE id IN (); </pre> <p>Does anyone have any suggestions? How should I translate and empty array into sql that can be injected into an IN clause? Substituting NULL will not work. </p>
[ { "answer_id": 124635, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "SELECT * FROM Users WHERE id IN ();\nSELECT * FROM Users WHERE a = 7 AND id IN ();\nSELECT * FROM Users WHERE id IN () OR a = 9;\n SELECT * FROM Users;\nSELECT * FROM Users WHERE a = 7;\nSELECT * FROM Users WHERE a = 9;\n" }, { "answer_id": 124645, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "sqlf() \"m,znmzcb~~1\"" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20512/" ]
124,615
<p>Lets say I have a class that stores user information complete with getters and setters, and it is populated with data from an XML file. How would I iterate over all of the instances of that class like you would do with java beans and tag libraries?</p>
[ { "answer_id": 124783, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 0, "selected": false, "text": "List<YourClass> myObjects = SomeMagicMethodThatGetsAllInstancesOfThatClassAndAddsThemtoTheCollection();\nforeach (YourClass instance in myObjects)\n{\nResponse.Write(instance.PropertyName.ToString();\n}\n" }, { "answer_id": 124825, "author": "brock.holum", "author_id": 15860, "author_profile": "https://Stackoverflow.com/users/15860", "pm_score": 1, "selected": false, "text": "[snip]\n<body>\n <form id=\"form1\" runat=\"server\">\n <% Somethings.ForEach(s => { %>\n <h1><%=s.Name %></h1>\n <h2><%=s.Id %></h2>\n <% }); %>\n </form>\n</body>\n</html>\n [snip]\npublic partial class _Default : System.Web.UI.Page\n {\n protected List<Something> Somethings { get; private set; }\n protected void Page_Load(object sender, EventArgs e)\n {\n Somethings = GetSomethings(); // Or whatever populates the collection\n\n }\n[snip]\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066/" ]
124,630
<p>I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:</p> <pre><code>public Image getImageFromArray(int[] pixels, int width, int height) { MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width); Toolkit tk = Toolkit.getDefaultToolkit(); return tk.createImage(mis); } </code></pre> <p><em>Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?</em></p> <p>Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.</p>
[ { "answer_id": 124957, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 2, "selected": false, "text": "// Capture whole screen\nRectangle region = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());\nBufferedImage capturedImage = new Robot().createScreenCapture(region);\n\n// Save as PNG\nFile imageFile = new File(\"capturedImage.png\");\nImageIO.write(capturedImage, \"png\", imageFile);\n" }, { "answer_id": 125013, "author": "Brendan Cashman", "author_id": 5814, "author_profile": "https://Stackoverflow.com/users/5814", "pm_score": 6, "selected": true, "text": "public static Image getImageFromArray(int[] pixels, int width, int height) {\n BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n WritableRaster raster = (WritableRaster) image.getData();\n raster.setPixels(0,0,width,height,pixels);\n return image;\n }\n getImageFromArray BufferedImage.TYPE_INT_ARGB" }, { "answer_id": 804635, "author": "mdm", "author_id": 25318, "author_profile": "https://Stackoverflow.com/users/25318", "pm_score": 3, "selected": false, "text": "ArrayIndexOutOfBoundsException BufferedImage TYPE_INT_ARGB setRGB(...) BufferedImage" }, { "answer_id": 4884818, "author": "beemaster", "author_id": 524844, "author_profile": "https://Stackoverflow.com/users/524844", "pm_score": 2, "selected": false, "text": " // Получаем картинку из массива.\n int[] pixels = new int[width*height];\n // Рисуем диагональ.\n for (int j = 0; j < height; j++) {\n for (int i = 0; i < width; i++) {\n if (i == j) {\n pixels[j*width + i] = Color.RED.getRGB();\n }\n else {\n pixels[j*width + i] = Color.BLUE.getRGB();\n //pixels[j*width + i] = 0x00000000;\n }\n }\n }\n\nBufferedImage pixelImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); \n pixelImage.setRGB(0, 0, width, height, pixels, 0, width);\n" }, { "answer_id": 16926586, "author": "Harald K", "author_id": 1428606, "author_profile": "https://Stackoverflow.com/users/1428606", "pm_score": 0, "selected": false, "text": "BufferedImage image = new BufferedImageFactory(image).getBufferedImage();\n PixelGrabber" }, { "answer_id": 37948442, "author": "Raul H", "author_id": 3163732, "author_profile": "https://Stackoverflow.com/users/3163732", "pm_score": 0, "selected": false, "text": "public static Image getImageFromArray(int[] pixels, int width, int height) {\n BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n WritableRaster raster = (WritableRaster) image.getData();\n raster.setPixels(0,0,width,height,pixels);\n image.setData(raster); \n return image;\n }\n JFrame frame = new JFrame();\n frame.getContentPane().setLayout(new FlowLayout());\n frame.getContentPane().add(new JLabel(new ImageIcon(image)));\n frame.pack();\n frame.setVisible(true);\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
124,638
<p>I found an article on getting active tcp/udp connections on a machine.</p> <p><a href="http://www.codeproject.com/KB/IP/iphlpapi.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/IP/iphlpapi.aspx</a></p> <p>My issue however is I need to be able to determine active connections remotely - to see if a particular port is running or listening without tampering with the machine.</p> <p>Is this possible?</p> <p>Doesn't seem like it natively, otherwise it could pose a security issue. The alternative would be to query a remoting service which could then make the necessary calls on the local machine.</p> <p>Any thoughts?</p>
[ { "answer_id": 124641, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 2, "selected": false, "text": "telnet google.com 80\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]