qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
352,474
<p>I have an interface A, for which I have to supply a few different implementations. However, those implementations share some helper methods, so I moved those methods to an abstract base class.</p> <pre><code>Interface A { void doX(); } abstract Class B implements A { protected void commonY() { // ... } @Override public abstract void doX(); } Class C extends B { @Override public void doX() { // ... } } Class D extends B { @Override public void doX() { // ... } } </code></pre> <p>My code works as expected, but I have a few questions:</p> <ul> <li><p>Should I declare the abstract Method doX() in Class B? Why (not)?</p></li> <li><p>Should I also explicitly declare "implements A" on Class C and D? Why (not)?</p></li> </ul>
[ { "answer_id": 352486, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 0, "selected": false, "text": "doX() B implements A C D doX() B implements A implements A C D C D A implements" }, { "answer_id": 352488, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 4, "selected": true, "text": "Interface A {\n void doX();\n}\n\nabstract Class B {\n protected void commonY() {\n // ...\n }\n}\n\nClass C extends B implements A{\n\n public void doX() {\n // ...\n }\n}\n\nClass D extends B implements A{\n\n public void doX() {\n // ...\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29549/" ]
352,478
<p>Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?</p> <p>For example:</p> <pre><code>asimpletest -&gt; Asimpletest aSimpleTest -&gt; ASimpleTest </code></pre> <p>I would like to be able to do all string lengths as well.</p>
[ { "answer_id": 352494, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 3, "selected": false, "text": "s = s[0].upper() + s[1:]\n s=\"\"" }, { "answer_id": 352513, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 7, "selected": true, "text": "s = s[:1].upper() + s[1:]\n" }, { "answer_id": 14162785, "author": "skyler", "author_id": 300368, "author_profile": "https://Stackoverflow.com/users/300368", "pm_score": 4, "selected": false, "text": "your_string.title() \"banana\".title() -> Banana" }, { "answer_id": 15279448, "author": "rbp", "author_id": 403423, "author_profile": "https://Stackoverflow.com/users/403423", "pm_score": 3, "selected": false, "text": "def capitalize(str): \n return str[:1].upper() + str[1:].lower().......\n" }, { "answer_id": 16212385, "author": "tigeronk2", "author_id": 1469086, "author_profile": "https://Stackoverflow.com/users/1469086", "pm_score": 7, "selected": false, "text": ">>> b = \"my name\"\n>>> b.capitalize()\n'My name'\n>>> b.title()\n'My Name'\n" }, { "answer_id": 32772576, "author": "saar", "author_id": 5374227, "author_profile": "https://Stackoverflow.com/users/5374227", "pm_score": -1, "selected": false, "text": "str = str[:].upper()\n" }, { "answer_id": 38990813, "author": "faiz", "author_id": 5727260, "author_profile": "https://Stackoverflow.com/users/5727260", "pm_score": 2, "selected": false, "text": "a=\"asimpletest\"\nprint a.capitalize()\n print a.upper()\n" }, { "answer_id": 47247321, "author": "Eric", "author_id": 2681088, "author_profile": "https://Stackoverflow.com/users/2681088", "pm_score": 2, "selected": false, "text": "In [1]: x = \"hello\"\n\nIn [2]: x.capitalize()\nOut[2]: 'Hello'\n" }, { "answer_id": 50083474, "author": "Saurabh", "author_id": 2078672, "author_profile": "https://Stackoverflow.com/users/2078672", "pm_score": 2, "selected": false, "text": "s=\"gf12 23sadasd\"\nprint( string.capwords(s, ' ') )\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ]
352,479
<p>When I compile my application under Delphi 2006 I get the following warning [Pascal Warning]- W1002 Symbol 'FileSetDate' is specific to a platform</p> <p>What must I do to suppress this warning?</p> <p>The code </p> <pre><code>MyLastError:= FileSetDate( Files[ i ].Handle, DateTimeToFileDate( arcDate ) ); </code></pre>
[ { "answer_id": 352498, "author": "Daniel Rikowski", "author_id": 23368, "author_profile": "https://Stackoverflow.com/users/23368", "pm_score": 5, "selected": false, "text": "{$WARN SYMBOL_PLATFORM OFF}\n// Your code\n{$WARN SYMBOL_PLATFORM ON}\n {$WARNINGS OFF}\n// Your code\n{$WARNINGS ON}\n FileSetDate" }, { "answer_id": 352584, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 6, "selected": true, "text": "function FileSetDate(const FileName: string; Age: Integer): Integer; overload;\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ]
352,503
<p>Master table contains ID and PersonName.<br> Course table contains ID, CourseName.<br> Detail table contains ID, MasterID, CourseID, StartDate,EndDate</p> <p>I want to create report that shows list of persons (PersonName) and the only last course they took (so every person is listed only once):</p> <p>PersonName - CourseName - StartDate - EndDate</p>
[ { "answer_id": 352526, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": true, "text": "select m.PersonName, c.CourseName\nfrom Master m\njoin Detail d on d.MasterID = m.ID\njoin Course c on c.ID = d.CourseID\nwhere d.StartDate = (select max(d2.StartDate)\n from Detail d2\n where d2.MasterID = m.ID\n )\n" }, { "answer_id": 352562, "author": "Samiksha", "author_id": 29515, "author_profile": "https://Stackoverflow.com/users/29515", "pm_score": 0, "selected": false, "text": " Select personname,coursename from details \n inner join course on course.id = details.courseid \n inner join master on master.id = details.masterid\n inner join (select max(startdate) , courseid,masterid \n from details group by masterid,courseid ) as tb1\n on tb1.courseid = details.courseid and tb1.masterid = details.masterid\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11744/" ]
352,527
<p>I am adventuring into some AOP and it seems with .NET PostSharp is the way to go. </p> <p>I want to do some simple logging to the db when an exception occurs. However I am finding it difficult to find any real solid examples of using PostSharp beyond the basics. I tried the following:</p> <pre><code>[Serializable] public sealed class LogExceptionAttribute : ExceptionHandlerAspect { public override void OnException(MethodExecutionEventArgs eventArgs) { //do some logging here } } </code></pre> <p>And then attaching a <code>[LogException]</code> attribute to a method</p> <p>But I get a compile error:</p> <pre><code>Error 7 The type "CoDrivrBeta1.Classes.LogExceptionAttribute" or one of its ancestor should be decorated by an instance of MulticastAttributeUsageAttribute. C:\work\CoDrivrBeta1\CoDrivrBeta1\EXEC CoDrivrBeta1 </code></pre> <p>I have to confess I am very new to this, but it seems like an interesting concept, I think i just need to be pointed in the right direction</p>
[ { "answer_id": 353889, "author": "Ryan Cook", "author_id": 43029, "author_profile": "https://Stackoverflow.com/users/43029", "pm_score": 3, "selected": true, "text": "OnExceptionAspect [Serializable]\npublic sealed class LogExceptionAttribute : OnExceptionAspect\n{\n public override void OnException(MethodExecutionEventArgs eventArgs)\n {\n //do some logging here\n }\n}\n [Serializable]\n[MulticastAttributeUsage(... Add Appropriate MulticastTargets ...)]\npublic sealed class LogExceptionAttribute : ExceptionHandlerAspect\n{\n public override void OnException(MethodExecutionEventArgs eventArgs)\n {\n //do some logging here\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3193/" ]
352,532
<p><strong>Questions</strong>:</p> <ul> <li>What does the kernel do if you stick a shell-script into the shebang line? </li> <li>How does the Kernel know which interpreter to launch?</li> </ul> <p><strong>Explanation</strong>:</p> <p>I recently wanted to write a wrapper around <em>/usr/bin/env</em> because my CGI Environment does not allow me to set the <em>PATH</em> variable, except globally (which of course sucks!).</p> <p>So I thought, "OK. Let's set PREPENDPATH and set <em>PATH</em> in a wrapper around env.". The resulting script (here called <em>env.1</em>) looked like this:</p> <pre><code>#!/bin/bash /usr/bin/env PATH=$PREPENDPATH:$PATH $* </code></pre> <p>which looks like it should work. I checked how they both react, after setting PREPENDPATH:</p> <pre><code>$ which /usr/bin/env python /usr/bin/env /usr/bin/python $ which /usr/bin/env.1 python /usr/bin/env /home/pi/prepend/bin/python </code></pre> <p>Look absolutely <em>perfect</em>! So far, so good. But look what happens to "Hello World!".</p> <pre><code># Shebang is #!/usr/bin/env python $ test-env.py Hello World! # Shebang is #!/usr/bin/env.1 python $ test-env.1.py Warning: unknown mime-type for "Hello World!" -- using "application/*" Error: no such file "Hello World!" </code></pre> <p>I guess I am missing something pretty fundamental about UNIX.</p> <p>I'm pretty lost, even after looking at the source code of the original <em>env</em>. It sets the environment and launches the program (or so it seems to me...).</p>
[ { "answer_id": 352830, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 2, "selected": false, "text": "execve /usr/bin/env.1 env #!/usr/bin/env /usr/bin/env.1 python\n /usr/bin/env.1 python env.1 env.1.c #include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n\n\nconst char* prependpath = \"/your/prepend/path/here:\";\n\nint main(int argc, char** argv){\n int args_len = argc + 1;\n char* args[args_len];\n const char* env = \"/usr/bin/env\";\n int i;\n\n /* arguments: the same */\n args[0] = env;\n for(i=1; i<argc; i++)\n args[i] = argv[i];\n args[argc] = NULL;\n\n /* environment */\n char* p = getenv(\"PATH\");\n char* newpath = (char*) malloc(strlen(p)\n + strlen(prependpath));\n sprintf(newpath, \"%s%s\", prependpath, p);\n setenv(\"PATH\", newpath, 1);\n\n execv(env, args);\n return 0;\n}\n" }, { "answer_id": 358537, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "$* \"$@\" env env\n env -i HOME=$HOME PATH=$PREPENDPATH:$PATH ... command args\n command #!/bin/bash\nexport PATH=${PREPENDPATH:?}:$PATH\nexec python \"$@\"\n $PREPENDPATH $PATH python exec python #!/bin/bash\nPATH=${PREPENDPATH:?}:$PATH exec python \"$@\"\n python /usr/bin /home/pi/prepend/bin env env env #!/bin/ksh\n#\n# @(#)$Id: boot.black_19.sh,v 1.3 2008/06/25 15:44:44 jleffler Exp $\n#\n# Boot server black_19 - IDS 11.50.FC1\n\nIXD=/usr/informix/11.50.FC1\nIXS=black_19\ncd $IXD || exit 1\n\nIXF=$IXD/do.not.start.$IXS\nif [ -f $IXF ]\nthen\n echo \"$0: will not start server $IXS because file $IXF exists\" 1>&2\n exit 1\nfi\n\nONINIT=$IXD/bin/oninit.$IXS\nif [ ! -f $ONINIT ]\nthen ONINIT=$IXD/bin/oninit\nfi\n\ntmpdir=$IXD/tmp\nDAEMONIZE=/work1/jleffler/bin/daemonize\nstdout=$tmpdir/$IXS.stdout\nstderr=$tmpdir/$IXS.stderr\n\nif [ ! -d $tmpdir ]\nthen asroot -u informix -g informix -C -- mkdir -p $tmpdir\nfi\n\n# Specialized programs carried to extremes:\n# * asroot sets UID and GID values and then executes\n# * env, which sets the environment precisely and then executes\n# * daemonize, which makes the process into a daemon and then executes\n# * oninit, which is what we really wanted to run in the first place!\n# NB: daemonize defaults stdin to /dev/null and could set umask but\n# oninit dinks with it all the time so there is no real point.\n# NB: daemonize should not be necessary, but oninit doesn't close its\n# controlling terminal and therefore causes cron-jobs that restart\n# it to hang, and interactive shells that started it to hang, and\n# tracing programs.\n# ??? Anyone want to integrate truss into this sequence?\n\nasroot -u informix -g informix -C -a dbaao -a dbsso -- \\\n env -i HOME=$IXD \\\n INFORMIXDIR=$IXD \\\n INFORMIXSERVER=$IXS \\\n INFORMIXCONCSMCFG=$IXD/etc/concsm.$IXS \\\n IFX_LISTEN_TIMEOUT=3 \\\n ONCONFIG=onconfig.$IXS \\\n PATH=/usr/bin:$IXD/bin \\\n SHELL=/usr/bin/ksh \\\n TZ=UTC0 \\\n $DAEMONIZE -act -d $IXD -o $stdout -e $stderr -- \\\n $ONINIT \"$@\"\n\ncase \"$*\" in\n(*v*) track-oninit-v $stdout;;\nesac\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15274/" ]
352,535
<p>Aloha</p> <p>I have a VS2008 solution to which I want to add a webservice reference. I enter an url like '<a href="http://192.168.100.87:7001/wsdl/IMySOAPWebService" rel="nofollow noreferrer">http://192.168.100.87:7001/wsdl/IMySOAPWebService</a>'. The Add Web Reference dialog starts looking then throws me this error: </p> <blockquote> <p>There was an error downloading '<a href="http://192.168.100.87:7001/wsdl/IMySOAPWebService/" rel="nofollow noreferrer">http://192.168.100.87:7001/wsdl/IMySOAPWebService/</a>$metadata'.</p> </blockquote> <p>Adding the exact same reference to a VS 2005 project works fine. Any clues?</p>
[ { "answer_id": 352830, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 2, "selected": false, "text": "execve /usr/bin/env.1 env #!/usr/bin/env /usr/bin/env.1 python\n /usr/bin/env.1 python env.1 env.1.c #include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n\n\nconst char* prependpath = \"/your/prepend/path/here:\";\n\nint main(int argc, char** argv){\n int args_len = argc + 1;\n char* args[args_len];\n const char* env = \"/usr/bin/env\";\n int i;\n\n /* arguments: the same */\n args[0] = env;\n for(i=1; i<argc; i++)\n args[i] = argv[i];\n args[argc] = NULL;\n\n /* environment */\n char* p = getenv(\"PATH\");\n char* newpath = (char*) malloc(strlen(p)\n + strlen(prependpath));\n sprintf(newpath, \"%s%s\", prependpath, p);\n setenv(\"PATH\", newpath, 1);\n\n execv(env, args);\n return 0;\n}\n" }, { "answer_id": 358537, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "$* \"$@\" env env\n env -i HOME=$HOME PATH=$PREPENDPATH:$PATH ... command args\n command #!/bin/bash\nexport PATH=${PREPENDPATH:?}:$PATH\nexec python \"$@\"\n $PREPENDPATH $PATH python exec python #!/bin/bash\nPATH=${PREPENDPATH:?}:$PATH exec python \"$@\"\n python /usr/bin /home/pi/prepend/bin env env env #!/bin/ksh\n#\n# @(#)$Id: boot.black_19.sh,v 1.3 2008/06/25 15:44:44 jleffler Exp $\n#\n# Boot server black_19 - IDS 11.50.FC1\n\nIXD=/usr/informix/11.50.FC1\nIXS=black_19\ncd $IXD || exit 1\n\nIXF=$IXD/do.not.start.$IXS\nif [ -f $IXF ]\nthen\n echo \"$0: will not start server $IXS because file $IXF exists\" 1>&2\n exit 1\nfi\n\nONINIT=$IXD/bin/oninit.$IXS\nif [ ! -f $ONINIT ]\nthen ONINIT=$IXD/bin/oninit\nfi\n\ntmpdir=$IXD/tmp\nDAEMONIZE=/work1/jleffler/bin/daemonize\nstdout=$tmpdir/$IXS.stdout\nstderr=$tmpdir/$IXS.stderr\n\nif [ ! -d $tmpdir ]\nthen asroot -u informix -g informix -C -- mkdir -p $tmpdir\nfi\n\n# Specialized programs carried to extremes:\n# * asroot sets UID and GID values and then executes\n# * env, which sets the environment precisely and then executes\n# * daemonize, which makes the process into a daemon and then executes\n# * oninit, which is what we really wanted to run in the first place!\n# NB: daemonize defaults stdin to /dev/null and could set umask but\n# oninit dinks with it all the time so there is no real point.\n# NB: daemonize should not be necessary, but oninit doesn't close its\n# controlling terminal and therefore causes cron-jobs that restart\n# it to hang, and interactive shells that started it to hang, and\n# tracing programs.\n# ??? Anyone want to integrate truss into this sequence?\n\nasroot -u informix -g informix -C -a dbaao -a dbsso -- \\\n env -i HOME=$IXD \\\n INFORMIXDIR=$IXD \\\n INFORMIXSERVER=$IXS \\\n INFORMIXCONCSMCFG=$IXD/etc/concsm.$IXS \\\n IFX_LISTEN_TIMEOUT=3 \\\n ONCONFIG=onconfig.$IXS \\\n PATH=/usr/bin:$IXD/bin \\\n SHELL=/usr/bin/ksh \\\n TZ=UTC0 \\\n $DAEMONIZE -act -d $IXD -o $stdout -e $stderr -- \\\n $ONINIT \"$@\"\n\ncase \"$*\" in\n(*v*) track-oninit-v $stdout;;\nesac\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6399/" ]
352,537
<p>How can I extend a builtin class in python? I would like to add a method to the str class.<br /> I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer.</p>
[ { "answer_id": 352546, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": true, "text": ">>> class X(str):\n... def my_method(self):\n... return int(self)\n...\n>>> s = X(\"Hi Mom\")\n>>> s.lower()\n'hi mom'\n>>> s.my_method()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 3, in my_method\nValueError: invalid literal for int() with base 10: 'Hi Mom'\n\n>>> z = X(\"271828\")\n>>> z.lower()\n'271828'\n>>> z.my_method()\n271828\n" }, { "answer_id": 33033631, "author": "lll", "author_id": 5426708, "author_profile": "https://Stackoverflow.com/users/5426708", "pm_score": 4, "selected": false, "text": "@extend(SomeClassThatAlreadyExists)\nclass SomeClassThatAlreadyExists:\n def some_method(self, blahblahblah):\n stuff\n def extend(class_to_extend):\n def decorator(extending_class):\n class_to_extend.__dict__.update(extending_class.__dict__)\n return class_to_extend\n return decorator\n" }, { "answer_id": 39709092, "author": "MVP", "author_id": 6231595, "author_profile": "https://Stackoverflow.com/users/6231595", "pm_score": 3, "selected": false, "text": "__dict__ def open(cls):\n def update(extension):\n for k,v in extension.__dict__.items():\n if k != '__dict__':\n setattr(cls,k,v)\n return cls\n return update\n\n\nclass A(object):\n def hello(self):\n print('Hello!')\n\nA().hello() #=> Hello!\n\n#reopen class A\n@open(A)\nclass A(object):\n def hello(self):\n print('New hello!')\n def bye(self):\n print('Bye bye')\n\n\nA().hello() #=> New hello!\nA().bye() #=> Bye bye\n def open(cls):\n def update(extension):\n namespace = dict(cls.__dict__)\n namespace.update(dict(extension.__dict__))\n return type(cls.__name__,cls.__bases__,namespace)\n return update\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
352,538
<p>I want the IIS server to return <code>HTTP 304 (Not Modified)</code> when a particular file is accessed. </p> <p>How can I set this up? </p>
[ { "answer_id": 352546, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": true, "text": ">>> class X(str):\n... def my_method(self):\n... return int(self)\n...\n>>> s = X(\"Hi Mom\")\n>>> s.lower()\n'hi mom'\n>>> s.my_method()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 3, in my_method\nValueError: invalid literal for int() with base 10: 'Hi Mom'\n\n>>> z = X(\"271828\")\n>>> z.lower()\n'271828'\n>>> z.my_method()\n271828\n" }, { "answer_id": 33033631, "author": "lll", "author_id": 5426708, "author_profile": "https://Stackoverflow.com/users/5426708", "pm_score": 4, "selected": false, "text": "@extend(SomeClassThatAlreadyExists)\nclass SomeClassThatAlreadyExists:\n def some_method(self, blahblahblah):\n stuff\n def extend(class_to_extend):\n def decorator(extending_class):\n class_to_extend.__dict__.update(extending_class.__dict__)\n return class_to_extend\n return decorator\n" }, { "answer_id": 39709092, "author": "MVP", "author_id": 6231595, "author_profile": "https://Stackoverflow.com/users/6231595", "pm_score": 3, "selected": false, "text": "__dict__ def open(cls):\n def update(extension):\n for k,v in extension.__dict__.items():\n if k != '__dict__':\n setattr(cls,k,v)\n return cls\n return update\n\n\nclass A(object):\n def hello(self):\n print('Hello!')\n\nA().hello() #=> Hello!\n\n#reopen class A\n@open(A)\nclass A(object):\n def hello(self):\n print('New hello!')\n def bye(self):\n print('Bye bye')\n\n\nA().hello() #=> New hello!\nA().bye() #=> Bye bye\n def open(cls):\n def update(extension):\n namespace = dict(cls.__dict__)\n namespace.update(dict(extension.__dict__))\n return type(cls.__name__,cls.__bases__,namespace)\n return update\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38212/" ]
352,540
<p>I'd like to create an XPS document for storing and printing.</p> <p>What is the easiest way to create an XPS document (for example with a simple grid with some data inside) in my program, and to pass it around?</p>
[ { "answer_id": 352551, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "public static byte[] ToXpsDocument(IEnumerable<FixedPage> pages)\n{\n // XPS DOCUMENTS MUST BE CREATED ON STA THREADS!!!\n // Note, this is test code, so I don't care about disposing my memory streams\n // You'll have to pay more attention to their lifespan. You might have to \n // serialize the xps document and remove the package from the package store \n // before disposing the stream in order to prevent throwing exceptions\n byte[] retval = null;\n Thread t = new Thread(new ThreadStart(() =>\n {\n // A memory stream backs our document\n MemoryStream ms = new MemoryStream(2048);\n // a package contains all parts of the document\n Package p = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);\n // the package store manages packages\n Uri u = new Uri(\"pack://TemporaryPackageUri.xps\");\n PackageStore.AddPackage(u, p);\n // the document uses our package for storage\n XpsDocument doc = new XpsDocument(p, CompressionOption.NotCompressed, u.AbsoluteUri);\n // An xps document is one or more FixedDocuments containing FixedPages\n FixedDocument fDoc = new FixedDocument();\n PageContent pc;\n foreach (var fp in pages)\n {\n // this part of the framework is weak and hopefully will be fixed in 4.0\n pc = new PageContent();\n ((IAddChild)pc).AddChild(fp);\n fDoc.Pages.Add(pc);\n }\n // we use the writer to write the fixed document to the xps document\n XpsDocumentWriter writer;\n writer = XpsDocument.CreateXpsDocumentWriter(doc);\n // The paginator controls page breaks during the writing process\n // its important since xps document content does not flow \n writer.Write(fDoc.DocumentPaginator);\n // \n p.Flush();\n\n // this part serializes the doc to a stream so we can get the bytes\n ms = new MemoryStream();\n var writer = new XpsSerializerFactory().CreateSerializerWriter(ms);\n writer.Write(doc.GetFixedDocumentSequence());\n\n retval = ms.ToArray();\n }));\n // Instantiating WPF controls on a MTA thread throws exceptions\n t.SetApartmentState(ApartmentState.STA);\n // adjust as needed\n t.Priority = ThreadPriority.AboveNormal;\n t.IsBackground = false;\n t.Start();\n //~five seconds to finish or we bail\n int milli = 0;\n while (buffer == null && milli++ < 5000)\n Thread.Sleep(1);\n //Ditch the thread\n if(t.IsAlive)\n t.Abort();\n // If we time out, we return null.\n return retval;\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
352,543
<p>This is a bit of a long question, but here we go. There is a version of FormatDateTime that is said to be thread safe in that you use </p> <pre><code>GetLocaleFormatSettings(3081, FormatSettings); </code></pre> <p>to get a value and then you can use it like so; </p> <pre><code>FormatDateTime('yyyy', 0, FormatSettings); </code></pre> <p>Now imagine two timers, one using TTimer (interval say 1000ms) and then another timer created like so (10ms interval); </p> <pre><code>CreateTimerQueueTimer ( FQueueTimer, 0, TimerCallback, nil, 10, 10, WT_EXECUTEINTIMERTHREAD ); </code></pre> <p>Now the narly bit, if in the call back and also the timer event you have the following code;</p> <pre><code>for i := 1 to 10000 do begin FormatDateTime('yyyy', 0, FormatSettings); end; </code></pre> <p>Note there is no assignment. This produces access violations almost immediatley, sometimes 20 minutes later, whatever, at random places. Now if you write that code in C++Builder it never crashes. The header conversion we are using is the JEDI JwaXXXX ones. Even if we put locks in the Delphi version around the code, it only delays the inevitable. We've looked at the original C header files and it all looks good, is there some different way that C++ uses the Delphi runtime? The thread safe version of FormatDatTime looks to be re-entrant. Any ideas or thoughts from anyone who may have seen this before.</p> <p><strong>UPDATE:</strong></p> <p>To narrow this down a bit, FormatSettings is passed in as a const, so does it matter if they use the same copy (as it turns out passing a local version within the function call yeilds the same problem)? Also the version of FormatDateTime that takes the FormatSettings doesn't call GetThreadLocale, because it already has the Locale information in the FormatSettings structure (I double checked by stepping through the code). </p> <p>I made mention of no assignment to make it clear that no shared storage is being accessed, so no locking is required.</p> <p>WT_EXECUTEINTIMERTHREAD is used to simplify the problem. I was under the impression you should only use it for very short tasks because it may mean it'll miss the next interval if it is running something long?</p> <p>If you use a plain old TThread the problem doesn't occur. What I am getting at here I suppose is that using a TThread or a TTimer works but using a thread created outside the VCL doesn't, that's why I asked if there was a difference in the way C++ Builder uses the VCL/Delphi RTL.</p> <p>As an aside this code as mentioned before also fails (but takes longer), after a while, CS := TCriticalSection.Create;</p> <pre><code> CS.Acquire; for i := 1 to LoopCount do begin FormatDateTime('yyyy', 0, FormatSettings); end; CS.Release; </code></pre> <p>And now for the bit I really don't understand, I wrote this as suggested;</p> <pre><code>function ReturnAString: string; begin Result := 'Test'; UniqueString(Result); end; </code></pre> <p>and then inside each type of timer the code is;</p> <pre><code> for i := 1 to 10000 do begin ReturnAString; end; </code></pre> <p>This causes the same kinds of failiures, as I said before the fault is never in the same place inside the CPU window etc. Sometimes it's an access violation and sometimes it might be an invalid pointer operation. I am using Delphi 2009 btw.</p> <p><strong>UPDATE 2:</strong></p> <p>Roddy (below) points out the Ontimer event (and unfortunately also Winsock, i.e. TClientSocket) use the windows message pump (as an aside it would be nice to have some nice Winsock2 components using IOCP and Overlapping IO), hence the push to get away from it. However does anyone know how to see what sort of thread local storage is setup on the CreateQueueTimerQueue?</p> <p>Thanks for taking the time to think and answer this problem.</p>
[ { "answer_id": 353304, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 1, "selected": false, "text": "FormatDateTime UniqueString(Result) FormatSettings FormatDateTime TThread Execute" }, { "answer_id": 354847, "author": "Bruce", "author_id": 44574, "author_profile": "https://Stackoverflow.com/users/44574", "pm_score": 4, "selected": true, "text": "if (IsMultiThread) {\n ShowMessage(\"IsMultiThread is True!\");\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44574/" ]
352,544
<p>I need a thread to wait until a file is exist or created. I have the following code so far:</p> <pre><code>while(!receivedDataFile.isFileExists("receiveddata.txt")) { try { Thead.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); return null; } } </code></pre> <p>When I run it, the following exception appears, and the thread ends:</p> <pre><code>java.lang.InterruptedException: sleep interrupted </code></pre>
[ { "answer_id": 352603, "author": "Nick Holt", "author_id": 41423, "author_profile": "https://Stackoverflow.com/users/41423", "pm_score": 2, "selected": false, "text": "interrupt interrupt InterruptedException" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,552
<p>My table has a large number of columns. I have a command to copy some data - think of it as cloning a product - but as the columns may change in the future, I would like to only select everything from the table and only change the value of one column without having to refer to the rest.</p> <p>Eg instead of:</p> <pre><code>INSERT INTO MYTABLE ( SELECT NEW_ID, COLUMN_1, COLUMN_2, COLUMN_3, etc FROM MYTABLE) </code></pre> <p>I would like something resembling</p> <pre><code>INSERT INTO MYTABLE ( SELECT * {update this, set ID = NEW_ID} FROM MYTABLE) </code></pre> <p>Is there a simple way to do this?</p> <p>This is a DB2 database on an iSeries, but answers for any platform are welcome.</p>
[ { "answer_id": 352558, "author": "berlindev", "author_id": 44276, "author_profile": "https://Stackoverflow.com/users/44276", "pm_score": 1, "selected": false, "text": "\nINSERT INTO MYTABLE\n(id, col1, col2)\nSELECT new_id,col1, col2\nFROM TABLE2\nWHERE ...;\n" }, { "answer_id": 352585, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 4, "selected": true, "text": "create table mytable_copy as select * from mytable;\nupdate mytable_copy set id=new_id;\ninsert into mytable select * from mytable_copy;\ndrop table mytable_copy;\n" }, { "answer_id": 1220376, "author": "Kristoffon", "author_id": 149364, "author_profile": "https://Stackoverflow.com/users/149364", "pm_score": 2, "selected": false, "text": "array_of_field_names = conn->get_field__list;\narray_of_row_values = conn->execute (\"SELECT... \");\narray_of_row_values [\"ID\"] = new_id_value\ninsert_query_string = \"construct insert query string from list of field names and values\";\nconn->execute (insert_query_string);\n $table_name = \"MYTABLE\";\n$field_name = \"ID\";\n$existing_field_value = \"100\";\n$new_field_value = \"101\";\n\nmy $q = $dbh->prepare (\"SELECT * FROM $table_name WHERE $field_name=?\");\n$q->execute ($existing_field_value);\nmy $rowdata = $q->fetchrow_hashref; # includes field names\n$rowdata->{$field_name} = $new_field_value;\n\nmy $insq = $dbh->prepare (\"INSERT INTO $table_name (\" . join (\", \", keys %$rowdata) . \n \") VALUES (\" . join (\", \", map { \"?\" } keys %$rowdata) . \");\";\n$insq->execute (values %$rowdata);\n" }, { "answer_id": 1221229, "author": "Rob Farley", "author_id": 144351, "author_profile": "https://Stackoverflow.com/users/144351", "pm_score": 2, "selected": false, "text": "declare @othercols nvarchar(max);\ndeclare @qry nvarchar(max);\n\nselect @othercols = (\nselect ', ' + quotename(name)\nfrom sys.columns\nwhere object_id = object_id('tableA')\nand name <> 'Field3'\nand is_identity = 0\nfor xml path(''));\n\nselect @qry = 'insert mynewtable (changingcol' + @othercols + ') select newval' + @othercols;\n\nexec sp_executesql @qry;\n" }, { "answer_id": 1221257, "author": "nWorx", "author_id": 59006, "author_profile": "https://Stackoverflow.com/users/59006", "pm_score": -1, "selected": false, "text": "insert into newTable(col1, col2, col3)\nselect (col1, col2, col3) from oldatable\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23447/" ]
352,569
<p>I have four tables containing exactly the same columns, and want to create a view over all four so I can query them together.</p> <p>Is this possible?</p> <p>(for tedious reasons I cannot/am not permitted to combine them, which would make this irrelevant!)</p>
[ { "answer_id": 352574, "author": "terjetyl", "author_id": 29519, "author_profile": "https://Stackoverflow.com/users/29519", "pm_score": 2, "selected": false, "text": "select * from table1\nunion \nselect * from table2\nunion\nselect * from table3\n" }, { "answer_id": 352577, "author": "AlfaZulu", "author_id": 44060, "author_profile": "https://Stackoverflow.com/users/44060", "pm_score": 5, "selected": true, "text": "(CREATE VIEW view_name AS\n(SELECT * FROM table1\nUNION\nSELECT * FROM table2\nUNION\nSELECT * FROM table3));\n" }, { "answer_id": 352580, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 2, "selected": false, "text": "select table1.column1, 1 as TableNumber\nfrom table1\n\nunion\n\nselect table2.column1, 2 as TableNumber\nfrom table2\n\n.. etc ..\n" }, { "answer_id": 352689, "author": "Pete OHanlon", "author_id": 43635, "author_profile": "https://Stackoverflow.com/users/43635", "pm_score": 3, "selected": false, "text": "TableA\nID Name RelatedID\n1 John 2\n2 Paul 1\n\nTableB\nID Name RelatedID\n1 Ringo 1\n2 George 1\n\nTableC\nID Name RelatedID\n1 Bob 1\n\nTableD\nID Name RelatedID\n1 Kate NULL\n 1 John\n2 Paul\n1 Ringo\n2 George\n1 Bob\n1 Kate\n SELECT A.ID MasterID, A.Name MasterName, \n B.ID BandID, B.Name BandName, \n C.ID BlackadderID, C.Name BlackadderName\n D.ID BlackadderRealID, D.Name BlackadderRealName\nFROM\n TableA A\nINNER JOIN\n TableB B\nON\n A.RelatedID = B.ID\nINNER JOIN\n TableC C\nON\n B.RelatedID = C.ID\nINNER JOIN\n TableD D\nON\n C.RelatedID = D.ID\n MasterID MasterName BandID BandName BlackAdderID BlackAdderName BlackadderRealID BlackadderRealName\n1 John 2 George 1 Bob 1 Kate\n2 Paul 1 Ringo 1 Bob 1 Kate\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23447/" ]
352,586
<p>I have an existing database of a film rental system. Each film has a has a rating attribute. In SQL they used a constraint to limit the allowed values of this attribute.</p> <pre><code>CONSTRAINT film_rating_check CHECK ((((((((rating)::text = ''::text) OR ((rating)::text = 'G'::text)) OR ((rating)::text = 'PG'::text)) OR ((rating)::text = 'PG-13'::text)) OR ((rating)::text = 'R'::text)) OR ((rating)::text = 'NC-17'::text))) </code></pre> <p>I think it would be nice to use a Java enum to map the constraint into the object world. But it's not possible to simply take the allowed values because of the special char in "PG-13" and "NC-17". So I implemented the following enum:</p> <pre><code>public enum Rating { UNRATED ( "" ), G ( "G" ), PG ( "PG" ), PG13 ( "PG-13" ), R ( "R" ), NC17 ( "NC-17" ); private String rating; private Rating(String rating) { this.rating = rating; } @Override public String toString() { return rating; } } @Entity public class Film { .. @Enumerated(EnumType.STRING) private Rating rating; .. </code></pre> <p>With the toString() method the direction enum -> String works fine, but String -> enum does not work. I get the following exception:</p> <blockquote> <p>[TopLink Warning]: 2008.12.09 01:30:57.434--ServerSession(4729123)--Exception [TOPLINK-116] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DescriptorException Exception Description: No conversion value provided for the value [NC-17] in field [FILM.RATING]. Mapping: oracle.toplink.essentials.mappings.DirectToFieldMapping[rating-->FILM.RATING] Descriptor: RelationalDescriptor(de.fhw.nsdb.entities.Film --> [DatabaseTable(FILM)])</p> </blockquote> <p>cheers </p> <p>timo</p>
[ { "answer_id": 352680, "author": "Andreas Petersson", "author_id": 16542, "author_profile": "https://Stackoverflow.com/users/16542", "pm_score": 2, "selected": false, "text": "public enum Rating {\n\n UNRATED,\n G, \n PG,\n PG_13 ,\n R ,\n NC_17 ;\n\n public String getRating() {\n return name().replace(\"_\",\"-\");;\n }\n}\n" }, { "answer_id": 352819, "author": "Mg.", "author_id": 314728, "author_profile": "https://Stackoverflow.com/users/314728", "pm_score": 0, "selected": false, "text": "public String getRating{ \n return rating.toString();\n}\n\npubic void setRating(String rating){ \n //parse rating string to rating enum\n //JPA will use this getter to set the values when getting data from DB \n} \n\n@Transient \npublic Rating getRatingValue(){ \n return rating;\n}\n\n@Transient \npublic Rating setRatingValue(Rating rating){ \n this.rating = rating;\n}\n" }, { "answer_id": 352891, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 3, "selected": false, "text": "public enum Rating {\n\n UNRATED ( \"\" ),\n G ( \"G\" ), \n PG ( \"PG\" ),\n PG13 ( \"PG-13\" ),\n R ( \"R\" ),\n NC17 ( \"NC-17\" );\n\n private String rating;\n\n private static Map<String, Rating> ratings = new HashMap<String, Rating>();\n static {\n for (Rating r : EnumSet.allOf(Rating.class)) {\n ratings.put(r.toString(), r);\n }\n }\n\n private static Rating getRating(String rating) {\n return ratings.get(rating);\n }\n\n private Rating(String rating) {\n this.rating = rating;\n }\n\n @Override\n public String toString() {\n return rating;\n }\n}\n" }, { "answer_id": 388303, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 5, "selected": false, "text": "Enum.ordinal() Enum.name() toString() Enum.toString() name()" }, { "answer_id": 425829, "author": "aledbf", "author_id": 53078, "author_profile": "https://Stackoverflow.com/users/53078", "pm_score": 5, "selected": false, "text": "@Enumerated(EnumType.ORDINAL)\n" }, { "answer_id": 7645127, "author": "Selvaraj Muthiah", "author_id": 429444, "author_profile": "https://Stackoverflow.com/users/429444", "pm_score": -1, "selected": false, "text": "@Column(columnDefinition=\"ENUM('User', 'Admin')\")\n" }, { "answer_id": 47291178, "author": "Jayen Chondigara", "author_id": 3511090, "author_profile": "https://Stackoverflow.com/users/3511090", "pm_score": -1, "selected": false, "text": "private final String value;\n\nParentalControlLevelsEnum(final String value) {\n this.value = value;\n}\n\npublic String getValue() {\n return value;\n}\n\npublic static ParentalControlLevelsEnum fromString(final String value) {\n for (ParentalControlLevelsEnum level : ParentalControlLevelsEnum.values()) {\n if (level.getValue().equalsIgnoreCase(value)) {\n return level;\n }\n }\n return null;\n}\n public int compare(final ParentalControlLevelsEnum o1, final ParentalControlLevelsEnum o2) {\n if (o1.ordinal() < o2.ordinal()) {\n return -1;\n } else {\n return 1;\n }\n}\n" }, { "answer_id": 61091709, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 1, "selected": false, "text": "enum Rating AttributeCoverter @Converter(autoApply = true)\npublic class RatingConverter implements AttributeConverter<Rating, String> {\n\n @Override\n public String convertToDatabaseColumn(Rating rating) {\n if (rating == null) {\n return null;\n }\n return rating.toString();\n }\n\n @Override\n public Rating convertToEntityAttribute(String code) {\n if (code == null) {\n return null;\n }\n\n return Stream.of(Rating.values())\n .filter(c -> c.toString().equals(code))\n .findFirst()\n .orElseThrow(IllegalArgumentException::new);\n }\n}\n" }, { "answer_id": 74260561, "author": "Pierre Demeestere", "author_id": 19868455, "author_profile": "https://Stackoverflow.com/users/19868455", "pm_score": 1, "selected": false, "text": "enum name() ordinal() enum Embeddable enum code public enum ECourseType {\n PACS004(\"pacs.004\"), PACS008(\"pacs.008\");\n\n private String code;\n\n ECourseType(String code) {\n this.code = code;\n }\n\n public String getCode() {\n return code;\n }\n}\n code enum code from() enum @Embeddable\npublic class CourseType {\n\nprivate static Map<String, ECourseType> codeToEnumCache = \nArrays.stream(ECourseType.values())\n .collect(Collectors.toMap( e -> e.getCode(), e -> e));\n\n private String value;\n\n private CourseType() {};\n\n public static CourseType from(ECourseType en) {\n CourseType toReturn = new CourseType();\n toReturn.value = en.getCode();\n return toReturn;\n }\n\n public ECourseType getEnum() {\n return codeToEnumCache.get(value);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass() ) return false;\n\n CourseType that = (CourseType) o;\n return Objects.equals(value, that.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n}\n equals() hashcode() public boolean isEquiv(ECourseType eCourseType) {\n return Objects.equals(eCourseType, getEnum());\n}\n public class Course {\n \n @Id\n @GeneratedValue\n @Column(name = \"COU_ID\")\n private Long pk;\n\n @Basic\n @Column(name = \"COURSE_NAME\")\n private String name;\n\n @Embedded\n @AttributeOverrides({\n @AttributeOverride(name = \"value\", column = @Column(name = \"COURSE_TYPE\")),\n })\n private CourseType type;\n\n public void setType(CourseType type) {\n this.type = type;\n }\n\n public void setType(ECourseType type) {\n this.type = CourseType.from(type);\n }\n\n}\n setType(ECourseType type) type ECourseType CREATE TABLE \"PUBLIC\".\"COU_COURSE\"\n(\n COU_ID bigint PRIMARY KEY NOT NULL,\n COURSE_NAME varchar(255),\n COURSE_TYPE varchar(255)\n)\n;\n Course public List<Course> findByType(CourseType type) {\n manager.clear();\n Query query = manager.createQuery(\"from Course c where c.type = :type\");\n query.setParameter(\"type\", type);\n return (List<Course>) query.getResultList();\n}\n name ordinal" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44002/" ]
352,592
<p>I use <a href="http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.aspx" rel="nofollow noreferrer">System.Web.Services.WebMethodAttribute</a> to make a public static method of an ASP.NET page callable from a client-side script:</p> <p><strong><em>test.aspx.cs</em></strong></p> <pre><code>[System.Web.Services.WebMethod] public static string GetResult() { return "result"; } </code></pre> <p><strong><em>test.aspx</em></strong></p> <pre><code>&lt;asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" /&gt; &lt;script type="text/javascript"&gt; alert(PageMethods.GetResult()); &lt;/script&gt; </code></pre> <p>The method works as it should, but if I load <em>test.aspx</em> with </p> <pre><code>Server.Transfer("test.aspx"); </code></pre> <p>I receive "Unknown web method" error. After</p> <pre><code>Response.Redirect("test.aspx"); </code></pre> <p>the page works well.</p> <p>Could you tell me, please, what is a reason of the error and how can it also be avoided? Many thanks!</p>
[ { "answer_id": 352680, "author": "Andreas Petersson", "author_id": 16542, "author_profile": "https://Stackoverflow.com/users/16542", "pm_score": 2, "selected": false, "text": "public enum Rating {\n\n UNRATED,\n G, \n PG,\n PG_13 ,\n R ,\n NC_17 ;\n\n public String getRating() {\n return name().replace(\"_\",\"-\");;\n }\n}\n" }, { "answer_id": 352819, "author": "Mg.", "author_id": 314728, "author_profile": "https://Stackoverflow.com/users/314728", "pm_score": 0, "selected": false, "text": "public String getRating{ \n return rating.toString();\n}\n\npubic void setRating(String rating){ \n //parse rating string to rating enum\n //JPA will use this getter to set the values when getting data from DB \n} \n\n@Transient \npublic Rating getRatingValue(){ \n return rating;\n}\n\n@Transient \npublic Rating setRatingValue(Rating rating){ \n this.rating = rating;\n}\n" }, { "answer_id": 352891, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 3, "selected": false, "text": "public enum Rating {\n\n UNRATED ( \"\" ),\n G ( \"G\" ), \n PG ( \"PG\" ),\n PG13 ( \"PG-13\" ),\n R ( \"R\" ),\n NC17 ( \"NC-17\" );\n\n private String rating;\n\n private static Map<String, Rating> ratings = new HashMap<String, Rating>();\n static {\n for (Rating r : EnumSet.allOf(Rating.class)) {\n ratings.put(r.toString(), r);\n }\n }\n\n private static Rating getRating(String rating) {\n return ratings.get(rating);\n }\n\n private Rating(String rating) {\n this.rating = rating;\n }\n\n @Override\n public String toString() {\n return rating;\n }\n}\n" }, { "answer_id": 388303, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 5, "selected": false, "text": "Enum.ordinal() Enum.name() toString() Enum.toString() name()" }, { "answer_id": 425829, "author": "aledbf", "author_id": 53078, "author_profile": "https://Stackoverflow.com/users/53078", "pm_score": 5, "selected": false, "text": "@Enumerated(EnumType.ORDINAL)\n" }, { "answer_id": 7645127, "author": "Selvaraj Muthiah", "author_id": 429444, "author_profile": "https://Stackoverflow.com/users/429444", "pm_score": -1, "selected": false, "text": "@Column(columnDefinition=\"ENUM('User', 'Admin')\")\n" }, { "answer_id": 47291178, "author": "Jayen Chondigara", "author_id": 3511090, "author_profile": "https://Stackoverflow.com/users/3511090", "pm_score": -1, "selected": false, "text": "private final String value;\n\nParentalControlLevelsEnum(final String value) {\n this.value = value;\n}\n\npublic String getValue() {\n return value;\n}\n\npublic static ParentalControlLevelsEnum fromString(final String value) {\n for (ParentalControlLevelsEnum level : ParentalControlLevelsEnum.values()) {\n if (level.getValue().equalsIgnoreCase(value)) {\n return level;\n }\n }\n return null;\n}\n public int compare(final ParentalControlLevelsEnum o1, final ParentalControlLevelsEnum o2) {\n if (o1.ordinal() < o2.ordinal()) {\n return -1;\n } else {\n return 1;\n }\n}\n" }, { "answer_id": 61091709, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 1, "selected": false, "text": "enum Rating AttributeCoverter @Converter(autoApply = true)\npublic class RatingConverter implements AttributeConverter<Rating, String> {\n\n @Override\n public String convertToDatabaseColumn(Rating rating) {\n if (rating == null) {\n return null;\n }\n return rating.toString();\n }\n\n @Override\n public Rating convertToEntityAttribute(String code) {\n if (code == null) {\n return null;\n }\n\n return Stream.of(Rating.values())\n .filter(c -> c.toString().equals(code))\n .findFirst()\n .orElseThrow(IllegalArgumentException::new);\n }\n}\n" }, { "answer_id": 74260561, "author": "Pierre Demeestere", "author_id": 19868455, "author_profile": "https://Stackoverflow.com/users/19868455", "pm_score": 1, "selected": false, "text": "enum name() ordinal() enum Embeddable enum code public enum ECourseType {\n PACS004(\"pacs.004\"), PACS008(\"pacs.008\");\n\n private String code;\n\n ECourseType(String code) {\n this.code = code;\n }\n\n public String getCode() {\n return code;\n }\n}\n code enum code from() enum @Embeddable\npublic class CourseType {\n\nprivate static Map<String, ECourseType> codeToEnumCache = \nArrays.stream(ECourseType.values())\n .collect(Collectors.toMap( e -> e.getCode(), e -> e));\n\n private String value;\n\n private CourseType() {};\n\n public static CourseType from(ECourseType en) {\n CourseType toReturn = new CourseType();\n toReturn.value = en.getCode();\n return toReturn;\n }\n\n public ECourseType getEnum() {\n return codeToEnumCache.get(value);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass() ) return false;\n\n CourseType that = (CourseType) o;\n return Objects.equals(value, that.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n}\n equals() hashcode() public boolean isEquiv(ECourseType eCourseType) {\n return Objects.equals(eCourseType, getEnum());\n}\n public class Course {\n \n @Id\n @GeneratedValue\n @Column(name = \"COU_ID\")\n private Long pk;\n\n @Basic\n @Column(name = \"COURSE_NAME\")\n private String name;\n\n @Embedded\n @AttributeOverrides({\n @AttributeOverride(name = \"value\", column = @Column(name = \"COURSE_TYPE\")),\n })\n private CourseType type;\n\n public void setType(CourseType type) {\n this.type = type;\n }\n\n public void setType(ECourseType type) {\n this.type = CourseType.from(type);\n }\n\n}\n setType(ECourseType type) type ECourseType CREATE TABLE \"PUBLIC\".\"COU_COURSE\"\n(\n COU_ID bigint PRIMARY KEY NOT NULL,\n COURSE_NAME varchar(255),\n COURSE_TYPE varchar(255)\n)\n;\n Course public List<Course> findByType(CourseType type) {\n manager.clear();\n Query query = manager.createQuery(\"from Course c where c.type = :type\");\n query.setParameter(\"type\", type);\n return (List<Course>) query.getResultList();\n}\n name ordinal" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
352,599
<p>i remember there being a way of marking a section of code in eclipse (special comment or annotation?) which made the autoformatter ignore that section. Or I may have drempt this...</p> <p>Used mainly when I have strings which wrap onto several lines and i don't want the autoformatter to rearrange this.</p>
[ { "answer_id": 352609, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 2, "selected": false, "text": "/**\n * foo <i>\n * bar </i>\n * \n * <pre>\n * foo\n * bar\n * </pre>\n */\n /**\n * foo <i> bar </i>\n * \n * <pre>\n * foo\n * bar\n * </pre>\n */\n <pre>" }, { "answer_id": 3345289, "author": "stm", "author_id": 403576, "author_profile": "https://Stackoverflow.com/users/403576", "pm_score": 7, "selected": true, "text": "/* @formatter:on */\n" }, { "answer_id": 20004588, "author": "matt burns", "author_id": 276093, "author_profile": "https://Stackoverflow.com/users/276093", "pm_score": 3, "selected": false, "text": "normal code\n\n/* @formatter:off */\nstrangely laid out code\n/* @formatter:on */\n\nnormal code\n public class SomeTest {\n\n @Test\n public void can_deserialize_json() {\n /* @formatter:off */\n String json = \"\" +\n \"{\" +\n \"   \\\"id\\\" : 123,\" +\n \"   \\\"address1\\\" : blah,\" +\n \"   \\\"shippingInfo\\\" : {\" +\n \"      \\\"trackingUrl\\\" : null,\" +\n \"      \\\"price\\\" : 350\" +\n \"   },\" +\n \"   \\\"errorMessage\\\" : null\" +\n \"}\";\n /* @formatter:on */\n MyClass.deserializeJson(json);\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44579/" ]
352,600
<p>Without using any third party program to do this (i.e. without VMware ThinApp, U3 or MojoPac etc.) How to move MSVC++ 6.0 from from its install on C: over to a USB drive? So that it can be used on different PCs with no admin rights and without installing anything on the host PC? Even if it's only usable as a console application would be fine, although to have the GUI including Visual Assist etc. would be even better. </p>
[ { "answer_id": 396313, "author": "Rob Kam", "author_id": 25093, "author_profile": "https://Stackoverflow.com/users/25093", "pm_score": 3, "selected": true, "text": "c:\\program files\\ e:\\progs\\msvc\\msvc6 e:\\progs\\msvc\\vc98 e:\\progs\\msvc\\vc98\\bin\\vcvars32.bat prompt $g\nset path=e:\\progs\\uedit;e:\\progs\\utl;%PATH%\ne:\ncd e:\\work\nstart e:\\progs\\uedit\\uedit32.exe /i=e:\\progs\\uedit\\uedit32.ini \ncmd /k\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25093/" ]
352,605
<p>I'm trying to debug a rather complicated formula evaluator written in T-SQL UDFs (don't ask) that <strong>recursively</strong> (but indirectly through an intermediate function) calls itself, blah, blah.</p> <p>And, of course, we have a bug.</p> <p>Now, using PRINT statements (that can then be read from ADO.NET by implementing a handler for the InfoMessage event), I can simulate a trace for stored procedures.</p> <p>Doing the same for UDF results in a compile time message:</p> <pre><code>Invalid use of side-effecting or time-dependent operator in 'PRINT' within a function. </code></pre> <p>I get the message (PRINT does some stuff like resetting <code>@@ROWCOUNT</code> which definitly is a no-no in UDFs, but how can I trace through the calls? I want to have this trace printed out, so I can study it without getting distracted by stepping through the calls in the debugger...</p> <p><strong>EDIT:</strong> I have tried to use the SQL Profiler (this was a first time one for me), but I can't figure out what to trace for: Although I can get the trace to output the queries sent to the database, they are opaque in the sense that I can't drill down to the Expression-UDFs called: I can trace the actual Stored Procedure invoked, but the UDFs called by this procedure are not listed. Am I missing something? I guess not...</p> <p><strong>EDIT #2:</strong> Allthough the (auto-)accepted answer does trace the function calls - very helpful, thanks - it does not help in finding out what parameters were <em>passed</em> to the function. This, of course, is essential in <strong>debugging</strong> recursive functions. I will post if I find any sollution at all...</p>
[ { "answer_id": 553683, "author": "Robin Day", "author_id": 40655, "author_profile": "https://Stackoverflow.com/users/40655", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION mySum\n( \n @param1 int,\n @param2 int\n)\nRETURNS INT AS\nBEGIN\n DECLARE @mySum int\n\n SET @mySum = @param1\n\n SET @mySum = @mySum + @param2\n\n RETURN @mySum\n\nEND\nGO\nSELECT dbo.mySum(1, 2)\n CREATE FUNCTION mySumDebug\n( \n @param1 int,\n @param2 int\n)\nRETURNS @myTable TABLE\n(\n [mySum] int,\n [debug] nvarchar(max)\n)\nAS\nBEGIN\n DECLARE @debug nvarchar(max)\n\n SET @debug = 'Declare @mySum variable. '\n DECLARE @mySum int\n\n SET @debug = @debug + 'Set @mySum = @param1(' + CONVERT(nvarchar(50), @param1) + ') '\n SET @mySum = @param1\n\n\n SET @debug = @debug + 'Add @param2(' + CONVERT(nvarchar(50), @param2) + ') to @mySum(' + CONVERT(nvarchar(50), @mySum) + ') '\n SET @mySum = @mySum + @param2\n\n SET @debug = @debug + 'Return @mySum variable. '\n\n INSERT @myTable (mySum, debug) VALUES (@mySum, @debug)\n\n RETURN\nEND\nGO\nSELECT mySum, debug FROM dbo.mySumDebug(1, 2)\n" }, { "answer_id": 557161, "author": "Matthew Farwell", "author_id": 1836, "author_profile": "https://Stackoverflow.com/users/1836", "pm_score": 4, "selected": false, "text": "alter FUNCTION [dbo].[ufn_mjf](@i numeric(10))\n RETURNS numeric(20) \nAS\nBEGIN\ndeclare @datapoint varchar(10)\n\n set @datapoint = 'hello world'\n\n return @i\nEND\ngo\ndrop table foo\ngo\ncreate table dbo.foo ( foo_id numeric(10)) \ngo\ndelete from foo\ninsert into foo ( foo_id ) values ( 1 )\ninsert into foo ( foo_id ) values ( 2 )\n\nselect foo_id, dbo.ufn_mjf(foo_id) from foo\n SQL:BatchStarting alter FUNCTION [dbo].[ufn_mjf](@i numeric(10))\nSQL:BatchStarting drop table foo\nSQL:BatchStarting create table dbo.foo ( foo_id numeric(10)) \nSQL:BatchStarting delete from foo\n insert into foo ( foo_id ) values ( 1 )\n insert into foo ( foo_id ) values ( 2 )\n select foo_id, dbo.ufn_mjf(foo_id) from foo\nSP:Starting select foo_id, dbo.ufn_mjf(foo_id) from foo\nSP:StmtStarting set @datapoint = 'hello world'\nSP:StmtStarting return @i\nSP:Completed select foo_id, dbo.ufn_mjf(foo_id) from foo\nSP:Starting select foo_id, dbo.ufn_mjf(foo_id) from foo\nSP:StmtStarting set @datapoint = 'hello world'\nSP:StmtStarting return @i\nSP:Completed select foo_id, dbo.ufn_mjf(foo_id) from foo\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
352,612
<p>I have a Maven pom that uses <code>&lt;packaging&gt;war&lt;/packaging&gt;</code>. But actually, I don't want build the war-file, I just want all the dependent jars collected and a full deployment directory created.</p> <p>So I'm running the <code>war:exploded</code> goal to generate the deploy directory:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;configuration&gt; &lt;webappDirectory&gt;target/${env}/deploy&lt;/webappDirectory&gt; &lt;archiveClasses&gt;true&lt;/archiveClasses&gt; &lt;/configuration&gt; &lt;goals&gt; &lt;goal&gt;exploded&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>The trouble is, the war file still gets built. Is there a simple way of having <code>&lt;packaging&gt;war&lt;/packaging&gt;</code> execute the <code>war:exploded</code> goal instead of the war:war goal?</p> <p>Or is there another simple way to do this?</p>
[ { "answer_id": 1449740, "author": "Rich Seller", "author_id": 123582, "author_profile": "https://Stackoverflow.com/users/123582", "pm_score": 3, "selected": false, "text": "<build>\n <plugins>\n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <executions>\n <execution>\n <id>process-resources</id>\n <phase>process-resources</phase>\n <goals>\n <goal>resources</goal>\n </goal>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-compile-plugin</artifactId>\n <executions>\n <execution>\n <id>compile</id>\n <phase>compile</phase>\n <goals>\n <goal>compile</goal>\n </goal>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <executions>\n <execution>\n <id>process-test-resources</id>\n <phase>process-test-resources</phase>\n <goals>\n <goal>testResources</goal>\n </goal>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-surefire-plugin</artifactId>\n <executions>\n <execution>\n <id>test</id>\n <phase>test</phase>\n <goals>\n <goal>test</goal>\n </goal>\n </execution>\n </executions>\n </plugin>\n <!-- package not wanted, install and deploy already defined for pom packaging-->\n <!--define war:war execution in a profile in case it is needed-->\n" }, { "answer_id": 1530489, "author": "cetnar", "author_id": 104796, "author_profile": "https://Stackoverflow.com/users/104796", "pm_score": 7, "selected": true, "text": "mvn prepare-package war:exploded\n" }, { "answer_id": 11134940, "author": "Michael Wyraz", "author_id": 1471588, "author_profile": "https://Stackoverflow.com/users/1471588", "pm_score": 6, "selected": false, "text": "<pluginManagement>\n <plugins>\n <plugin><!-- don't pack the war -->\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-war-plugin</artifactId>\n <executions>\n <execution>\n <id>default-war</id>\n <phase>none</phase>\n </execution>\n <execution>\n <id>war-exploded</id>\n <phase>package</phase>\n <goals>\n <goal>exploded</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n</pluginManagement>\n" }, { "answer_id": 29275298, "author": "David", "author_id": 1901067, "author_profile": "https://Stackoverflow.com/users/1901067", "pm_score": 3, "selected": false, "text": "mvn clean install <profiles>\n <profile>\n <id>war_explode</id>\n <build>\n <pluginManagement>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-war-plugin</artifactId>\n <version>2.6</version>\n <executions>\n <execution>\n <id>default-war</id>\n <phase>none</phase>\n </execution>\n <execution>\n <id>war-exploded</id>\n <phase>package</phase>\n <goals>\n <goal>exploded</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-install-plugin</artifactId>\n <executions>\n <execution>\n <id>default-install</id>\n <phase>none</phase>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </pluginManagement>\n </build>\n </profile>\n</profiles>\n [INFO] --- maven-install-plugin:2.4:install (default-install) @ *** ---\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD FAILURE\n[INFO] ------------------------------------------------------------------------\n[ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-install) on project ***: The packaging for this project did not assign a file to the build artifact -> [Help 1]\n mvn clean install -P war_explode" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41861/" ]
352,618
<p>From what I have read best practice is to have classes based on an interface and loosely couple the objects, in order to help code re-use and unit test.</p> <p>Is this correct and is it a rule that should always be followed? </p> <p>The reason I ask is I have recently worked on a system with 100’s of very different objects. A few shared common interfaces but most do not and wonder if it should have had an interface mirroring every property and function in those classes?</p> <p>I am using C# and dot net 2.0 however I believe this question would fit many languages. </p>
[ { "answer_id": 352734, "author": "Gargamel", "author_id": 28146, "author_profile": "https://Stackoverflow.com/users/28146", "pm_score": 1, "selected": false, "text": "ICustomer CustomerHander" }, { "answer_id": 9580084, "author": "Tom W", "author_id": 313414, "author_profile": "https://Stackoverflow.com/users/313414", "pm_score": 2, "selected": false, "text": "Print()\nDraw()\nSave()\nSerialize()\nUpdate()\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33/" ]
352,623
<p>I have to interface with a slightly archaic system that doesn't use webservices. In order to send data to this system, I need to post an XML document into a <i>form</i> on the other system's website. This XML document can get very large so I would like to compress it. The other system sits on IIS and I use C# my end. I could of course implement something that compresses the data before posting it, but that requires the other system to change so it can decompress the data. I would like to avoid changing the other system as I don't own it. </p> <p>I have heard vague things about enabling compression / http 1.1 in IIS and the browser but I have no idea how to translate that to my program. Basically, is there some property I can set in my program that will make my program automatically compress the data that it is sending to IIS and for IIS to seamlessly decompress it so the receiving app doesn't even know the difference? </p> <p>Here is some sample code to show roughly what I am doing; </p> <pre><code>private static void demo() { Stream myRequestStream = null; Stream myResponseStream = null; HttpWebRequest myWebRequest = (HttpWebRequest)System.Net .WebRequest.Create("http://example.com"); byte[] bytMessage = null; bytMessage = Encoding.ASCII.GetBytes("data=xyz"); myWebRequest.ContentLength = bytMessage.Length; myWebRequest.Method = "POST"; // Set the content type as form so that the data // will be posted as form myWebRequest.ContentType = "application/x-www-form-urlencoded"; //Get Stream object myRequestStream = myWebRequest.GetRequestStream(); //Writes a sequence of bytes to the current stream myRequestStream.Write(bytMessage, 0, bytMessage.Length); //Close stream myRequestStream.Close(); WebResponse myWebResponse = myWebRequest.GetResponse(); myResponseStream = myWebResponse.GetResponseStream(); } </code></pre> <p>"data=xyz" will actually be "data=[a several MB XML document]".</p> <p>I am aware that this question may ultimately fall under the non-programming banner if this is achievable through non-programmatic means so apologies in advance.</p>
[ { "answer_id": 352666, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": true, "text": "gzip" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11534/" ]
352,632
<p>I'm making a WPF application that is comprised of Screens (Presenter + View). I want to be able to declare these screens in a config file or SQL database. I have been trying to come up with a good solution I've given up and am asking how some of you design this sort of thing? I've been working at this for over a week and every solution I come up with stinks.</p> <p>In my WPF application I have a treeview that represents screens. When the user clicks on a node, the screen is loaded. I want to be able to populate the treenodes from a config file or database. The program should not care where these are stored so I can swap out a config store for a database store. If I have the screen info stored I can also use an IOC container to instantiate the screens for me and retrieve them by name. Here is a sample of the config file schema that I have come up with:</p> <pre><code>&lt;screen name="" title="" presenterType="" viewType=""/&gt; &lt;screen ...&gt; &lt;screen .../&gt; &lt;screen .../&gt; &lt;/screen&gt; &lt;screen .../&gt; </code></pre> <p>The latest solution I have come up with is to use a ScreenService that asks a ScreenRepository for ScreenInfo objects. Then I will be able to populate the treeview and IOC container with this information.</p> <p>Does this sound like a good solution? What would you do different? And, how do you design this sort of system in your own programming?</p>
[ { "answer_id": 352666, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": true, "text": "gzip" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36383/" ]
352,633
<p>I need to write a script to set ip address/mask/broadcast as an alias on eth0:0 plus set the default gateway.</p> <p>This solution works:</p> <pre><code>ifconfig eth0:0 &lt;ip&gt; netmask &lt;mask&gt; up ip route replace default via &lt;ip&gt; </code></pre> <p>but sometimes the second call gets an error "network unavailable".</p> <p>Adding a sleep between them fixes it, but is unreliable. What is the proper way to wait for the network to be ready?</p> <p>The best I came up with so far is retrying the ip call a couple times. This works, but feels ugly. </p>
[ { "answer_id": 354798, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 1, "selected": false, "text": "ping -c1 -w" }, { "answer_id": 355551, "author": "Anders Westrup", "author_id": 36845, "author_profile": "https://Stackoverflow.com/users/36845", "pm_score": 0, "selected": false, "text": "ip address add <ip>/<mask> dev eth0\nip route replace default via <ip>\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23420/" ]
352,638
<p>What do you think is the best way for obtaining the results of the work of a thread? Imagine a Thread which does some calculations, how do you warn the main program the calculations are done?</p> <p>You could poll every X milliseconds for some public variable called &quot;job finished&quot; or something by the way, but then you'll receive the results later than when they would be available... the main code would be losing time waiting for them. On the other hand, if you use a lower X, the CPU would be wasted polling so many times.</p> <p>So, what do you do to be aware that the Thread, or some Threads, have finished their work?</p> <p>Sorry if it looks similar to this other <a href="https://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output">question</a>, that's probably the reason for the <em>eben</em> answer, I suppose. What I meant was running lots of threads and know when all of them have finished, without polling them.</p> <p>I was thinking more in the line of sharing the CPU load between multiple CPU's using batches of Threads, and know when a batch has finished. I suppose it can be done with <strong>Future</strong>s objects, but that blocking <em><strong>get</strong></em> method looks a lot like a hidden lock, not something I like.</p> <p>Thanks everybody for your support. Although I also liked the answer by <em><strong>erickson</strong></em>, I think <em><strong>saua</strong></em>'s the most complete, and the one I'll use in my own code.</p>
[ { "answer_id": 352655, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 6, "selected": true, "text": "Future get() get() Callable Executor ThreadPoolExecutor get() get() get() isDone() get() true" }, { "answer_id": 352662, "author": "AlfaZulu", "author_id": 44060, "author_profile": "https://Stackoverflow.com/users/44060", "pm_score": 1, "selected": false, "text": "final Lock lock = new ReentrantLock();\nfinal Condition cv = lock.newCondition();\n cv.wait() cv.signal()" }, { "answer_id": 353210, "author": "Nick Holt", "author_id": 41423, "author_profile": "https://Stackoverflow.com/users/41423", "pm_score": 1, "selected": false, "text": "Thread Runnable Thread Runnable" }, { "answer_id": 353338, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 1, "selected": false, "text": "invokeAll isDone Futures Future get submit Runnable run Future submit cancel ExecutorService interrupt" }, { "answer_id": 377504, "author": "Neal Donnan", "author_id": 40970, "author_profile": "https://Stackoverflow.com/users/40970", "pm_score": 2, "selected": false, "text": "/**\n * Listener interface to implement to be called when work has\n * finished.\n */\npublic interface WorkerListener {\n public void workDone(WorkerThread thread);\n}\n import java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Thread to perform work\n */\npublic class WorkerThread implements Runnable {\n private List listeners = new ArrayList();\n private List results;\n\n public void run() {\n // Do some long running work here\n\n try {\n // Sleep to simulate long running task\n Thread.sleep(5000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n results = new ArrayList();\n results.add(\"Result 1\");\n\n // Work done, notify listeners\n notifyListeners();\n }\n\n private void notifyListeners() {\n for (Iterator iter = listeners.iterator(); iter.hasNext();) {\n WorkerListener listener = (WorkerListener) iter.next();\n listener.workDone(this);\n }\n }\n\n public void registerWorkerListener(WorkerListener listener) {\n listeners.add(listener);\n }\n\n public List getResults() {\n return results;\n }\n}\n import java.util.Iterator;\nimport java.util.List;\n\n/**\n * Class to simulate a main program\n */\npublic class MainProg {\n public MainProg() {\n WorkerThread worker = new WorkerThread();\n // Register anonymous listener class\n worker.registerWorkerListener(new WorkerListener() {\n public void workDone(WorkerThread thread) {\n System.out.println(\"Work done\");\n List results = thread.getResults();\n for (Iterator iter = results.iterator(); iter.hasNext();) {\n String result = (String) iter.next();\n System.out.println(result);\n }\n }\n });\n\n // Start the worker thread\n Thread thread = new Thread(worker);\n thread.start();\n\n System.out.println(\"Main program started\");\n }\n\n public static void main(String[] args) {\n MainProg prog = new MainProg();\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38238/" ]
352,654
<p>I've added a proxy to a webservice to a VS2008/.NET 3.5 solution. When constructing the client .NET throws this error:</p> <blockquote> <p>Could not find default endpoint element that references contract 'IMySOAPWebService' in the ServiceModel client configuration section. This might be because no configuaration file was found for your application or because no endpoint element matching this contract could be found in the client element.</p> </blockquote> <p>Searching for this error tells me to use the full namespace in the contract. Here's my app.config with full namespace:</p> <pre><code>&lt;client&gt; &lt;endpoint address="http://192.168.100.87:7001/soap/IMySOAPWebService" binding="basicHttpBinding" bindingConfiguration="IMySOAPWebServicebinding" contract="Fusion.DataExchange.Workflows.IMySOAPWebService" name="IMySOAPWebServicePort" /&gt; &lt;/client&gt; </code></pre> <p>I'm running XP local (I mention this because a number of Google hits mention win2k3) The app.config is copied to app.exe.config, so that is also not the problem.</p> <p>Any clues?</p>
[ { "answer_id": 1574335, "author": "Jeff Moeller", "author_id": 190820, "author_profile": "https://Stackoverflow.com/users/190820", "pm_score": 4, "selected": false, "text": "MyServiceClient myService = new MyServiceClient();\n" }, { "answer_id": 3016995, "author": "Andomar", "author_id": 50552, "author_profile": "https://Stackoverflow.com/users/50552", "pm_score": 6, "selected": false, "text": "new WebService.WebServiceSoapClient(\"http://myservice.com/moo.aspx\");\n new WebService.WebServiceSoapClient(\"WebServiceEndpoint\");\n Web.config App.config <client>\n <endpoint address=\"http://myservice.com/moo.aspx\"\n binding=\"basicHttpBinding\" \n bindingConfiguration=\"WebService\"\n contract=\"WebService.WebServiceSoap\"\n name=\"WebServiceEndpoint\" />\n </client>\n </system.serviceModel>\n" }, { "answer_id": 3037481, "author": "sAeid mOhammad hAshem", "author_id": 365697, "author_profile": "https://Stackoverflow.com/users/365697", "pm_score": 2, "selected": false, "text": "<system.serviceModel> <system.serviceModel>" }, { "answer_id": 4058429, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 3, "selected": false, "text": "ServiceReference <endpoint address=\"http://localhost:4000/ServiceName\" binding=\"basicHttpBinding\"\n bindingConfiguration=\"BasicHttpBinding_ISchedulerService\"\n contract=\"ServiceReference.ISchedulerService\" \n name=\"BasicHttpBinding_ISchedulerService\" />\n <endpoint address=\"http://localhost:4000/ServiceName\" binding=\"basicHttpBinding\"\n bindingConfiguration=\"BasicHttpBinding_ISchedulerService\"\n contract=\"ISchedulerService\" \n name=\"BasicHttpBinding_ISchedulerService\" />\n" }, { "answer_id": 6369334, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 7, "selected": false, "text": "var remoteAddress = new System.ServiceModel.EndpointAddress(_webServiceUrl);\n\nusing (var productService = new ProductClient(new System.ServiceModel.BasicHttpBinding(), remoteAddress))\n{\n //set timeout\n productService.Endpoint.Binding.SendTimeout = new TimeSpan(0,0,0,_webServiceTimeout);\n\n //call web service method\n productResponse = productService.GetProducts();\n} \n BasicHttpsBinding BasicHttpBinding" }, { "answer_id": 7021038, "author": "Bravo", "author_id": 835464, "author_profile": "https://Stackoverflow.com/users/835464", "pm_score": 4, "selected": false, "text": "<system.serviceModel> <system.serviceModel>" }, { "answer_id": 8614358, "author": "rob", "author_id": 799759, "author_profile": "https://Stackoverflow.com/users/799759", "pm_score": 2, "selected": false, "text": "ChannelFactory<TService> _channelFactory = new ChannelFactory<TService>(\"\");\n" }, { "answer_id": 23640621, "author": "David", "author_id": 1467396, "author_profile": "https://Stackoverflow.com/users/1467396", "pm_score": 2, "selected": false, "text": "web.config <protocolMapping>\n <add binding=\"basicHttpsBinding\" scheme=\"https\" />\n</protocolMapping>\n protocolMapping <protocolMapping>\n <add binding=\"basicHttpBinding\" scheme=\"http\" />\n <add binding=\"basicHttpsBinding\" scheme=\"https\" />\n</protocolMapping>\n" }, { "answer_id": 26642221, "author": "saille", "author_id": 30246, "author_profile": "https://Stackoverflow.com/users/30246", "pm_score": 2, "selected": false, "text": "<endpoint contract=\"global::MyNamepsace.IMyContract\" .../>\n <endpoint contract=\"MyNamepsace.IMyContract\" .../>\n" }, { "answer_id": 27310639, "author": "melvas", "author_id": 2087567, "author_profile": "https://Stackoverflow.com/users/2087567", "pm_score": 4, "selected": false, "text": "public static class ServiceClientHelper\n{\n public static T GetClient<T>(string moduleName) where T : IClientChannel\n {\n var channelType = typeof(T);\n var contractType = channelType.GetInterfaces().First(i => i.Namespace == channelType.Namespace);\n var contractAttribute = contractType.GetCustomAttributes(typeof(ServiceContractAttribute), false).First() as ServiceContractAttribute;\n\n if (contractAttribute == null)\n throw new Exception(\"contractAttribute not configured\");\n\n //path to your lib app.config (mark as \"Copy Always\" in properties)\n var configPath = HostingEnvironment.MapPath(String.Format(\"~/Modules/{0}/bin/{0}.dll.config\", moduleName)); \n\n var configuration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = configPath }, ConfigurationUserLevel.None);\n var serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);\n\n if (serviceModelSectionGroup == null)\n throw new Exception(\"serviceModelSectionGroup not configured\");\n\n var endpoint = serviceModelSectionGroup.Client.Endpoints.OfType<ChannelEndpointElement>().First(e => e.Contract == contractAttribute.ConfigurationName);\n var channelFactory = new ConfigurationChannelFactory<T>(endpoint.Name, configuration, null);\n var client = channelFactory.CreateChannel();\n return client;\n }\n}\n using (var client = ServiceClientHelper.GetClient<IDefaultNameServiceChannel>(yourLibName)) {\n ... get data from service ...\n }\n" }, { "answer_id": 37552233, "author": "Waldemar Gałęzinowski", "author_id": 5343480, "author_profile": "https://Stackoverflow.com/users/5343480", "pm_score": 2, "selected": false, "text": "<client>\n <endpoint address=\"http://192.168.100.87:7001/soap/IMySOAPWebService\"\n binding=\"basicHttpBinding\" \n contract=\"MyNamespace.IMySOAPWebService\" />\n</client>\n" }, { "answer_id": 39613317, "author": "nzrytmn", "author_id": 3193030, "author_profile": "https://Stackoverflow.com/users/3193030", "pm_score": 2, "selected": false, "text": "<client>\n <endpoint address=\"https://xxxxxxxx\" binding=\"basicHttpBinding\" bindingConfiguration=\"basic\" contract=\"ServiceReference.IIntegrationService\" name=\"basic\" />\n</client>\n <client>\n <endpoint address=\"xxxxxxxxxxxxx\" binding=\"basicHttpBinding\" bindingConfiguration=\"basic\" contract=\"ServiceReference1.IIntegrationService\" name=\"basic\" />\n</client>\n <client>\n <endpoint address=\"https://xxxxxxxxxxx\" binding=\"basicHttpBinding\" bindingConfiguration=\"basic\" contract=\"MyServiceReferrence.IIntegrationService\" name=\"basic\" />\n</client>\n" }, { "answer_id": 44935152, "author": "markaaronky", "author_id": 3456812, "author_profile": "https://Stackoverflow.com/users/3456812", "pm_score": 4, "selected": false, "text": " <system.serviceModel>\n<bindings>\n <basicHttpBinding>\n <binding name=\"BasicHttpBinding_ITranslationServiceOutbound\" />\n </basicHttpBinding>\n</bindings>\n<client>\n <endpoint address=\"http://MyHostName/TranslationServiceOutbound/TranslationServiceOutbound.svc\"\n binding=\"basicHttpBinding\" bindingConfiguration=\"BasicHttpBinding_ITranslationServiceOutbound\"\n contract=\"TranslationService.ITranslationServiceOutbound\" name=\"BasicHttpBinding_ITranslationServiceOutbound\" />\n</client>\n" }, { "answer_id": 49750125, "author": "Nikhil Dinesh", "author_id": 735597, "author_profile": "https://Stackoverflow.com/users/735597", "pm_score": -1, "selected": false, "text": "<system.serviceModel>" }, { "answer_id": 67312620, "author": "Naz141", "author_id": 2116420, "author_profile": "https://Stackoverflow.com/users/2116420", "pm_score": 0, "selected": false, "text": "endpointConfigurationName endpointConfigurationName EservicesNew.ServiceClient eservicenew = new EservicesNew.ServiceClient(\"BasicHttpsBinding_IService\");\n endpointConfigurationName bindingConfiguration BasicHttpsBinding_IService" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6399/" ]
352,670
<p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
[ { "answer_id": 353510, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 3, "selected": false, "text": "def WeightedSelectionWithoutReplacement(l, n):\n \"\"\"Selects without replacement n random elements from a list of (weight, item) tuples.\"\"\"\n l = sorted((random.random() * x[0], x[1]) for x in l)\n return l[-n:]\n def WeightedSelectionWithReplacement(l, n):\n \"\"\"Selects with replacement n random elements from a list of (weight, item) tuples.\"\"\"\n cuml = []\n total_weight = 0.0\n for weight, item in l:\n total_weight += weight\n cuml.append((total_weight, item))\n return [cuml[bisect.bisect(cuml, random.random()*total_weight)] for x in range(n)]\n" }, { "answer_id": 353576, "author": "John with waffle", "author_id": 279, "author_profile": "https://Stackoverflow.com/users/279", "pm_score": 6, "selected": true, "text": "(a:1, b:1, c:1, d:1, e:1) 1.0 (a:0.2 b:0.2 c:0.2 d:0.2 e:0.2) |p| 1/|p| 8 0.125 a (p1{a|null,1.0},p2,p3,p4,p5,p6,p7,p8) (a:0.075, b:0.2 c:0.2 d:0.2 e:0.2) (p1{a|null,1.0},p2{a|b,0.6},p3,p4,p5,p6,p7,p8) (a:0, b:0.15 c:0.2 d:0.2 e:0.2) U(0,1) 0.001100000 lg2(p) 3 001.1 0.5 0.5 < 0.6 a" }, { "answer_id": 20548895, "author": "josliber", "author_id": 3093387, "author_profile": "https://Stackoverflow.com/users/3093387", "pm_score": 4, "selected": false, "text": "import heapq\nimport math\nimport random\n\ndef WeightedSelectionWithoutReplacement(weights, m):\n elt = [(math.log(random.random()) / weights[i], i) for i in range(len(weights))]\n return [x[1] for x in heapq.nlargest(m, elt)]\n" }, { "answer_id": 29722230, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 2, "selected": false, "text": "bucket[1] def prep(weights):\n data_sz = len(weights)\n factor = data_sz/float(sum(weights))\n data = [[w*factor, i] for i,w in enumerate(weights)]\n big=0\n while big<data_sz and data[big][0]<=1.0: big+=1\n for small,bucket in enumerate(data):\n if bucket[1] is not small: continue\n excess = 1.0 - bucket[0]\n while excess > 0:\n if big==data_sz: break\n bucket[1] = big\n bucket = data[big]\n bucket[0] -= excess\n excess = 1.0 - bucket[0]\n if (excess >= 0):\n big+=1\n while big<data_sz and data[big][0]<=1: big+=1\n return data\n\ndef sample(data):\n r=random.random()*len(data)\n idx = int(r)\n return data[idx][1] if r-idx > data[idx][0] else idx\n TRIALS=1000\nweights = [20,1.5,9.8,10,15,10,15.5,10,8,.2];\nsamples = [0]*len(weights)\ndata = prep(weights)\n\nfor _ in range(int(sum(weights)*TRIALS)):\n samples[sample(data)]+=1\n\nresult = [float(s)/TRIALS for s in samples]\nerr = [a-b for a,b in zip(result,weights)]\nprint(result)\nprint([round(e,5) for e in err])\nprint(sum([e*e for e in err]))\n" }, { "answer_id": 40071790, "author": "Maroxo", "author_id": 6779095, "author_profile": "https://Stackoverflow.com/users/6779095", "pm_score": 0, "selected": false, "text": " import numpy.random as rnd\n\n sampling_size = 3\n domain = ['white','blue','black','yellow','green']\n probs = [.1, .2, .4, .1, .2]\n sample = rnd.choice(domain, size=sampling_size, replace=False, p=probs)\n # in short: rnd.choice(domain, sampling_size, False, probs)\n print(sample)\n # Possible output: ['white' 'black' 'blue']\n replace True" }, { "answer_id": 57466348, "author": "k06a", "author_id": 440168, "author_profile": "https://Stackoverflow.com/users/440168", "pm_score": 0, "selected": false, "text": "K N 0.1\n0.1\n0.8\n 2 3 0.254315\n0.256755\n0.488930\n 2 3 >K N std::vector<int> validators;\nstd::vector<int> weights(n);\nint totalWeights = 0;\n\nfor (int j = 0; validators.size() < m; j++) {\n int value = rand() % likehoodsSum;\n for (int i = 0; i < n; i++) {\n if (value < likehoods[i]) {\n if (weights[i] == 0) {\n validators.push_back(i);\n }\n weights[i]++;\n totalWeights++;\n break;\n }\n\n value -= likehoods[i];\n }\n}\n 0.101230\n0.099113\n0.799657\n" }, { "answer_id": 66553611, "author": "Joey Jojo Jr Shabadoo", "author_id": 6888894, "author_profile": "https://Stackoverflow.com/users/6888894", "pm_score": 1, "selected": false, "text": "numpy.random.choice" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12030/" ]
352,673
<p>I know I can update a single record like this - but then how to I get access to the id of the record that was updated? (I'm using MSSQL so I can't use Oracles RowId)</p> <pre><code>update myTable set myCol = 'foo' where itemId in (select top 1 itemId from myTable ) </code></pre> <p>If I was peforming an Insert I could use getGeneratedKeys to get the id field value, but I don't think there is an equivalent for an update?</p> <p>I know I can use a scrollable resultset to do what I want</p> <p>i.e.</p> <pre><code>stmt = conn.prepareStatement("select top 1 myCol, itemId from myTable", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet resultSet = stmt.executeQuery(); if(resultSet.first()){ resultSet.updateString(1, "foo"); resultSet.updateRow(); String theItemId = resultSet.getString(1) } resultSet.close(); </code></pre> <p>but I'm concerned about performance as testing shows lock timeouts under load and I was wondering if there was a better/simpler way?</p> <p>-- EDIT: Just to finalise this issue... When we migrate to MSSQL2005 we will upgrade our code to use Rich's answer. In the current release we have used the lock hints: (UPDLOCK ROWLOCK READPAST) to mitigate the performance problems our original code showed. </p>
[ { "answer_id": 352737, "author": "Rich Andrews", "author_id": 37381, "author_profile": "https://Stackoverflow.com/users/37381", "pm_score": 4, "selected": true, "text": "SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n\nDROP TABLE [dbo].[TEST_TABLE]\nGO\n\nCREATE TABLE [dbo].[TEST_TABLE](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [name] [nvarchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,\n CONSTRAINT [PK_TEST_TABLE] PRIMARY KEY CLUSTERED \n(\n [id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\n\n-- An insert which will return the identity\nINSERT INTO [dbo].[TEST_TABLE] ([name]) \nOUTPUT inserted.id\nVALUES('Test 1')\n\n-- Another insert which will return the identity\nINSERT INTO [dbo].[TEST_TABLE] ([name]) \nOUTPUT inserted.id\nVALUES('Test 2')\n\n-- Now an update which will return the identity\nUPDATE [dbo].[TEST_TABLE]\nSET [name] = 'Updated Test 1'\nOUTPUT inserted.id\nWHERE [name] = 'Test 1'\n\nSELECT id, [name] FROM [dbo].[TEST_TABLE]\n update myTable\nset myCol = 'foo'\noutput inserted.itemid\nwhere itemId in (select top 1 itemId from myTable )\n" }, { "answer_id": 352760, "author": "Mg.", "author_id": 314728, "author_profile": "https://Stackoverflow.com/users/314728", "pm_score": -1, "selected": false, "text": "@@Identity" }, { "answer_id": 352775, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "Begin Tran\n\nupdate myTable\nset myCol = 'foo'\nwhere itemId in (select top 1 itemId from myTable )\n\nselect top 1 itemId from myTable\n\nCommit Tran\n" }, { "answer_id": 352822, "author": "keithwarren7", "author_id": 40714, "author_profile": "https://Stackoverflow.com/users/40714", "pm_score": 0, "selected": false, "text": "Create Procedure doMyUpdate\n\n @Id int output\n\nas\n\nSet @Id = (select top 1 itemId from myTable)\nupdate myTable\nset myCol = 'foo'\nwhere itemId = @Id\n Create Procedure doMyUpdate\n\nas\n\nDeclare @Id int\nSet @Id = (select top 1 itemId from myTable)\n\nupdate myTable\nset myCol = 'foo'\nwhere itemId = @Id\n\nRETURN @Id\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44538/" ]
352,674
<p>i wonder if there is a way to generate valid GUIDs/UUIDs where the first (or any part) part is a user-selected prefix.</p> <p>I.e., the GUID has the format AAAAAAAA-BBBB-CCCC-DDDD-DDDDDDDDDDDD, and I want to set any part to a pre-defined value (ideally the AAA's). The goal is to have GUIDs still globally unique, but they do not need to be cryptographically safe.</p>
[ { "answer_id": 352802, "author": "Oliver Friedrich", "author_id": 44532, "author_profile": "https://Stackoverflow.com/users/44532", "pm_score": 1, "selected": false, "text": "\nGuid g = Guid.NewGuid();\nstring gs = g.ToString();\nGuid f = new Guid(string.Format(\"{0}-{1}\", \"AAAAAAAA\", gs.Substring(gs.IndexOf('-') + 1)));\n" }, { "answer_id": 352946, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": " UUID = time-low \"-\" time-mid \"-\"\n time-high-and-version \"-\"\n clock-seq-and-reserved\n clock-seq-low \"-\" node\n time-low = 4hexOctet\n time-mid = 2hexOctet\n time-high-and-version = 2hexOctet\n clock-seq-and-reserved = hexOctet\n clock-seq-low = hexOctet\n node = 6hexOctet\n hexOctet = hexDigit hexDigit\n hexDigit =\n \"0\" / \"1\" / \"2\" / \"3\" / \"4\" / \"5\" / \"6\" / \"7\" / \"8\" / \"9\" /\n \"a\" / \"b\" / \"c\" / \"d\" / \"e\" / \"f\" /\n \"A\" / \"B\" / \"C\" / \"D\" / \"E\" / \"F\"\n" }, { "answer_id": 4948974, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 2, "selected": false, "text": "using System;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n string target_prefix = \"dead\";\n\n while (true)\n {\n Guid g = Guid.NewGuid();\n string gs = g.ToString();\n if (gs.Substring(0, target_prefix.Length) == target_prefix)\n {\n Console.WriteLine(\"Match: \" + gs);\n }\n else\n {\n //Console.WriteLine(\"Mismatch: \" + gs);\n }\n }\n }\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
352,676
<p>I know how to connect to web server using an iPhone but now I have to connect the iPhone to a web service. I don't know how to do it and there is no demo or class available online.</p> <p>Does anyone have any ideas?</p>
[ { "answer_id": 352750, "author": "Geraud.ch", "author_id": 43954, "author_profile": "https://Stackoverflow.com/users/43954", "pm_score": 4, "selected": false, "text": "NSURL *URL=[[NSURL alloc] initWithString:stringForURL];\nNSString *results = [[NSString alloc] initWithContentsOfURL :URL];\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,693
<pre><code>class Trial { static int i; int getI() { return i;} void setI(int value) { i = value;} } public class ttest { public static void main(String args[]) { Trial t1 = new Trial(); t1.setI(10); System.out.println(t1.getI()); Trial t2 = new Trial(); t2.setI(100); System.out.println(t1.getI()); System.out.println(t2.getI()); } } </code></pre> <p>Here trial is a non static class and i is a static variable. How can I access this from a static main method. Is this way correct?</p>
[ { "answer_id": 352702, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "Trial t1 = new Trial(); \n" }, { "answer_id": 352992, "author": "frankern", "author_id": 44617, "author_profile": "https://Stackoverflow.com/users/44617", "pm_score": 0, "selected": false, "text": "class Trial { \n private int i; \n int getI() { return i;} \n void setI(int value) {i = value;} \n} \n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,694
<p>I'm trying to pass u url as parameter to a get method. I defined a route that accepts a {*url} parameter so I can send "/" characters without it separating my parameter. As soon as there is a ":" in the url (like in http: or localhost:3857 for example), the method never gets hit.</p> <p>The Html.ActionLink method escapes it's parameter itself, but it doesn't seem to escape the ':'. I cannot escape it manually because then the escape characters get escaped by the very same Html.Actionlink method.</p> <p>any ideas?</p>
[ { "answer_id": 4866802, "author": "tessa", "author_id": 123246, "author_profile": "https://Stackoverflow.com/users/123246", "pm_score": 1, "selected": false, "text": "<a href=\"Movies?id=@item.ID\">@item.Title</a>\n Request.QueryString.Get(\"id\")\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
352,695
<p>I currently trying to find a solution, how to ensure that a test fails if an exception occurs in a thread which is spawn by the test method.</p> <p>I DON'T want to start a discussion about more than one thread in a unit test. => "unit test".Replace("unit","integration");</p> <p>I already read a lot of threads in several forums, I know about <a href="http://www.peterprovost.org/blog/post/NUnit-and-Multithreaded-Tests-CrossThreadTestRunner.aspx" rel="nofollow noreferrer" title="CrossThreadTestRunner">CrossThreadTestRunner</a>, but I'm searching for a solution whichs integrates into nunit, and does not require to rewrite a lot of tests.</p>
[ { "answer_id": 3319885, "author": "Tim Lloyd", "author_id": 189516, "author_profile": "https://Stackoverflow.com/users/189516", "pm_score": 2, "selected": false, "text": "<legacyUnhandledExceptionPolicy enabled=\"1\"/>\n <legacyUnhandledExceptionPolicy enabled=\"0\" />" }, { "answer_id": 32106502, "author": "Bruno Guardia", "author_id": 4917076, "author_profile": "https://Stackoverflow.com/users/4917076", "pm_score": 0, "selected": false, "text": " const int MaxThreads = 25;\n const int MaxWait = 10;\n const int Iterations = 10;\n private readonly Random random=new Random();\n private static int startedThreads=MaxThreads ;\n private static int exceptions = 0;\n [Test]\n public void testclass()\n {\n // Create n threads, each of them will be reading configuration while another one cleans up\n\n Thread thread = new Thread(Method1)\n {\n IsBackground = true,\n Name = \"MyThread0\"\n };\n\n thread.Start();\n for (int i = 1; i < MaxThreads; i++)\n {\n thread = new Thread(Method2)\n {\n IsBackground = true,\n Name = string.Format(\"MyThread{0}\", i)\n };\n\n thread.Start();\n }\n\n // wait for all of them to finish\n while (startedThreads > 0 && exceptions==0)\n {\n Thread.Sleep(MaxWait);\n }\n Assert.AreEqual(0, exceptions, \"Expected no exceptions on threads\");\n }\n\n private void Method1()\n {\n try\n {\n for (int i = 0; i < Iterations; i++)\n {\n // Stuff being tested\n Thread.Sleep(random.Next(MaxWait));\n }\n }\n catch (Exception exception)\n {\n Console.Out.WriteLine(\"Ërror in Method1 Thread {0}\", exception);\n exceptions++;\n }\n finally\n {\n startedThreads--;\n }\n }\n\n private void Method2()\n {\n try\n {\n for (int i = 0; i < Iterations; i++)\n {\n // Stuff being tested\n Thread.Sleep(random.Next(MaxWait));\n }\n }\n catch (Exception exception)\n {\n Console.Out.WriteLine(\"Ërror in Method2 Thread {0}\", exception);\n exceptions++;\n }\n finally\n {\n startedThreads--;\n }\n }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24756/" ]
352,699
<p>I want that list, because if something horrible happens, and I'll have to reinstall Visual Studio - I'll need this list, so that I can recreate the same development environment. This also makes it hard to search for updates - I can not see the versions of currently installed plug-ins.</p> <p>So, is there a single place in Visual Studio, that would show me a complete list of plug-ins and their versions?</p>
[ { "answer_id": 3319885, "author": "Tim Lloyd", "author_id": 189516, "author_profile": "https://Stackoverflow.com/users/189516", "pm_score": 2, "selected": false, "text": "<legacyUnhandledExceptionPolicy enabled=\"1\"/>\n <legacyUnhandledExceptionPolicy enabled=\"0\" />" }, { "answer_id": 32106502, "author": "Bruno Guardia", "author_id": 4917076, "author_profile": "https://Stackoverflow.com/users/4917076", "pm_score": 0, "selected": false, "text": " const int MaxThreads = 25;\n const int MaxWait = 10;\n const int Iterations = 10;\n private readonly Random random=new Random();\n private static int startedThreads=MaxThreads ;\n private static int exceptions = 0;\n [Test]\n public void testclass()\n {\n // Create n threads, each of them will be reading configuration while another one cleans up\n\n Thread thread = new Thread(Method1)\n {\n IsBackground = true,\n Name = \"MyThread0\"\n };\n\n thread.Start();\n for (int i = 1; i < MaxThreads; i++)\n {\n thread = new Thread(Method2)\n {\n IsBackground = true,\n Name = string.Format(\"MyThread{0}\", i)\n };\n\n thread.Start();\n }\n\n // wait for all of them to finish\n while (startedThreads > 0 && exceptions==0)\n {\n Thread.Sleep(MaxWait);\n }\n Assert.AreEqual(0, exceptions, \"Expected no exceptions on threads\");\n }\n\n private void Method1()\n {\n try\n {\n for (int i = 0; i < Iterations; i++)\n {\n // Stuff being tested\n Thread.Sleep(random.Next(MaxWait));\n }\n }\n catch (Exception exception)\n {\n Console.Out.WriteLine(\"Ërror in Method1 Thread {0}\", exception);\n exceptions++;\n }\n finally\n {\n startedThreads--;\n }\n }\n\n private void Method2()\n {\n try\n {\n for (int i = 0; i < Iterations; i++)\n {\n // Stuff being tested\n Thread.Sleep(random.Next(MaxWait));\n }\n }\n catch (Exception exception)\n {\n Console.Out.WriteLine(\"Ërror in Method2 Thread {0}\", exception);\n exceptions++;\n }\n finally\n {\n startedThreads--;\n }\n }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1353085/" ]
352,703
<p>Is it possible to integrate <a href="http://hudson.dev.java.net/" rel="noreferrer" title="hudson: an extensible continuous integration engine">Hudson</a> with MS Test?</p> <p>I am setting up a smaller CI server on my development machine with Hudson right now, just so that I can have some statistics (ie. <a href="http://blogs.msdn.com/fxcop/" rel="noreferrer" title="Code Analysis Team Blog">FxCop</a> and compiler warnings). Of course, it would also be nice if it could just run my unit tests and present their output.</p> <p>Up to now, I have added the following batch task to Hudson, which makes it run the tests properly.</p> <pre><code>"%PROGRAMFILES%\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe" /runconfig:LocalTestRun.testrunconfig /testcontainer:Tests\bin\Debug\Tests.dll </code></pre> <p>However, as far as I know, Hudson does not support analysis of MS Test results, yet. Does anyone know whether the TRX files generated by <code>MSTest.exe</code> can be transformed to the <a href="http://www.junit.org/" rel="noreferrer">JUnit</a> or <a href="http://www.nunit.org/" rel="noreferrer">NUnit</a> result format (because those are supported by Hudson), or whether there is any other way to integrate MS Test unit tests with Hudson?</p>
[ { "answer_id": 459816, "author": "Shawn Miller", "author_id": 247, "author_profile": "https://Stackoverflow.com/users/247", "pm_score": 0, "selected": false, "text": "<Exec Command=\"\"C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\Common7\\IDE\\mstest.exe\" /testcontainer:\"MyAssembly.dll\"\" />\n" }, { "answer_id": 512092, "author": "Allen Rice", "author_id": 49885, "author_profile": "https://Stackoverflow.com/users/49885", "pm_score": 4, "selected": false, "text": "\nSET MSTest=\"C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\MSTest.exe\"\nSET XSLParser=\"C:\\MsBuildNunit\\msxsl.exe\"\n\nSET TestDLL=path-to-your-test-projects.dll\nSET TestOutFILE=TestResults\\some-unique-filename.trx\nSET TransformedOutputFile=%TestOutFILE:.trx=%.xml\nSET XSLFile=c:\\MsBuildNunit\\MSBuild-to-NUnit.xslt\n\nMKDIR TestResults\n\n%MSTest% \"/testcontainer:%TestDLL%\" /nologo /resultsfile:%TestOutFILE% \n\n%XSLParser% %TestOutFILE% %XSLFile% -o %TransformedOutputFile%\n\nSET ERRORLEVEL=0\n TestResults/*.xml" }, { "answer_id": 1088294, "author": "Trinition", "author_id": 133792, "author_profile": "https://Stackoverflow.com/users/133792", "pm_score": 2, "selected": false, "text": "\"%PROGRAMFILES%\\Microsoft Visual Studio 9.0\\Common7\\IDE\\MSTest.exe\" /runconfig:LocalTestRun.testrunconfig /testcontainer:MyProject1.Test/bin/Debug/MyProject1.Test.dll /testcontainer: MyProject2.Test/bin/Debug/MyProject2.Test.dll /resultsfile:TestResults\\HudsonJobTestResults.trx\n TestResults\\HudsonJobTestResults.trx\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11963/" ]
352,720
<p>than just to call the parameter as it is?</p>
[ { "answer_id": 352727, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "this.foo = foo; this.SomeMethod()" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,722
<p>I've got in an ASP.NET application this process :</p> <ul> <li>Start a connection</li> <li>Start a transaction</li> <li>Insert into a table "LoadData" a lot of values with the SqlBulkCopy class with a column that contains a specific LoadId.</li> <li>Call a stored procedure that : <ul> <li>read the table "LoadData" for the specific LoadId.</li> <li>For each line does a lot of calculations which implies reading dozens of tables and write the results into a temporary (#temp) table (process that last several minutes).</li> <li>Deletes the lines in "LoadDate" for the specific LoadId.</li> <li>Once everything is done, write the result in the result table.</li> </ul></li> <li>Commit transaction or rollback if something fails.</li> </ul> <p>My problem is that if I have 2 users that start the process, the second one will have to wait that the previous has finished (because the insert seems to put an exclusive lock on the table) and my application sometimes falls in timeout (and the users are not happy to wait :) ).</p> <p>I'm looking for a way to be able to have the users that does everything in parallel as there is no interaction, except the last one: writing the result. I think that what is blocking me is the inserts / deletes in the "LoadData" table. I checked the other transaction isolation levels but it seems that nothing could help me.</p> <p>What would be perfect would be to be able to remove the exclusive lock on the "LoadData" table (is it possible to force SqlServer to only lock rows and not table ?) when the Insert is finished, but without ending the transaction.</p> <p>Any suggestion?</p>
[ { "answer_id": 352727, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "this.foo = foo; this.SomeMethod()" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28544/" ]
352,752
<p>My application is developped in C++ using Qt and is using signals and slots.</p> <p>Let's say I have the following classes (pseudo-C++ code) :</p> <pre><code>class Ball { Color m_Color; int m_Size; }; class Player { public: setBall(Ball* pBall) { if (pBall != m_pBall) { Ball* pPreviousBall = m_pBall; m_pBall = pBall; emit notifyBallNotUsed(pPreviousBall); } } Ball* getBall(); signals: void notifyBallNotUsed(Ball*); private: String m_Name; Ball* m_pBall; }; class GeneralHandler { public: addBall(Ball* pBall); deleteBall(Ball* pBall); addPlayer(Player* pPlayer) { connect(pPlayer, SIGNAL(notifyBallNotUsed(Ball*)), this, SLOT(onBallUsageChanged(Ball*))); ... } deletePlayer(Player* pPlayer); { disconnect(pPlayer, SIGNAL(notifyBallNotUsed(Ball*)), this, SLOT(onBallUsageChanged(Ball*))); onBallUsageChanged(pPlayer-&gt;getBall()); .... } private slots: void onBallUsageChanged(Ball* pBall) { if (isNotUsedAnymore(pBall)) { m_BallList.remove(pBall); delete pBall; } } private: bool isNotUsedAnymore(Ball* pBall); // Check if the given ball is still used by at least one player List&lt;Player*&gt; m_PlayerList; List&lt;Ball*&gt; m_BallList; }; </code></pre> <p>With my application, the user can add/remove player, and for each player, decide the color and the size of the ball. Behind the hood, the GeneralHandler is in charge to store the balls and delete them. It is perfectly possible that two players are using the same ball.</p> <p>When a player is deleted, if the ball is not used anymore, the GeneralHandler should delete it (or keep it if the ball is still used by another player). If the ball a player is using is changed, the previous ball, if not used anymore, should be deleted by the GeneralHandler as well.</p> <p>So far so good.</p> <p>Now, I want to add undo/redo capability to my application, using the command pattern, and this is where I'm stuck. Lets say I have something like this :</p> <pre><code>class ChangePlayerBall : public QUndoCommand { public: ChangePlayerBall(Player* pPlayer, Ball* pNewBall) { m_pPlayer = pPlayer; } void redo(); void undo(); private: Player* m_pPlayer; }; </code></pre> <p>I guess the redo() method will look like this :</p> <pre><code>void ChangePlayerBall::redo() { m_pPlayer-&gt;setBall(pNewBall); } </code></pre> <p>If nothing else is changed in the code above, the previous Ball will be deleted if not used anymore by other players. This will be a problem when implementing the undo() method : if the previous ball has been deleted, I don't know what was it's characteristics and the undo command won't be able to recreate it. Or maybe I should store the previous ball, but how will the undo/redo command know if this previous ball is still existing or has been deleted by the handler ? Or maybe this mechanism of deleting a ball as soon as it isn't used anymore should be implemented in the undo command ? The problem is that the undo command will have a lot of dependencies on many other classes. The other problem is that this code would be partially duplicated in the DeletePlayer command, which will have to do something similar :</p> <pre><code>class DeletePlayer : public QUndoCommand { public: DeletePlayer(Player* pPlayer); void redo(); void undo(); ... }; </code></pre> <p>I hope my explainations where understandable !</p> <p>How would you solve this problem ? I cannot find a satisfying solution.</p> <p>Thanks !</p>
[ { "answer_id": 370771, "author": "user11323", "author_id": 11323, "author_profile": "https://Stackoverflow.com/users/11323", "pm_score": 1, "selected": false, "text": "s the source of your doubts. Certainly undo() command shouldn't recreate an object nor have it" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2796/" ]
352,758
<p>I have an inherited QTreeWidget (called PackList) class and its parent is a KXmlGuiWindow. How can I access to the parent's slots? </p> <p>I've tried getParent()->mySlot() from the QTreeWidget class but I've got</p> <pre><code>error: no matching function for call to 'PackList::mySlot()' </code></pre> <p>Does anybody know the correct way? Thanks</p>
[ { "answer_id": 352850, "author": "Jérôme", "author_id": 2796, "author_profile": "https://Stackoverflow.com/users/2796", "pm_score": 1, "selected": false, "text": "parentWidget()->a_slot();\n" }, { "answer_id": 358277, "author": "Michael Bishop", "author_id": 45114, "author_profile": "https://Stackoverflow.com/users/45114", "pm_score": 5, "selected": true, "text": "((KXmlGuiWindow*)parentWidget())->mySlot();\n connect( this, SIGNAL(mySignal()), parentWidget(), SLOT(mySlot()) );\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39339/" ]
352,777
<p>Using JDBC (with jt400 driver / connection, naming=system) I'm running these SQL statements:</p> <pre><code>"CREATE ALIAS QTEMP/SOURCETEMP FOR " + library + "/" + file + " (" + member + ")" "SELECT SRCDTA FROM QTEMP/SOURCETEMP" "DROP ALIAS QTEMP/SOURCETEMP" </code></pre> <p>This works. However, when the member String has a . in it this confuses everthing.</p> <p>Is there any way of dealing with this?</p> <p>Thanks.</p>
[ { "answer_id": 352854, "author": "nearly_lunchtime", "author_id": 23447, "author_profile": "https://Stackoverflow.com/users/23447", "pm_score": 2, "selected": false, "text": "member = \"foo.bar\"\n member = \"\\\"FOO.BAR\\\"\"\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29574/" ]
352,780
<p>In what situations should one catch <code>java.lang.Error</code> on an application?</p>
[ { "answer_id": 352793, "author": "tronda", "author_id": 6896, "author_profile": "https://Stackoverflow.com/users/6896", "pm_score": 6, "selected": false, "text": "OutOfMemoryError" }, { "answer_id": 352842, "author": "Yoni Roit", "author_id": 34161, "author_profile": "https://Stackoverflow.com/users/34161", "pm_score": 8, "selected": true, "text": "LinkageError Error OutOfMemoryError" }, { "answer_id": 352860, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 3, "selected": false, "text": "Error Error Error Throwable Error Error VirtualMachineError Error Throwable try-catch Error" }, { "answer_id": 614579, "author": "Horcrux7", "author_id": 12631, "author_profile": "https://Stackoverflow.com/users/12631", "pm_score": 4, "selected": false, "text": "java.lang.Error java.lang.Error ZipError OutOfMemoryError NoClassDefFoundError int length = Integer.parseInt(xyz);\nbyte[] buffer = new byte[length];\n OutOfMemoryError NoClassDefFoundError Throwable" }, { "answer_id": 622098, "author": "Sarmun", "author_id": 70173, "author_profile": "https://Stackoverflow.com/users/70173", "pm_score": 4, "selected": false, "text": "try {\n while (shouldRun()) {\n doSomething();\n }\n}\ncatch (Throwable t) {\n log(t);\n stop();\n System.exit(1);\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35323/" ]
352,790
<pre><code>&lt;xsl:template match="foo"&gt; </code></pre> <p>matches the foo element in the null namespace.</p> <pre><code>&lt;xsl:template match="*"&gt; </code></pre> <p>matches any element in <em>any</em> namespace.</p> <p>I tried:</p> <pre><code>xmlns:null="" ... &lt;xsl:template match="null:*"&gt; </code></pre> <p>but it's illegal to declare a prefix for the null namespace.</p> <p>So how can I match an element with any name in the null namespace?</p>
[ { "answer_id": 352826, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 4, "selected": true, "text": "<xsl:template match='*[namespace-uri() = \"\"]'>\n namespace-uri" }, { "answer_id": 353044, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 2, "selected": false, "text": "*[not(namespace-uri() )]" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31662/" ]
352,806
<p>When I asked for tools to profile Rails apps, someone <a href="https://stackoverflow.com/questions/350470/what-tools-do-you-recommend-to-profile-rails-apps#351842">pointed at DTrace</a>. Since I work on MacOSX stations and deploy on OpenSolaris, it is a valid way to go. But I have little knowledge of DTrace.</p> <p>Besides the usual suspect, Sun DTrace page and the avaliable info there, is there any other killer pointer to learn Dtrace out there?</p>
[ { "answer_id": 352840, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": 2, "selected": false, "text": "truss dtruss /Developer/Applications/Instruments.app" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20875/" ]
352,814
<p>Sql Server 2008 supports spatial data with new geometry and geography UDT's. They both support AsGml() method to serialize data in gml format. However they serialize data into GML3 format. Is there any way to tell it to serialize data into GML2 format?</p>
[ { "answer_id": 496310, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "CustomWriter w = new CustomWriter();\nSqlGeometry.Parse(\"POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))\").Populate(w);\nSystem.Console.WriteLine(w);\n\npublic class CustomWriter : IGeometrySink {\n private StringBuilder _builder = new StringBuilder();\n\n public string ToString() {\n return _builder.ToString();\n }\n\n public void SetSrid(int srid) {\n _builder.Append('@');\n _builder.Append(srid);\n }\n\n public void BeginGeometry(OpenGisGeometryType type) {\n _builder.Append(\" (\");\n _builder.Append(type);\n }\n\n public void BeginFigure(double x, double y, double? z, double? m) {\n _builder.Append(\" [\");\n _builder.Append(x);\n _builder.Append(' ');\n _builder.Append(y);\n }\n\n public void AddLine(double x, double y, double? z, double? m) {\n _builder.Append(',');\n _builder.Append(x);\n _builder.Append(' ');\n _builder.Append(y);\n }\n\n public void EndFigure() {\n _builder.Append(']');\n }\n\n public void EndGeometry() {\n _builder.Append(')');\n }\n}\n // Create \"POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))\" using Builder API\nSqlGeometryBuilder b = new SqlGeometryBuilder();\nb.SetSrid(0);\nb.BeginGeometry(OpenGisGeometryType.Polygon);\n b.BeginFigure(0, 0);\n b.AddLine(10, 0);\n b.AddLine(10, 10);\n b.AddLine(0, 10);\n b.AddLine(0, 0);\n b.EndFigure();\nb.EndGeometry();\nSqlGeometry g = b.ConstructedGeometry;\n" }, { "answer_id": 2194841, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 1, "selected": false, "text": "text ST_AsGML(integer version, geometry g1);" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11525/" ]
352,821
<p>I'm stuck in a battle between ReSharper and StyleCop, and I'd like to let ReSharper win, but I want to hear the arguments in favour of StyleCop before I do that.</p> <p>When I'm writing long argument lists ReSharper sensibly chops the parameter list and restarts it on the next line. I find that much more readable.</p> <p>When I run StyleCop over the code it wants me to leave those lines really long. I don't like that, so I want to ignore that StyleCop rule (SA1115). I can't think of a good reason why SC would want those long lines in the first place &ndash; is it just a case of "we've always done it this way"?</p>
[ { "answer_id": 352858, "author": "J Cooper", "author_id": 38803, "author_profile": "https://Stackoverflow.com/users/38803", "pm_score": 0, "selected": false, "text": "void Foo( int blah\n , string blork\n , ...\n" }, { "answer_id": 1324941, "author": "Jason Evans", "author_id": 127440, "author_profile": "https://Stackoverflow.com/users/127440", "pm_score": 1, "selected": false, "text": "public static string Format<T>(string pattern, T template)\n{\n Dictionary<string, string> cache = new Dictionary<string, string>();\n\n return RegexExpression.Replace(\n pattern, \n match =>\n {\n string key = match.Groups[1].Value;\n string value;\n\n if (!cache.TryGetValue(key, out value))\n {\n var prop = typeof(T).GetProperty(key);\n\n if (prop == null)\n {\n throw new ArgumentException(\"Not found: \" + key, \"pattern\");\n }\n\n value = Convert.ToString(prop.GetValue(template, null));\n cache.Add(key, value);\n }\n\n return value;\n });\n}\n" }, { "answer_id": 4053858, "author": "Jason Allor", "author_id": 491508, "author_profile": "https://Stackoverflow.com/users/491508", "pm_score": 3, "selected": false, "text": "public void MyMethod(int param1, int param2, int param3)\n\npublic void MyMethod(\n int param1, int param2, int param3)\n\npublic void MyMethod(\n int param1,\n int param2,\n int param3)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
352,832
<p>May be my title is not clear. I am looking for some kind of version control on database tables, like subversion does on files, like wiki does.</p> <p>I want to trace the changes log. I want to extract and run the diff in reverse. (undo like a "svn merge -r 101:100"). I may need a indexed search on the history.</p> <p>I've read the "<a href="https://stackoverflow.com/questions/49755/design-pattern-for-undo-engine">Design Pattern for Undo Engine</a>", but it is related to "Patterns". Are there anything I could reuse without reinvent the wheel?</p> <p><strong>EDIT:</strong> For example, bank account transactions. I have column "balance"(and others) updated in table. a user will find a mistake by him 10 days later, and he will want to cancel/rollback the specific transaction, without changing others.</p> <p>How can I do it gracefully in the application level?</p>
[ { "answer_id": 353170, "author": "JWD", "author_id": 39365, "author_profile": "https://Stackoverflow.com/users/39365", "pm_score": 2, "selected": false, "text": "[ID] [Revision Date] [Revision Status] [Modified By] [Balance]\n1 1-1-2008 Expired User1 $100\n1 1-2-2008 Expired User2 $200\n2 1-2-2008 Approved User3 $300\n1 1-3-2008 Approved User1 $250\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40214/" ]
352,837
<p>This is a question regarding Unix shell scripting (any shell), but any other &quot;standard&quot; scripting language solution would also be appreciated:</p> <p>I have a directory full of files where the filenames are hash values like this:</p> <pre><code>fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee </code></pre> <p>These files have different original file types such as png, zip, doc, pdf etc.</p> <p>Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the <code>file</code> command?</p> <h2>Answer:</h2> <p><a href="https://stackoverflow.com/questions/352837/how-to-add-file-extensions-based-on-file-type-on-linuxunix#352973">J.F. Sebastian's</a> script will work for both ouput of the filenames as well as the actual renaming.</p>
[ { "answer_id": 352846, "author": "csl", "author_id": 21028, "author_profile": "https://Stackoverflow.com/users/21028", "pm_score": 4, "selected": false, "text": "file -i filename\n" }, { "answer_id": 352919, "author": "Phil H", "author_id": 36537, "author_profile": "https://Stackoverflow.com/users/36537", "pm_score": 3, "selected": false, "text": "file -i filename\n file -i filename ls | while read f; do mv \"$f\" \"$f\".`file -i \"$f\" | get_extension.py`; done\n for f in * ls | while read f" }, { "answer_id": 352973, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 5, "selected": true, "text": "#!/usr/bin/env python\n\"\"\"It is a `filename -> filename.ext` filter. \n\n `ext` is mime-based.\n\n\"\"\"\nimport fileinput\nimport mimetypes\nimport os\nimport sys\nfrom subprocess import Popen, PIPE\n\nif len(sys.argv) > 1 and sys.argv[1] == '--rename':\n do_rename = True\n del sys.argv[1]\nelse:\n do_rename = False \n\nfor filename in (line.rstrip() for line in fileinput.input()):\n output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()\n mime = output.split(';', 1)[0].lower().strip()\n ext = mimetypes.guess_extension(mime, strict=False)\n if ext is None:\n ext = os.path.extsep + 'undefined'\n filename_ext = filename + ext\n print filename_ext\n if do_rename:\n os.rename(filename, filename_ext)\n #!/usr/bin/env python\n\"\"\"It is a `filename -> filename.ext` filter. \n\n `ext` is mime-based.\n\"\"\"\n# Mapping of mime-types to extensions is taken form here:\n# http://as3corelib.googlecode.com/svn/trunk/src/com/adobe/net/MimeTypeMap.as\nmime2exts_list = [\n [\"application/andrew-inset\",\"ez\"],\n [\"application/atom+xml\",\"atom\"],\n [\"application/mac-binhex40\",\"hqx\"],\n [\"application/mac-compactpro\",\"cpt\"],\n [\"application/mathml+xml\",\"mathml\"],\n [\"application/msword\",\"doc\"],\n [\"application/octet-stream\",\"bin\",\"dms\",\"lha\",\"lzh\",\"exe\",\"class\",\"so\",\"dll\",\"dmg\"],\n [\"application/oda\",\"oda\"],\n [\"application/ogg\",\"ogg\"],\n [\"application/pdf\",\"pdf\"],\n [\"application/postscript\",\"ai\",\"eps\",\"ps\"],\n [\"application/rdf+xml\",\"rdf\"],\n [\"application/smil\",\"smi\",\"smil\"],\n [\"application/srgs\",\"gram\"],\n [\"application/srgs+xml\",\"grxml\"],\n [\"application/vnd.adobe.apollo-application-installer-package+zip\",\"air\"],\n [\"application/vnd.mif\",\"mif\"],\n [\"application/vnd.mozilla.xul+xml\",\"xul\"],\n [\"application/vnd.ms-excel\",\"xls\"],\n [\"application/vnd.ms-powerpoint\",\"ppt\"],\n [\"application/vnd.rn-realmedia\",\"rm\"],\n [\"application/vnd.wap.wbxml\",\"wbxml\"],\n [\"application/vnd.wap.wmlc\",\"wmlc\"],\n [\"application/vnd.wap.wmlscriptc\",\"wmlsc\"],\n [\"application/voicexml+xml\",\"vxml\"],\n [\"application/x-bcpio\",\"bcpio\"],\n [\"application/x-cdlink\",\"vcd\"],\n [\"application/x-chess-pgn\",\"pgn\"],\n [\"application/x-cpio\",\"cpio\"],\n [\"application/x-csh\",\"csh\"],\n [\"application/x-director\",\"dcr\",\"dir\",\"dxr\"],\n [\"application/x-dvi\",\"dvi\"],\n [\"application/x-futuresplash\",\"spl\"],\n [\"application/x-gtar\",\"gtar\"],\n [\"application/x-hdf\",\"hdf\"],\n [\"application/x-javascript\",\"js\"],\n [\"application/x-koan\",\"skp\",\"skd\",\"skt\",\"skm\"],\n [\"application/x-latex\",\"latex\"],\n [\"application/x-netcdf\",\"nc\",\"cdf\"],\n [\"application/x-sh\",\"sh\"],\n [\"application/x-shar\",\"shar\"],\n [\"application/x-shockwave-flash\",\"swf\"],\n [\"application/x-stuffit\",\"sit\"],\n [\"application/x-sv4cpio\",\"sv4cpio\"],\n [\"application/x-sv4crc\",\"sv4crc\"],\n [\"application/x-tar\",\"tar\"],\n [\"application/x-tcl\",\"tcl\"],\n [\"application/x-tex\",\"tex\"],\n [\"application/x-texinfo\",\"texinfo\",\"texi\"],\n [\"application/x-troff\",\"t\",\"tr\",\"roff\"],\n [\"application/x-troff-man\",\"man\"],\n [\"application/x-troff-me\",\"me\"],\n [\"application/x-troff-ms\",\"ms\"],\n [\"application/x-ustar\",\"ustar\"],\n [\"application/x-wais-source\",\"src\"],\n [\"application/xhtml+xml\",\"xhtml\",\"xht\"],\n [\"application/xml\",\"xml\",\"xsl\"],\n [\"application/xml-dtd\",\"dtd\"],\n [\"application/xslt+xml\",\"xslt\"],\n [\"application/zip\",\"zip\"],\n [\"audio/basic\",\"au\",\"snd\"],\n [\"audio/midi\",\"mid\",\"midi\",\"kar\"],\n [\"audio/mpeg\",\"mp3\",\"mpga\",\"mp2\"],\n [\"audio/x-aiff\",\"aif\",\"aiff\",\"aifc\"],\n [\"audio/x-mpegurl\",\"m3u\"],\n [\"audio/x-pn-realaudio\",\"ram\",\"ra\"],\n [\"audio/x-wav\",\"wav\"],\n [\"chemical/x-pdb\",\"pdb\"],\n [\"chemical/x-xyz\",\"xyz\"],\n [\"image/bmp\",\"bmp\"],\n [\"image/cgm\",\"cgm\"],\n [\"image/gif\",\"gif\"],\n [\"image/ief\",\"ief\"],\n [\"image/jpeg\",\"jpg\",\"jpeg\",\"jpe\"],\n [\"image/png\",\"png\"],\n [\"image/svg+xml\",\"svg\"],\n [\"image/tiff\",\"tiff\",\"tif\"],\n [\"image/vnd.djvu\",\"djvu\",\"djv\"],\n [\"image/vnd.wap.wbmp\",\"wbmp\"],\n [\"image/x-cmu-raster\",\"ras\"],\n [\"image/x-icon\",\"ico\"],\n [\"image/x-portable-anymap\",\"pnm\"],\n [\"image/x-portable-bitmap\",\"pbm\"],\n [\"image/x-portable-graymap\",\"pgm\"],\n [\"image/x-portable-pixmap\",\"ppm\"],\n [\"image/x-rgb\",\"rgb\"],\n [\"image/x-xbitmap\",\"xbm\"],\n [\"image/x-xpixmap\",\"xpm\"],\n [\"image/x-xwindowdump\",\"xwd\"],\n [\"model/iges\",\"igs\",\"iges\"],\n [\"model/mesh\",\"msh\",\"mesh\",\"silo\"],\n [\"model/vrml\",\"wrl\",\"vrml\"],\n [\"text/calendar\",\"ics\",\"ifb\"],\n [\"text/css\",\"css\"],\n [\"text/html\",\"html\",\"htm\"],\n [\"text/plain\",\"txt\",\"asc\"],\n [\"text/richtext\",\"rtx\"],\n [\"text/rtf\",\"rtf\"],\n [\"text/sgml\",\"sgml\",\"sgm\"],\n [\"text/tab-separated-values\",\"tsv\"],\n [\"text/vnd.wap.wml\",\"wml\"],\n [\"text/vnd.wap.wmlscript\",\"wmls\"],\n [\"text/x-setext\",\"etx\"],\n [\"video/mpeg\",\"mpg\",\"mpeg\",\"mpe\"],\n [\"video/quicktime\",\"mov\",\"qt\"],\n [\"video/vnd.mpegurl\",\"m4u\",\"mxu\"],\n [\"video/x-flv\",\"flv\"],\n [\"video/x-msvideo\",\"avi\"],\n [\"video/x-sgi-movie\",\"movie\"],\n [\"x-conference/x-cooltalk\",\"ice\"]]\n\n#NOTE: take only the first extension\nmime2ext = dict(x[:2] for x in mime2exts_list)\n\nif __name__ == '__main__':\n import fileinput, os.path\n from subprocess import Popen, PIPE\n\n for filename in (line.rstrip() for line in fileinput.input()):\n output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()\n mime = output.split(';', 1)[0].lower().strip()\n print filename + os.path.extsep + mime2ext.get(mime, 'undefined')\n #NOTE: take only the first extension\nmime2ext = {}\nfor x in mime2exts_list:\n mime2ext[x[0]] = x[1]\n\nif __name__ == '__main__':\n import os\n import sys\n\n # this version supports only stdin (part of fileinput.input() functionality)\n lines = sys.stdin.read().split('\\n')\n for line in lines:\n filename = line.rstrip()\n output = os.popen('file -bi ' + filename).read() \n mime = output.split(';')[0].lower().strip()\n try: ext = mime2ext[mime]\n except KeyError:\n ext = 'undefined'\n print filename + '.' + ext\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5949/" ]
352,839
<p>I need to create a DHTML menu with the specified features, but I can't figure out how to do it. Here's what I need:</p> <p>All items are layed out horizontally. If they would be wider than the screen, two little arrows appear on the right side of the menu that allow to scroll it. Something like this:</p> <pre><code>+--------+--------+-------+---+---+ | Item 1 | Item 2 | Item 3| &lt; | &gt; | +--------+--------+-------+---+---+ </code></pre> <p>Menu items should be clickable anywhere in the cell. They should stretch both vertically and horizontally to the contents. The text in the items should be centered both vertically and horizontally. The menu should work in IE7/Opera/FF/Safari.</p> <p>The scrolling is the easy part - I just place it all in a container (say, a <code>&lt;div&gt;</code>), set the container to <code>overflow: hidden</code> and then play around in Javascript with <code>clientWidth</code>, <code>scrollWidth</code> and <code>scrollLeft</code>. That I've figured out and have already tried.</p> <p>But how to make the menu items so stretchy, clickable anywhere and centered text?</p>
[ { "answer_id": 352859, "author": "Chris Van Opstal", "author_id": 7264, "author_profile": "https://Stackoverflow.com/users/7264", "pm_score": 2, "selected": false, "text": "#menu {\n display: table; \n} \n#menu a {\n display:table-cell; \n vertical-align:middle;\n}\n <div id=\"menu\">\n <a href=\"#\">normal text</a>\n <a href=\"#\"><big>large text</big></a>\n <a href=\"#\"><span style=\"line-height:100px;\">very tall text</span></a>\n</div>\n" }, { "answer_id": 352869, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": -1, "selected": false, "text": "<ul id=\"menu\"><li class=\"item\" onclick=\"foo()\" style=\"cursor:pointer; cursor:hand; padding:1em; margin:1px; float: left;\">FOO!</li></ul>\n" }, { "answer_id": 353067, "author": "Vilx-", "author_id": 41360, "author_profile": "https://Stackoverflow.com/users/41360", "pm_score": 2, "selected": true, "text": "<a> <table>" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41360/" ]
352,899
<p>Is Structured Exception Handling bad? What is the right way to handle exceptions?</p> <p><strong>EDIT: Exception Handling in .NET using C#.</strong></p> <p>I usually have a set of specific exception classes (DivideByZeroException, ArrayTypeMismatchException) and don't have a generic "catch (Exception ex)".</p> <p>The thinking behind this is that I expect certain types of exceptions to occur and have specific actions defined when they occur and the unexpected exceptions would rise up the the interface (either windows or web). Is this a good practice? </p>
[ { "answer_id": 352937, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 3, "selected": false, "text": "try {\n ...\n}\ncatch (Exception e) {\n //TODO: handle this later\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1443363/" ]
352,906
<h2>Scenario</h2> <p>You've got several bug reports all showing the same problem. They're all cryptic with similar tales of how the problem occurred. You follow the steps but it doesn't reliably reproduce the problem. After some investigation and web searching, you suspect what might be going on and you are pretty sure you can fix it.</p> <h2>Problem</h2> <p>Unfortunately, without a reliable way to reproduce the original problem, you can't verify that it actually fixes the issue rather than having no effect at all or exacerbating and masking the real problem. You could just not fix it until it becomes reproducible every time, but it's a big bug and not fixing it would cause your users a lot of other problems.</p> <h2>Question</h2> <p>How do you go about verifying your change?</p> <p>I think this is a very familiar scenario to anyone who has engineered software, so I'm sure there are a plethora of approaches and best practices to tackling bugs like this. We are currently looking at one of these problems on our project where I have spent some time determining the issue but have been unable to confirm my suspicions. A colleague is soak-testing my fix in the hopes that "a day of running without a crash" equates to "it's fixed". However, I'd prefer a more reliable approach and I figured there's a wealth of experience here on SO.</p>
[ { "answer_id": 353568, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "const int NITER = 1000;\nint thread_unsafe_count = 0;\nint thread_unsafe_tracker = 0;\n\nvoid* thread_unsafe_plus(void *a){\n int i, local;\n thread_unsafe_tracker++;\n for (i=0; i<NITER; i++){\n local = thread_unsafe_count;\n local++;\n thread_unsafe_count+=local;\n };\n}\nvoid* thread_unsafe_minus(void *a){\n int i, local;\n thread_unsafe_tracker--;\n for (i=0; i<NITER; i++){\n local = thread_unsafe_count;\n local--;\n thread_unsafe_count+=local;\n };\n}\n pthread_t th1, th2;\npthread_create(&th1,NULL,&thread_unsafe_plus,NULL);\npthread_create(&th2,NULL,&thread_unsafe_minus,NULL);\npthread_join(th1,NULL);\npthread_join(th2,NULL);\nif (thread_unsafe_count != 0) {\n printf(\"Ah ha!\\n\");\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23234/" ]
352,925
<p>I have a little project with some jsp deployed on an Tomcat 5.5. Recently the Servlets which are also deployed with the jsp files (one war archive) stopped working. I also checked out a previous version from my svn which should work. What I noticed that the <code>displayname</code> (I use a german version of Tomcat , so I guess that is how I would translate it, the name in the second column in the Tomcat manager) disappeared. I use Eclipse Ganymede on vista. Tomcat is running on Debian. A local Tomcat shows the same behavior. Hope someone have an idea. Thanks.</p>
[ { "answer_id": 352960, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 5, "selected": true, "text": "<display-name> web.xml /WEB-INF/web.xml" }, { "answer_id": 38151569, "author": "MonoThreaded", "author_id": 294702, "author_profile": "https://Stackoverflow.com/users/294702", "pm_score": 3, "selected": false, "text": "<web-app blahblah>\n <display-name>**This**</display-name>\n <servlet>\n <servlet-name>Not this</servlet-name>\n </servlet>\n</web-app>\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38721/" ]
352,949
<p>I've got two tables that need to be joined via LINQ, but they live in different databases. Right now I'm returning the results of one table, then looping through and retrieving the results of the other, which as you can guess isn't terribly efficient. Is there any way to get them into a single LINQ statement? Is there any other way to construct this to avoid the looping? I'm just looking for ideas, in case I'm overlooking something.</p> <p>Note that I can't alter the databases, i.e. I can't create a view in one that references the other. Something I haven't tried yet is creating views in a third database that references both tables. Any ideas welcome.</p>
[ { "answer_id": 353106, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 6, "selected": true, "text": "<Table Name=\"dbo.Customers\" Member=\"Customers\">\n <Table Name=\"SomeOtherDatabase.dbo.Customers\" Member=\"Customers\">\n<Table Name=\"SomeOtherServer.SomeOtherDatabase.dbo.Customers\" Member=\"Customers\">\n SELECT SomeColumn\nFROM OtherServer.OtherDatabase.dbo.SomeTable\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23935/" ]
352,952
<p>I have a web service which returns tab delimited data (see sample below).</p> <p>I need to parse this into an array or similar so I can create a navigation view of it.</p> <p>I've managed to perform the web request and could parse an XML file, but my knowledge of Objective-C is small.</p> <pre><code>433 Eat 502 Not Fussed 442 British 443 Chinese 444 Dim Sum 445 Fish 446 French 447 Gastropubs 449 Indian 451 Italian 452 Japanese 453 Middle Eastern 454 Pan-Asian 455 Pizza 456 Spanish 457 Tapas 458 Thai 459 Vegetarian 434 Drink 501 Not Fussed 460 Bars 461 Pubs </code></pre>
[ { "answer_id": 353483, "author": "Brett", "author_id": 37848, "author_profile": "https://Stackoverflow.com/users/37848", "pm_score": 3, "selected": false, "text": "with - (NSArray *)componentsSeparatedByString:(NSString *)separator NSArray *components = [myString componentsSeperatedByString:@\"\\t\"];\n NSArray NSStrings - (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator NSString" }, { "answer_id": 353531, "author": "Brett", "author_id": 37848, "author_profile": "https://Stackoverflow.com/users/37848", "pm_score": 2, "selected": false, "text": "NSArray *lines = [data componentsSeparatedByString:@\"\\n\"];\nfor (NSString *line in lines) {\n NSArray *fields = [line componentsSeparatedByString:@\"\\t\"];\n // Do something here with each two-element array, such as add to an NSDictionary or to an NSArray (to make a multidimensional array.)\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258/" ]
352,954
<p>Im using asynchronous threading in my application WITH httpClient. I make a call using the Future Api like so </p> <pre><code>mStrResults = (String) rssFuture.get(); </code></pre> <p>this call attempts to retrieve an html string returned from my Callable httpClient call() method.</p> <p>What i want to do however is ensure that the get method does not wait too long while executing the call() method. Should i pass a timeout parameter when calling rssFuture.get() or is it ok to just surround with a InterruptedException catch block?</p> <p>Also is there a default time which the asynchronous thread will wait before throwing an InterruptedException and if so can i set a custom value?</p>
[ { "answer_id": 353483, "author": "Brett", "author_id": 37848, "author_profile": "https://Stackoverflow.com/users/37848", "pm_score": 3, "selected": false, "text": "with - (NSArray *)componentsSeparatedByString:(NSString *)separator NSArray *components = [myString componentsSeperatedByString:@\"\\t\"];\n NSArray NSStrings - (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator NSString" }, { "answer_id": 353531, "author": "Brett", "author_id": 37848, "author_profile": "https://Stackoverflow.com/users/37848", "pm_score": 2, "selected": false, "text": "NSArray *lines = [data componentsSeparatedByString:@\"\\n\"];\nfor (NSString *line in lines) {\n NSArray *fields = [line componentsSeparatedByString:@\"\\t\"];\n // Do something here with each two-element array, such as add to an NSDictionary or to an NSArray (to make a multidimensional array.)\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24481/" ]
352,958
<p>I'd like to do something like the following in C#:</p> <pre><code> class Container { //... public void ForEach(Action method) { foreach (MyClass myObj in sequence) myObj.method(); } } //... containerObj.ForEach(MyClass.Method); </code></pre> <p>In C++ I would use something like std::mem_fun. How would I do it in C#?</p>
[ { "answer_id": 352981, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": " public void ForEach(Action method) {\n foreach (MyClass myObj in sequence) method(myObj);\n" }, { "answer_id": 353018, "author": "jlew", "author_id": 7450, "author_profile": "https://Stackoverflow.com/users/7450", "pm_score": 3, "selected": true, "text": "class Container \n{ \n//... \npublic void ForEach(Action<MyObj> method) \n{ \n foreach (MyClass myObj in sequence) method(myObj); \n} \n} \n\n//... containerObj.ForEach( myobj => myObj.Method() );\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44615/" ]
352,991
<p>How can I do for inserting a Default Value into a column of a table in Access? I use this instruction:</p> <pre><code>ALTER TABLE Tabella ADD Campo Double DEFAULT 0 ALTER TABLE Tabella ADD Campo Double DEFAULT (0) ALTER TABLE Tabella ADD Campo DEFAULT 0 ALTER TABLE Tabella ADD Campo DEFAULT (0) ALTER TABLE Tabella ADD Campo SET DEFAULT 0 ALTER TABLE Tabella ADD Campo SET DEFAULT (0) </code></pre> <p>but all of these cause error. How can I do for doing it?</p>
[ { "answer_id": 353047, "author": "Tiberiu Ana", "author_id": 38567, "author_profile": "https://Stackoverflow.com/users/38567", "pm_score": 0, "selected": false, "text": "alter table Tabella alter column Campo Double DEFAULT 0\n" }, { "answer_id": 353130, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "Public Function addNewField( _\n m_tableName as string, _\n m_fieldName As String, _\n m_fieldType As Long, _ 'check syntax of .createField method for values'\n m_fieldLength As Long, _ 'check syntax of .createField method for values'\n Optional m_defaultValue As Variant = Null)\n\nDim myTable As DAO.TableDef\nDim myField As DAO.Field\n\nOn Error GoTo addNewField_error\n\nSet myTable = currentDb.TableDefs(m_tableName)\nSet myField = myTable.CreateField(m_fieldName, m_fieldType, m_fieldLength)\n\nIf Not IsNull(m_defaultValue) Then\n myField.DefaultValue = m_defaultValue\nEnd If\n\nmyTable.Fields.Append myField\n\nSet myTable = Nothing\nSet myField = Nothing\n\nExit Function\n\naddNewField_error:\nIf Err.Number = 3191 Or Err.Number = 3211 Then\n 'The field already exists or the table is opened'\n 'nothing to do but exit the function'\nElse\n debug.print Err.Number & \" - \" & Error$\nEnd If\n\nEnd Function\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,997
<p>I would appreciate your opinion/advice on the following</p> <p><strong>Scenario</strong> </p> <p>HTML has PDF file nick name, back end has URL for each nick. </p> <p>The link URL is always <code>download.php?what=%PDF_Nick%</code> to ensure download for JS disabled clients. </p> <p>For JS enabled clients I do JQuery AJAX call and rewrite link URL from <code>download.php?what=%PDF_Nick%</code> to <a href="http://examplesite.com/requestedPFF.pdf" rel="nofollow noreferrer">http://examplesite.com/requestedPFF.pdf</a> to activate download from the client. I set <code>"async: false"</code> to allow AJAX get new url.</p> <p><strong>Problem</strong></p> <p>AJAX returns valid script rewriting JS url variable, but <code>location.href</code> runs again to the initial url, creating extra back end call</p> <p>Do you think it's related to the bug ignoring <code>"async: false,"</code> definition or it's mistake I've made and missed to catch?</p> <p>Thank you in advance</p> <h1>HTML code</h1> <pre><code> &lt;a href="/download.php?what=PDF_A" onclick="javascript:download ('PDF_A')"&gt;Download&lt;/a&gt; </code></pre> <h1>JS code</h1> <pre><code>function download ( what ) { var url = "download.php?what="+what; $.ajax({ type: "GET", url: "download.php?ajax=true", data: "what=" + what async: false, dataType: "script" }); // if AJAX got the download URL I expect actual download to start: location.href = url; } </code></pre> <h1>Back end (download.php) code</h1> <pre><code>$myPDF = array(); $myPDF["PDF_A"] = "PDF_A.pdf"; .... $url = "http://examplesite.com/" . $myPDF["PDF_A"]; ... if ( $_GET["ajax"] === "true" ) { // overwrite JS url variable print('url = "'.$url.'";'); } else { header("Location: ". $url ); header("Connection: close"); } </code></pre>
[ { "answer_id": 353027, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 2, "selected": false, "text": "$.ajax({\n type: \"GET\",\n url: \"download.php?ajax=true\",\n data: \"what=\" + what,\n dataType: \"script\",\n success: function(msg) {\n location.href = url;\n }\n});\n" }, { "answer_id": 353116, "author": "powtac", "author_id": 22470, "author_profile": "https://Stackoverflow.com/users/22470", "pm_score": 2, "selected": false, "text": "var html = $.ajax({\n url: \"some.php\",\n async: false\n}).responseText;\n function download ( what ) {\n var url = \"download.php?what=\"+what;\n\n location.href = $.ajax({\n type: \"GET\",\n url: \"download.php?ajax=true\",\n data: \"what=\" + what\n async: false,\n dataType: \"script\"\n }).responseText;\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
353,013
<p>I'm trying to abstract out all database code into a separate library and then use that library in all my code. All database connections are done using typed TableAdapters that I create by dragging and dropping in datasets in VS2005, using a connection string from the appSettings.</p> <p>The problem that I haven't been able to solve is that .Net doesn't propagate the libraries appSettings to the other project that's using it.</p> <p>In short, I have a database layer library, MyProgram.DbLayer, which is used by other projects such as MyProgram.Client etc. When I had all the datasets in the .Client the connectionString was in MyProgram.Client.exe.config so that I could change it after build. When I moved it into the MyProgram.DbLayer that setting isn't avaliable to me after I build the binaries.</p> <p>EDIT: This seems to be a more general issue with ApplicationSettings.</p> <p>What I noticed was that if I manually add a setting only used in a library it will be properly read. The only thing I need now is for the setting to be automatically included in the .config file as well.</p>
[ { "answer_id": 353027, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 2, "selected": false, "text": "$.ajax({\n type: \"GET\",\n url: \"download.php?ajax=true\",\n data: \"what=\" + what,\n dataType: \"script\",\n success: function(msg) {\n location.href = url;\n }\n});\n" }, { "answer_id": 353116, "author": "powtac", "author_id": 22470, "author_profile": "https://Stackoverflow.com/users/22470", "pm_score": 2, "selected": false, "text": "var html = $.ajax({\n url: \"some.php\",\n async: false\n}).responseText;\n function download ( what ) {\n var url = \"download.php?what=\"+what;\n\n location.href = $.ajax({\n type: \"GET\",\n url: \"download.php?ajax=true\",\n data: \"what=\" + what\n async: false,\n dataType: \"script\"\n }).responseText;\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2973/" ]
353,014
<p>I've been doing a <code>convert(varchar,datefield,112)</code> on each date field that I'm using in 'between' queries in SQL server to ensure that I'm only accounting for dates and not missing any based on the time part of datetime fields.</p> <p>Now, I'm hearing that the converts aren't indexable and that there are better methods, in SQL Server 2005, to compare the date part of datetimes in a query to determine if dates fall in a range.</p> <p>What is the optimal, indexable, method of doing something like this:</p> <pre><code>select * from appointments where appointmentDate&gt;='08-01-2008' and appointmentDate&lt;'08-15-2008' </code></pre>
[ { "answer_id": 353045, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 2, "selected": false, "text": "select * from appointments where appointmentdate between \n'08/01/2008' AND '08/16/2008'\n" }, { "answer_id": 353049, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 6, "selected": false, "text": " DateAdd(day, datediff(day,0, MydateValue), 0)\n Where MyDateTimeColumn > DateAdd(day, \n datediff(day,0, @MydateParameter), 0) -- SARG-able\n Where DateAdd(day, datediff(day,0, \n MyDateTimeColumn ), 0) > @MydateParameter -- Not SARG-able\n `Declare @Dt DateTime Set @Dt = getdate() \n Set @Dt = @Dt + 1.0/24 -- Adds one hour \n Select @Dt \n Set @Dt = @Dt - .25 -- Moves back 6 hours \n Select @Dt`\n" }, { "answer_id": 353063, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 4, "selected": true, "text": "select * from appointments where appointmentDate>='08-01-2008' and appointmentDate<'08-15-2008'\n select * from appointments where appointmentDate>='08-01-2008' and appointmentDate<='08-14-2008 23:59:59.996'\n" }, { "answer_id": 7583223, "author": "Mladen Mihajlovic", "author_id": 11421, "author_profile": "https://Stackoverflow.com/users/11421", "pm_score": 0, "selected": false, "text": "SELECT CAST(FLOOR(CAST( getdate() AS float )) AS datetime)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335036/" ]
353,019
<p>I have a query that runs super fast when executed in the sql editor (oracle): 1ms.</p> <p>The same query (as stored procedure) when executed by a DataSet-TableAdapter takes 2 seconds. I'm just retrieving 20rows.</p> <p>Since I'm using a TableAdapter, the return values are stored in a ref cursor.</p> <p>If I was fetching 2'000 rows I could understand that some time is needed to build the DataSet, but 2 seconds for only 20 rows seems too much for me.</p> <p>There is a better way to execute SP on oracle or this is the only way? What could I try to do to improve the performances?</p> <p>Thanks for your help!</p> <hr> <p>Searching in google, it seems that the problem is with the refcursor. Others people faced the same performance issue, but no solution is provided.</p>
[ { "answer_id": 355364, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 0, "selected": false, "text": "CommandType CommandType.StoredProcedure OracleCommand cmd = new OracleCommand();\ncmd.Connection = conn;\ncmd.CommandText = \"COUNT_JOB_HISTORY\";\ncmd.CommandType = CommandType.StoredProcedure;\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1812/" ]
353,020
<p>I would need to create a temp table for paging purposes. I would be selecting all records into a temp table and then do further processing with it.</p> <p>I am wondering which of the following is a better approach:</p> <p>1) Select all the columns of my Primary Table into the Temp Table and then being able to select the rows I would need</p> <p>OR</p> <p>2) Select only the primary key of the Primary Table into the Temp Table and then joining with the Primary Table later on?</p> <p>Is there any size consideration when working with approach 1 versus approach 2?</p> <p>[EDIT]</p> <p>I am asking because I would have done the first approach but looking at PROCEDURE [dbo].[aspnet_Membership_FindUsersByName], that was included with ASP.NET Membership, they are doing Approach 2</p> <p>[EDIT2]</p> <p>With people without access to the Stored procedure:</p> <pre><code> -- Insert into our temp table INSERT INTO #PageIndexForUsers (UserId) SELECT u.UserId FROM dbo.aspnet_Users u, dbo.aspnet_Membership m WHERE u.ApplicationId = @ApplicationId AND m.UserId = u.UserId AND u.LoweredUserName LIKE LOWER(@UserNameToMatch) ORDER BY u.UserName SELECT u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved, m.CreateDate, m.LastLoginDate, u.LastActivityDate, m.LastPasswordChangedDate, u.UserId, m.IsLockedOut, m.LastLockoutDate FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, #PageIndexForUsers p WHERE u.UserId = p.UserId AND u.UserId = m.UserId AND p.IndexId &gt;= @PageLowerBound AND p.IndexId &lt;= @PageUpperBound ORDER BY u.UserName </code></pre>
[ { "answer_id": 353182, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "Where RowNum Between ((PageNumber-1) * PageSize) + 1 And PageNumber * PageSize\n" }, { "answer_id": 1102595, "author": "super9", "author_id": 131238, "author_profile": "https://Stackoverflow.com/users/131238", "pm_score": 0, "selected": false, "text": "CREATE PROC GetPagedEmployees (@NumbersOnPage INT=25,@PageNumb INT = 1)\nAS BEGIN\n\nWITH AllEmployees AS\n(SELECT ROW_NUMBER() OVER (Order by [Person].[Contact].[LastName]) AS RowID,\n[FirstName],[MiddleName],[LastName],[EmailAddress] FROM [Person].[Contact])\n\nSELECT [FirstName],[MiddleName],[LastName],[EmailAddress]\nFROM AllEmployees WHERE RowID BETWEEN\n((@PageNumb - 1) * @NumbersOnPage) + 1 AND @PageNumb * NumbersOnPage\nORDER BY RowID\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
353,039
<p>I'm writing some code to scale a 32 bit RGBA image in C/C++. I have written a few attempts that have been somewhat successful, but they're slow and most importantly the quality of the sized image is not acceptable. </p> <p>I compared the same image scaled by OpenGL (i.e. my video card) and my routine and it's miles apart in quality. I've Google Code Searched, scoured source trees of anything I thought would shed some light (SDL, Allegro, wxWidgets, CxImage, GD, ImageMagick, etc.) but usually their code is either convoluted and scattered all over the place or riddled with assembler and little or no comments. I've also read multiple articles on Wikipedia and elsewhere, and I'm just not finding a clear explanation of what I need. I understand the basic concepts of interpolation and sampling, but I'm struggling to get the algorithm right. I do NOT want to rely on an external library for one routine and have to convert to their image format and back. Besides, I'd like to know how to do it myself anyway. :)</p> <p>I have seen a similar question asked on stack overflow before, but it wasn't really answered in this way, but I'm hoping there's someone out there who can help nudge me in the right direction. Maybe point me to some articles or pseudo code... anything to help me learn and do.</p> <p>Here's what I'm looking for:</p> <ol> <li>No assembler (I'm writing very portable code for multiple processor types).</li> <li>No dependencies on external libraries.</li> <li>I am primarily concerned with scaling DOWN, but will also need to write a scale up routine later.</li> <li>Quality of the result and clarity of the algorithm is most important (I can optimize it later).</li> </ol> <p>My routine essentially takes the following form:</p> <pre><code>DrawScaled(uint32 *src, uint32 *dst, src_x, src_y, src_w, src_h, dst_x, dst_y, dst_w, dst_h ); </code></pre> <p>Thanks!</p> <p><strong>UPDATE:</strong> To clarify, I need something more advanced than a box resample for downscaling which blurs the image too much. I suspect what I want is some kind of bicubic (or other) filter that is somewhat the reverse to a bicubic upscaling algorithm (i.e. each destination pixel is computed from all contributing source pixels combined with a weighting algorithm that keeps things sharp.</p> <h2>Example</h2> <p>Here's an example of what I'm getting from the wxWidgets BoxResample algorithm vs. what I want on a 256x256 bitmap scaled to 55x55.</p> <ul> <li>www.free_image_hosting.net/uploads/1a25434e0b.png</li> </ul> <p>And finally: </p> <ul> <li>www.free_image_hosting.net/uploads/eec3065e2f.png</li> </ul> <p>the original 256x256 image</p>
[ { "answer_id": 353189, "author": "berlindev", "author_id": 44276, "author_profile": "https://Stackoverflow.com/users/44276", "pm_score": 1, "selected": false, "text": "\nint enlarge_or_reduce(imgdes *image1)\n{\n imgdes timage;\n int dx, dy, rcode, pct = 83; // 83% percent of original size\n\n // Allocate space for the new image\n dx = (int)(((long)(image1->endx - image1->stx + 1)) * pct / 100);\n dy = (int)(((long)(image1->endy - image1->sty + 1)) * pct / 100);\n if((rcode = allocimage(&timage, dx, dy,\n image1->bmh->biBitCount)) == NO_ERROR) {\n // Resize Image into timage\n if((rcode = resizeex(image1, &timage, 1)) == NO_ERROR) {\n // Success, free source image\n freeimage(image1);\n // Assign timage to image1\n copyimgdes(&timage, image1);\n }\n else // Error in resizing image, release timage memory\n freeimage(&timage);\n }\n return(rcode);\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4065/" ]
353,040
<p>I want to list (a sorted list) all my entries from an attribute called streetNames in my table/relation Customers. eg. I want to achieve the following order: </p> <p>Street_1A<br> Street_1B<br> Street_2A<br> Street_2B<br> Street_12A<br> Street_12B </p> <p>A simple order by streetNames will do a lexical comparision and then Street_12A and B will come before Street_2A/B, and that is not correct. Is it possible to solve this by pure SQL?</p>
[ { "answer_id": 353124, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": -1, "selected": true, "text": "DECLARE @test TABLE\n(\n street VARCHAR(100)\n)\n\nINSERT INTO @test (street) VALUES('Street')\nINSERT INTO @test (street) VALUES('Street 1A')\nINSERT INTO @test (street) VALUES('Street1 12B')\nINSERT INTO @test (street) VALUES('Street 22A')\nINSERT INTO @test (street) VALUES('Street1 200B-8a')\nINSERT INTO @test (street) VALUES('')\nINSERT INTO @test (street) VALUES(NULL)\n\nSELECT\n street,\n CASE \n WHEN LEN(street) > 0 AND CHARINDEX(' ', REVERSE(street)) > 0\n THEN CASE\n WHEN RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1) LIKE '%[0-9]%'\n THEN LEFT(street, LEN(street) - CHARINDEX(' ', REVERSE(street)))\n END\n END street_part,\n CASE \n WHEN LEN(street) > 0 AND CHARINDEX(' ', REVERSE(street)) > 0\n THEN CASE \n WHEN RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1) LIKE '%[0-9]%'\n THEN RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1)\n END\n END house_part,\n CASE \n WHEN LEN(street) > 0 AND CHARINDEX(' ', REVERSE(street)) > 0\n THEN CASE \n WHEN RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1) LIKE '%[0-9]%'\n THEN CASE\n WHEN PATINDEX('%[a-z]%', LOWER(RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1))) > 0\n THEN CONVERT(INT, LEFT(RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1), PATINDEX('%[^0-9]%', LOWER(RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1))) - 1))\n END\n END\n END house_part_num\nFROM\n @test \nORDER BY\n street_part,\n house_part_num,\n house_part\n REPLACE(street, ' - ', '-')" }, { "answer_id": 353149, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": -1, "selected": false, "text": "Declare @T Table (streetName VarChar(50))\nInsert @T(streetName) Values('Street 1A')\nInsert @T(streetName) Values('Street 2A')\nInsert @T(streetName) Values('Street 2B')\nInsert @T(streetName) Values('Street 12A')\nInsert @T(streetName) Values('Another Street 1A')\nInsert @T(streetName) Values('Another Street 4A')\nInsert @T(streetName) Values('a third Street 12B')\nInsert @T(streetName) Values('a third Street 1C')\n\nSelect * From @T \nOrder By Substring(StreetName, 0, 1 + len(StreetName) - charIndex(' ', reverse(StreetName))),\n Cast(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), \n Case When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 5)) = 1 Then 5\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 4)) = 1 Then 4\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 3)) = 1 Then 3\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 2)) = 1 Then 2\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 1)) = 1 Then 1\n End) as Integer),\n Substring(StreetName, len(StreetName) - charIndex(' ', reverse(StreetName)) +\n Case When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 5)) = 1 Then 5\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 4)) = 1 Then 6\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 3)) = 1 Then 5\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 2)) = 1 Then 4\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 1)) = 1 Then 3\n End, Len(StreetName))\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
353,078
<p>I'm running into a problem when modifying a WCF service.</p> <p>The original service method looks like this:</p> <pre><code>[OperationContract(IsOneWay = true, IsInitiating = true, IsTerminating = false)] void Login(string userName, string password); </code></pre> <p>This method works.</p> <p>The problem is that when I change it to this:</p> <pre><code>[OperationContract(IsOneWay = false, IsInitiating = true, IsTerminating = false)] bool Login(string userName, string password); </code></pre> <p>It stops working and times out.</p> <p>Any ideas?</p>
[ { "answer_id": 353124, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": -1, "selected": true, "text": "DECLARE @test TABLE\n(\n street VARCHAR(100)\n)\n\nINSERT INTO @test (street) VALUES('Street')\nINSERT INTO @test (street) VALUES('Street 1A')\nINSERT INTO @test (street) VALUES('Street1 12B')\nINSERT INTO @test (street) VALUES('Street 22A')\nINSERT INTO @test (street) VALUES('Street1 200B-8a')\nINSERT INTO @test (street) VALUES('')\nINSERT INTO @test (street) VALUES(NULL)\n\nSELECT\n street,\n CASE \n WHEN LEN(street) > 0 AND CHARINDEX(' ', REVERSE(street)) > 0\n THEN CASE\n WHEN RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1) LIKE '%[0-9]%'\n THEN LEFT(street, LEN(street) - CHARINDEX(' ', REVERSE(street)))\n END\n END street_part,\n CASE \n WHEN LEN(street) > 0 AND CHARINDEX(' ', REVERSE(street)) > 0\n THEN CASE \n WHEN RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1) LIKE '%[0-9]%'\n THEN RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1)\n END\n END house_part,\n CASE \n WHEN LEN(street) > 0 AND CHARINDEX(' ', REVERSE(street)) > 0\n THEN CASE \n WHEN RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1) LIKE '%[0-9]%'\n THEN CASE\n WHEN PATINDEX('%[a-z]%', LOWER(RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1))) > 0\n THEN CONVERT(INT, LEFT(RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1), PATINDEX('%[^0-9]%', LOWER(RIGHT(street, CHARINDEX(' ', REVERSE(street)) - 1))) - 1))\n END\n END\n END house_part_num\nFROM\n @test \nORDER BY\n street_part,\n house_part_num,\n house_part\n REPLACE(street, ' - ', '-')" }, { "answer_id": 353149, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": -1, "selected": false, "text": "Declare @T Table (streetName VarChar(50))\nInsert @T(streetName) Values('Street 1A')\nInsert @T(streetName) Values('Street 2A')\nInsert @T(streetName) Values('Street 2B')\nInsert @T(streetName) Values('Street 12A')\nInsert @T(streetName) Values('Another Street 1A')\nInsert @T(streetName) Values('Another Street 4A')\nInsert @T(streetName) Values('a third Street 12B')\nInsert @T(streetName) Values('a third Street 1C')\n\nSelect * From @T \nOrder By Substring(StreetName, 0, 1 + len(StreetName) - charIndex(' ', reverse(StreetName))),\n Cast(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), \n Case When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 5)) = 1 Then 5\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 4)) = 1 Then 4\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 3)) = 1 Then 3\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 2)) = 1 Then 2\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 1)) = 1 Then 1\n End) as Integer),\n Substring(StreetName, len(StreetName) - charIndex(' ', reverse(StreetName)) +\n Case When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 5)) = 1 Then 5\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 4)) = 1 Then 6\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 3)) = 1 Then 5\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 2)) = 1 Then 4\n When IsNumeric(Substring(StreetName, 2 + len(StreetName) - charIndex(' ', reverse(StreetName)), 1)) = 1 Then 3\n End, Len(StreetName))\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373/" ]
353,093
<p>I know that I can use $('#myId').load('aPage.html'); to load a page into an element, how do I do use that to alter an image?</p>
[ { "answer_id": 353098, "author": "matdumsa", "author_id": 1775, "author_profile": "https://Stackoverflow.com/users/1775", "pm_score": 4, "selected": true, "text": "$(\"selectorforyourimage\").attr(\"src\",\"newimagelocation\");\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
353,100
<p>The below <a href="http://docs.jquery.com/Effects/fadeIn" rel="nofollow noreferrer">fadeIn</a>, <a href="http://docs.jquery.com/Effects/fadeOut" rel="nofollow noreferrer">fadeOut</a> effect works fine in Firefox 3.0 but it doesn't work in IE 7 ... Whay is that and what's the trick? The idea is of course to get a "blink" effect and attract the attention of the user to a specific row in a table. </p> <pre><code>function highLightErrorsAndWarnings() { $(".status-error").fadeIn(100).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300); $(".status-warning").fadeIn(100).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300); } </code></pre> <p><strong>Update:</strong> Found the stupid problem ... ".status-error" points to a tr-element. It's possible to the set the background-color and fade it on a tr in Firefox but not in IE. Changing the "CSS pointer" to ".status-error <strong><em>td</em></strong>" made it point to the td below the tr and everything worked in all browsers.</p>
[ { "answer_id": 2170546, "author": "Iggi", "author_id": 262773, "author_profile": "https://Stackoverflow.com/users/262773", "pm_score": 1, "selected": false, "text": "down and dirty div/span/etc $.fn.crossBrowserPulsate = function() {\n var startColor = $(this).css(\"background-color\");\n var endColor = $(this).css(\"color\");\n\n $(this).animate({color:startColor},500,\n function() {\n $(this).animate({color:endColor},500,\n ...\n )}\n );\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298/" ]
353,110
<p>Is it possible to exclude a complete namespace from all FxCop analysis while still analyzing the rest of the assembly using the <code>SuppressMessageAttribute</code>?</p> <p>In my current case, I have a bunch of classes generated by LINQ to SQL which cause a lot of FxCop issues, and obviously, I will not modify all of those to match FxCop standards, as a lot of those modifications would be gone if I re-generated the classes.</p> <p>I know that FxCop has a project option to suppress analysis on generated code, but it does not seem to recognize the entity and context classes created by LINQ 2 SQL as generated code.</p>
[ { "answer_id": 353145, "author": "Chane", "author_id": 43808, "author_profile": "https://Stackoverflow.com/users/43808", "pm_score": 1, "selected": false, "text": "[GeneratedCodeAttribute(\"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator\", \"9.0.0.0\")]\n" }, { "answer_id": 2404925, "author": "AMissico", "author_id": 163921, "author_profile": "https://Stackoverflow.com/users/163921", "pm_score": 1, "selected": false, "text": "<Assembly: SuppressMessage(\"Microsoft.Design\", _\n \"CA1020:AvoidNamespacesWithFewTypes\", _\n Scope:=\"namespace\", _\n Target:=\"Missico.IO\")> \n GlobalSuppressions.vb" }, { "answer_id": 3619158, "author": "SLaks", "author_id": 34397, "author_profile": "https://Stackoverflow.com/users/34397", "pm_score": 3, "selected": false, "text": "[GeneratedCode] attribute" }, { "answer_id": 3619171, "author": "Justin Niessner", "author_id": 84651, "author_profile": "https://Stackoverflow.com/users/84651", "pm_score": 5, "selected": true, "text": "[GeneratedCode] [GeneratedCode]\npublic partial class MainDataContext { }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11963/" ]
353,126
<p>This is probably not possible, but I have this class:</p> <pre><code>public class Metadata&lt;DataType&gt; where DataType : struct { private DataType mDataType; } </code></pre> <p>There's more to it, but let's keep it simple. The generic type (DataType) is limited to value types by the where statement. What I want to do is have a list of these Metadata objects of varying types (DataType). Such as:</p> <pre><code>List&lt;Metadata&gt; metadataObjects; metadataObjects.Add(new Metadata&lt;int&gt;()); metadataObjects.Add(new Metadata&lt;bool&gt;()); metadataObjects.Add(new Metadata&lt;double&gt;()); </code></pre> <p>Is this even possible?</p>
[ { "answer_id": 353134, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 9, "selected": true, "text": "public abstract class Metadata\n{\n}\n\n// extend abstract Metadata class\npublic class Metadata<DataType> : Metadata where DataType : struct\n{\n private DataType mDataType;\n}\n" }, { "answer_id": 353174, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 7, "selected": false, "text": "MetaData public interface IMetaData { }\n\npublic class Metadata<DataType> : IMetaData where DataType : struct\n{\n private DataType mDataType;\n}\n" }, { "answer_id": 353320, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 5, "selected": false, "text": "new public interface IMetadata\n{\n Type DataType { get; }\n\n object Data { get; }\n}\n\npublic interface IMetadata<TData> : IMetadata\n{\n new TData Data { get; }\n}\n Data public class Metadata<TData> : IMetadata<TData>\n{\n public Metadata(TData data)\n {\n Data = data;\n }\n\n public Type DataType\n {\n get { return typeof(TData); }\n }\n\n object IMetadata.Data\n {\n get { return Data; }\n }\n\n public TData Data { get; private set; }\n}\n public interface IValueTypeMetadata : IMetadata\n{\n\n}\n\npublic interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct\n{\n\n}\n\npublic class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct\n{\n public ValueTypeMetadata(TData data) : base(data)\n {}\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44626/" ]
353,131
<p>I'm trying to store the names of some variables inside strings. For example:</p> <pre><code>Dim Foo1 as Integer Dim Foo1Name as String ' -- Do something to set Foo1Name to the name of the other variable -- MessageBox.Show(Foo1Name &amp; " is the variable you are looking for.") ' Outputs: ' Foo1 is the variable you are looking for. </code></pre> <p>This would help with some debugging I'm working on.</p>
[ { "answer_id": 353192, "author": "Paul Morel", "author_id": 1311247, "author_profile": "https://Stackoverflow.com/users/1311247", "pm_score": 1, "selected": false, "text": "myArray(\"foo1Name\") = \"foo1\"\n if( myArray(variableName(x)) == whatImLookingFor ) print variableName(x) & \"is it\"\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38258/" ]
353,132
<p>I am modifying a SQL table through C# code and I need to drop a NOT NULL constraint if it exists. How do I check to see if it exists first?</p>
[ { "answer_id": 353160, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 5, "selected": true, "text": "select is_nullable \nfrom sys.columns\nwhere object_id = OBJECT_ID('tablename') \nand name = 'columnname';\n" }, { "answer_id": 353163, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "syscolumns.isnullable COLUMNPROPERTY(@tableId, 'ColumnName', 'AllowsNull')\n" }, { "answer_id": 353172, "author": "Rick Kierner", "author_id": 11771, "author_profile": "https://Stackoverflow.com/users/11771", "pm_score": 1, "selected": false, "text": "select * from information_schema.columns c\ninner join information_schema.tables t on c.table_catalog = t.table_catalog and t.table_schema = c.table_schema and t.table_name = c.table_name\nwhere c.table_name = 'Categories' and c.Is_nullable = 'NO'\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
353,148
<p>I am on a shared host and can not change the symbolic link to Python2.4, it defaults to 2.3. I tried creating a sym link in the director I would be working on to 2.4, but it seems the the 'global' python interpreter under /usr/bin/python take presedence unless I run it as ./python. What alternative ways are there to override this behaviour?</p>
[ { "answer_id": 353159, "author": "Bombe", "author_id": 43582, "author_profile": "https://Stackoverflow.com/users/43582", "pm_score": 3, "selected": true, "text": "ln -s /usr/bin/python2.4 $HOME/bin/python\nexport PATH=\"$HOME/bin:$PATH\"\n" }, { "answer_id": 353200, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python\n #!/whatever/the/path/to/your/version/python\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370899/" ]
353,152
<p>I'm tackling project euler's <a href="http://projecteuler.net/index.php?section=problems&amp;id=220" rel="nofollow noreferrer">problem 220</a> (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!)</p> <p>So far I have:</p> <pre><code>D = "Fa" def iterate(D,num): for i in range (0,num): D = D.replace("a","A") D = D.replace("b","B") D = D.replace("A","aRbFR") D = D.replace("B","LFaLb") return D instructions = iterate("Fa",50) print instructions </code></pre> <p>Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step.</p>
[ { "answer_id": 353242, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "def repl220( string ):\n for c in string:\n if c == 'a': yield \"aRbFR\"\n elif c == 'b': yield \"LFaLb\"\n else yield c\n" }, { "answer_id": 353243, "author": "xahtep", "author_id": 42184, "author_profile": "https://Stackoverflow.com/users/42184", "pm_score": 2, "selected": false, "text": "iterate(D,n)" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ]
353,161
<p>I would like to be able to query whether or not a service is running from a windows batch file. I know I can use: </p> <blockquote> <p>sc query "ServiceName" </p> </blockquote> <p>but, this dumps out some text. What I really want is for it to set the <code>errorlevel</code> environment variable so that I can take action on that.</p> <p>Do you know a simple way I can do this?</p> <p><strong>UPDATE</strong><br> Thanks for the answers so far. I'm worried the solutions that parse the text may not work on non English operating systems. Does anybody know a way around this, or am I going to have to bite the bullet and write a console program to get this right.</p>
[ { "answer_id": 353196, "author": "Igal Serban", "author_id": 25737, "author_profile": "https://Stackoverflow.com/users/25737", "pm_score": 8, "selected": true, "text": "sc query \"ServiceName\" | find \"RUNNING\"\n" }, { "answer_id": 353201, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": false, "text": "sc query state= all \n" }, { "answer_id": 353205, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "@echo off\nnet start | grep -x \"Service\"\nif %ERRORLEVEL% == 2 goto trouble\nif %ERRORLEVEL% == 1 goto stopped\nif %ERRORLEVEL% == 0 goto started\necho unknown status\ngoto end\n:trouble\necho trouble\ngoto end\n:started\necho started\ngoto end\n:stopped\necho stopped\ngoto end\n:end\n" }, { "answer_id": 353206, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 2, "selected": false, "text": " sc query \"ServiceName\" | findstr RUNNING \n" }, { "answer_id": 396531, "author": "NicJ", "author_id": 43815, "author_profile": "https://Stackoverflow.com/users/43815", "pm_score": 3, "selected": false, "text": "call wmic /locale:ms_409 service where (name=\"wsearch\") get state /value | findstr State=Running\nif %ErrorLevel% EQU 0 (\n echo Running\n) else (\n echo Not running\n)\n" }, { "answer_id": 1155887, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "\n$serviceName = \"ServiceName\";\n$serviceStatus = (get-service \"$serviceName\").Status;\n\nif ($serviceStatus -eq \"Running\") {\n echo \"Service is Running\";\n}\nelse {\n #Could be Stopped, Stopping, Paused, or even Starting...\n echo \"Service is $serviceStatus\";\n}\n \n@ECHO off\nSET PS=powershell -nologo -command\n%PS% \"& {if((get-service SvcName).Status -eq 'Running'){exit 1}}\"\n\nECHO.%ERRORLEVEL%\n powershell myCode.ps1" }, { "answer_id": 5406688, "author": "Shahin", "author_id": 673192, "author_profile": "https://Stackoverflow.com/users/673192", "pm_score": 4, "selected": false, "text": "net start | find \"Service Name\"\n" }, { "answer_id": 13885775, "author": "Mark Sowul", "author_id": 155892, "author_profile": "https://Stackoverflow.com/users/155892", "pm_score": 2, "selected": false, "text": "WMIC Service WHERE \"Name = 'SericeName'\" GET Started WMIC Service WHERE \"Name = 'ServiceName'\" GET ProcessId" }, { "answer_id": 38763063, "author": "Chris Voon", "author_id": 755356, "author_profile": "https://Stackoverflow.com/users/755356", "pm_score": 1, "selected": false, "text": "sc.exe query \"ServiceName\" | findstr RUNNING\n sc sc query \"ServiceName\" | findstr RUNNING\n find sc.exe query \"ServiceName\" | find RUNNING\n" }, { "answer_id": 40981295, "author": "Luis Ramos", "author_id": 7119966, "author_profile": "https://Stackoverflow.com/users/7119966", "pm_score": 1, "selected": false, "text": "SERVICO.BAT\n@echo off\necho Servico: %1\nif \"%1\"==\"\" goto erro\nsc query %1 | findstr RUNNING\nif %ERRORLEVEL% == 2 goto trouble\nif %ERRORLEVEL% == 1 goto stopped\nif %ERRORLEVEL% == 0 goto started\necho unknown status\ngoto end\n:trouble\necho trouble\ngoto end\n:started\necho started\ngoto end\n:stopped\necho stopped\ngoto end\n:erro\necho sintaxe: servico NOMESERVICO\ngoto end\n\n:end\n" }, { "answer_id": 41294507, "author": "Muhammad Imron", "author_id": 7193332, "author_profile": "https://Stackoverflow.com/users/7193332", "pm_score": 2, "selected": false, "text": "@ECHO OFF\nREM testing at cmd : sc query \"MSSQLSERVER\" | findstr RUNNING\nREM \"MSSQLSERVER\" is the name of Service for sample\nsc query \"MSSQLSERVER\" %1 | findstr RUNNING\nif %ERRORLEVEL% == 2 goto trouble\nif %ERRORLEVEL% == 1 goto stopped\nif %ERRORLEVEL% == 0 goto started\necho unknown status\ngoto end\n:trouble\necho Oh noooo.. trouble mas bro\ngoto end\n:started\necho \"SQL Server (MSSQLSERVER)\" is started\ngoto end\n:stopped\necho \"SQL Server (MSSQLSERVER)\" is stopped\necho Starting service\nnet start \"MSSQLSERVER\"\ngoto end\n:erro\necho Error please check your command.. mas bro \ngoto end\n\n:end\n" }, { "answer_id": 47864232, "author": "not2qubit", "author_id": 1147688, "author_profile": "https://Stackoverflow.com/users/1147688", "pm_score": 0, "selected": false, "text": "sc query \"SomeService\" |grep -qo RUNNING && echo \"SomeService is running.\" || echo \"SomeService is not running!\"\n sc.exe" }, { "answer_id": 48760195, "author": "kayleeFrye_onDeck", "author_id": 3543437, "author_profile": "https://Stackoverflow.com/users/3543437", "pm_score": 1, "selected": false, "text": "find findstr CDPUserSvc CDPUserSvc_54530 find findstr CDPUserSvc CDPUserSvc_54530 /r /c findstr $ CDPUserSvc CDPUserSvc_54530 sc query|findstr /r /c:\"CDPUserSvc$\"" }, { "answer_id": 69799396, "author": "MSBUTech", "author_id": 17301516, "author_profile": "https://Stackoverflow.com/users/17301516", "pm_score": -1, "selected": false, "text": "sc query \"YourService\" | find /i \"failed\" 2>&1>nul && echo.'YourService Not Installed' || (sc query \"YourService\"| find /i \"running\" 2>&1>nul && echo.Yes || echo.No)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898/" ]
353,165
<p>I have a virtual path (example: "~/Images/Banner.jpg") and I want to make that an absolute web path (example: "/ApplicationRoot/Images/Banner.jpg"). There is a method that will do this, I believe in a class called something like HTTPUtility or similar name. Though ever time I need this method, it takes me hours searching for it. It would be greatly appreciated if someone could post the proper method to do this so I can favorite this for easy access in the future. </p> <p>Thank you very much. </p>
[ { "answer_id": 353184, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 7, "selected": true, "text": "System.Web.VirtualPathUtility.ToAbsolute(\"yourRelativePath\");\n" }, { "answer_id": 353185, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": false, "text": "Control.ResolveClientUrl(url)\n Control.ResolveUrl(url)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
353,180
<p>I have been using PRETTY_FUNCTION to output the current function name, however I have reimplemented some functions and would like to find out which functions are calling them.</p> <p>In C++ how can I get the function name of the calling routine?</p>
[ { "answer_id": 378165, "author": "Aaron", "author_id": 28950, "author_profile": "https://Stackoverflow.com/users/28950", "pm_score": 6, "selected": false, "text": "// orignal function name was 'FunctionName'\nvoid FunctionNameReal(...)\n{\n // Do Something\n}\n\n#undef FunctionName\n#define FunctionName printf(\"Calling FunctionName from %s\\n\",__FUNCTION__);FunctionNameReal\n printf() __FUNCTION__ __LINE__ __FILE__ #ifdef class operator() operator() g++ -o test test.cpp g++ -o test test.cpp -DREPORT #include <iostream>\n\nint FunctionName(int one, int two)\n{\n static int calls=0;\n return (++calls+one)*two;\n}\n\n#ifdef REPORT\n // class to capture the caller and print it. \n class Reporter\n {\n public:\n Reporter(std::string Caller, std::string File, int Line)\n : caller_(Caller)\n , file_(File)\n , line_(Line)\n {}\n\n int operator()(int one, int two)\n {\n std::cout\n << \"Reporter: FunctionName() is being called by \"\n << caller_ << \"() in \" << file_ << \":\" << line_ << std::endl;\n // can use the original name here, as it is still defined\n return FunctionName(one,two);\n }\n private:\n std::string caller_;\n std::string file_;\n int line_;\n\n };\n\n// remove the symbol for the function, then define a new version that instead\n// creates a stack temporary instance of Reporter initialized with the caller\n# undef FunctionName\n# define FunctionName Reporter(__FUNCTION__,__FILE__,__LINE__)\n#endif\n\n\nvoid Caller1()\n{\n int val = FunctionName(7,9); // <-- works for captured return value\n std::cout << \"Mystery Function got \" << val << std::endl;\n}\n\nvoid Caller2()\n{\n // Works for inline as well.\n std::cout << \"Mystery Function got \" << FunctionName(11,13) << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n Caller1();\n Caller2();\n return 0;\n}\n Reporter: FunctionName() is being called by Caller1() in test.cpp:44\nMystery Function got 72\nReporter: FunctionName() is being called by Caller2() in test.cpp:51\nMystery Function got 169\n FunctionName Reporter(__FUNCTION__,__FILE__,__LINE__) operator() g++ -E -DREPORT test.cpp void Caller2()\n{\n std::cout << \"Mystery Function got \" << Reporter(__FUNCTION__,\"test.cpp\",51)(11,13) << std::endl;\n}\n __LINE__ __FILE__ __FUNCTION__ g++ -o test test.cpp g++ -o test test.cpp -DREPORT #include <iostream>\n\nclass ClassName\n{\n public:\n explicit ClassName(int Member)\n : member_(Member)\n {}\n\n int FunctionName(int one, int two)\n {\n return (++member_+one)*two;\n }\n\n private:\n int member_;\n};\n\n#ifdef REPORT\n // class to capture the caller and print it. \n class ClassNameDecorator\n {\n public:\n ClassNameDecorator( int Member)\n : className_(Member)\n {}\n\n ClassNameDecorator& FunctionName(std::string Caller, std::string File, int Line)\n {\n std::cout\n << \"Reporter: ClassName::FunctionName() is being called by \"\n << Caller << \"() in \" << File << \":\" << Line << std::endl;\n return *this;\n }\n int operator()(int one, int two)\n {\n return className_.FunctionName(one,two);\n }\n private:\n ClassName className_;\n };\n\n\n// remove the symbol for the function, then define a new version that instead\n// creates a stack temporary instance of ClassNameDecorator.\n// FunctionName is then replaced with a version that takes the caller information\n// and uses Method Chaining to allow operator() to be invoked with the original\n// parameters.\n# undef ClassName\n# define ClassName ClassNameDecorator\n# undef FunctionName\n# define FunctionName FunctionName(__FUNCTION__,__FILE__,__LINE__)\n#endif\n\n\nvoid Caller1()\n{\n ClassName foo(21);\n int val = foo.FunctionName(7,9); // <-- works for captured return value\n std::cout << \"Mystery Function got \" << val << std::endl;\n}\n\nvoid Caller2()\n{\n ClassName foo(42);\n // Works for inline as well.\n std::cout << \"Mystery Function got \" << foo.FunctionName(11,13) << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n Caller1();\n Caller2();\n return 0;\n}\n Reporter: ClassName::FunctionName() is being called by Caller1() in test.cpp:56\nMystery Function got 261\nReporter: ClassName::FunctionName() is being called by Caller2() in test.cpp:64\nMystery Function got 702\n operator()" }, { "answer_id": 43970783, "author": "Rusty Shackleford", "author_id": 754018, "author_profile": "https://Stackoverflow.com/users/754018", "pm_score": 5, "selected": false, "text": "__builtin_FUNCTION __FUNCTION__ #include <cstdio>\n\nvoid foobar(const char* str = __builtin_FUNCTION()){\n std::printf(\"called by %s\\n\", str);\n}\n\nint main(){\n foobar();\n return 0;\n}\n called by main\n" }, { "answer_id": 50458222, "author": "mosh", "author_id": 476175, "author_profile": "https://Stackoverflow.com/users/476175", "pm_score": 1, "selected": false, "text": "// What: Track last few lines in loci of control, gpl/moshahmed_at_gmail\n// Test: gcc -Wall -g -lm -std=c11 track.c\n#include <stdio.h>\n#include <string.h>\n\n#define _DEBUG\n#ifdef _DEBUG\n#define lsize 255 /* const int lsize=255; -- C++ */\nstruct locs {\n int line[lsize];\n char *file[lsize];\n char *func[lsize];\n int cur; /* cur=0; C++ */\n} locs;\n\n#define track do {\\\n locs.line[locs.cur]=__LINE__ ;\\\n locs.file[locs.cur]=(char*)__FILE__ ;\\\n locs.func[locs.cur]=(char*) __builtin_FUNCTION() /* __PRETTY_FUNCTION__ -- C++ */ ;\\\n locs.cur=(locs.cur+1) % lsize;\\\n } while(0);\n\nvoid track_start(){\n memset(&locs,0, sizeof locs);\n}\n\nvoid track_print(){\n int i, k;\n for (i=0; i<lsize; i++){\n k = (locs.cur+i) % lsize;\n if (locs.file[k]){\n fprintf(stderr,\"%d: %s:%d %s\\n\",\n k, locs.file[k],\n locs.line[k], locs.func[k]);\n }\n }\n}\n#else\n#define track do {} while(0)\n#define track_start() (void)0\n#define track_print() (void)0\n#endif\n\n\n// Sample usage.\nvoid bar(){ track ; }\nvoid foo(){ track ; bar(); }\n\nint main(){\n int k;\n track_start();\n for (k=0;k<2;k++)\n foo();\n track;\n track_print();\n return 0;\n} \n" }, { "answer_id": 53353036, "author": "user", "author_id": 4934640, "author_profile": "https://Stackoverflow.com/users/4934640", "pm_score": 2, "selected": false, "text": "#define function #include <iostream>\n\nstruct ClassName {\n int member;\n ClassName(int member) : member(member) { }\n\n int secretFunctionName(\n int one, int two, const char* caller, const char* file, int line) \n {\n std::cout << \"Reporter: ClassName::function_name() is being called by \"\n << caller << \"() in \" << file << \":\" << line << std::endl;\n\n return (++member+one)*two;\n }\n};\n\n#define unique_global_function_name(first, second) \\\n secretFunctionName(first, second, __FUNCTION__,__FILE__,__LINE__)\n\nvoid caller1() {\n ClassName foo(21);\n int val = foo.unique_global_function_name(7, 9);\n std::cout << \"Mystery Function got \" << val << std::endl;\n}\n\nvoid caller2() {\n ClassName foo(42);\n int val = foo.unique_global_function_name(11, 13);\n std::cout << \"Mystery Function got \" << val << std::endl;\n}\n\nint main(int argc, char** argv) {\n caller1();\n caller2();\n return 0;\n}\n Reporter: ClassName::function_name() is being called by caller1() in D:\\test.cpp:26\nMystery Function got 261\nReporter: ClassName::function_name() is being called by caller2() in D:\\test.cpp:33\nMystery Function got 702\n" }, { "answer_id": 67155236, "author": "Cœur", "author_id": 1033581, "author_profile": "https://Stackoverflow.com/users/1033581", "pm_score": 0, "selected": false, "text": "#include <dlfcn.h>\n Dl_info info;\nif (dladdr(__builtin_return_address(0), &info)) {\n printf(\"%s called by %s\", __builtin_FUNCTION(), info.dli_sname);\n}\n dladdr -rdynamic -Wl,--export-dynamic" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24459/" ]
353,198
<p>We have a large collection of command-line utilities that we write ourselves and use frequently. At the moment, testing them is very cumbersome and consequently, we don't do as much testing as we aught to.</p> <p>I am wondering if anyone can suggest good techniques or tools for doing a good job of this kind of thing.</p> <p>This is UNIX.</p>
[ { "answer_id": 27971295, "author": "Venkat", "author_id": 4458990, "author_profile": "https://Stackoverflow.com/users/4458990", "pm_score": 0, "selected": false, "text": " # Various ways to say \"ok\"\n ok($got eq $expected, $test_name);\n is ($got, $expected, $test_name);\n isnt($got, $expected, $test_name);\n\n # Rather than print STDERR \"# here's what went wrong\\n\"\n diag(\"here's what went wrong\");\n\n like ($got, qr/expected/, $test_name);\n unlike($got, qr/expected/, $test_name);\n\n cmp_ok($got, '==', $expected, $test_name);\n" }, { "answer_id": 55379937, "author": "Emil Karlén", "author_id": 9214151, "author_profile": "https://Stackoverflow.com/users/9214151", "pm_score": 1, "selected": false, "text": "[setup]\n\ndir input\ndir output/good\ndir output/bad\n\nfile input/a.txt = <<EOF\nGOOD contents\nEOF\n\nfile input/b.txt = <<EOF\nbad contents\nEOF\n\n[act]\n\nclassify-files-by-moving-to-appropriate-dir GOOD input/ output/\n\n[assert]\n\ndir-contents input empty\n\nexists output/good/a.txt : type file\ndir-contents output/good num-files == 1\n\nexists output/bad/b.txt : type file\ndir-contents output/bad num-files == 1\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6101/" ]
353,211
<p>In the recent update of java (6.10) <a href="http://java.sun.com/javase/6/webnotes/6u10.html" rel="nofollow noreferrer">http://java.sun.com/javase/6/webnotes/6u10.html</a><a href="http://java.sun.com/javase/6/webnotes/6u10.html" rel="nofollow noreferrer">link text</a> the way that unsigned applets was changed. A warning is now displayed. Is it possible to turn this off without signing your applet?</p>
[ { "answer_id": 27971295, "author": "Venkat", "author_id": 4458990, "author_profile": "https://Stackoverflow.com/users/4458990", "pm_score": 0, "selected": false, "text": " # Various ways to say \"ok\"\n ok($got eq $expected, $test_name);\n is ($got, $expected, $test_name);\n isnt($got, $expected, $test_name);\n\n # Rather than print STDERR \"# here's what went wrong\\n\"\n diag(\"here's what went wrong\");\n\n like ($got, qr/expected/, $test_name);\n unlike($got, qr/expected/, $test_name);\n\n cmp_ok($got, '==', $expected, $test_name);\n" }, { "answer_id": 55379937, "author": "Emil Karlén", "author_id": 9214151, "author_profile": "https://Stackoverflow.com/users/9214151", "pm_score": 1, "selected": false, "text": "[setup]\n\ndir input\ndir output/good\ndir output/bad\n\nfile input/a.txt = <<EOF\nGOOD contents\nEOF\n\nfile input/b.txt = <<EOF\nbad contents\nEOF\n\n[act]\n\nclassify-files-by-moving-to-appropriate-dir GOOD input/ output/\n\n[assert]\n\ndir-contents input empty\n\nexists output/good/a.txt : type file\ndir-contents output/good num-files == 1\n\nexists output/bad/b.txt : type file\ndir-contents output/bad num-files == 1\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
353,224
<p>I'm brand new to Erlang. How do you do modulo (get the remainder of a division)? It's % in most C-like languages, but that designates a comment in Erlang.</p> <p>Several people answered with rem, which in most cases is fine. But I'm revisiting this because now I need to use negative numbers and rem gives you the remainder of a division, which is not the same as modulo for negative numbers.</p>
[ { "answer_id": 353241, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "rem" }, { "answer_id": 353244, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 5, "selected": false, "text": "rem Eshell V5.6.4 (abort with ^G)\n1> 97 rem 10.\n7\n" }, { "answer_id": 858649, "author": "grifaton", "author_id": 103003, "author_profile": "https://Stackoverflow.com/users/103003", "pm_score": 7, "selected": true, "text": "5 rem 3. 2 -5 rem 3. -2 -5 rem 3. -5 = -2 * 3 + 1. mod(X,Y) when X > 0 -> X rem Y;\nmod(X,Y) when X < 0 -> Y + X rem Y;\nmod(0,Y) -> 0.\n" }, { "answer_id": 2386387, "author": "user287075", "author_id": 287075, "author_profile": "https://Stackoverflow.com/users/287075", "pm_score": 2, "selected": false, "text": "% Returns the positive remainder of the division of X by Y, in [0;Y[. \n% In Erlang, -5 rem 3 is -2, whereas this function will return 1, \n% since -5 =-2 * 3 + 1.\n\nmodulo(X,Y) when X > 0 -> \n X rem Y;\n\nmodulo(X,Y) when X < 0 -> \n K = (-X div Y)+1,\n PositiveX = X + K*Y,\n PositiveX rem Y;\n\nmodulo(0,_Y) -> \n 0.\n" }, { "answer_id": 10676885, "author": "zie1ony", "author_id": 1076288, "author_profile": "https://Stackoverflow.com/users/1076288", "pm_score": 1, "selected": false, "text": "mod(A, B) when A > 0 -> A rem B;\nmod(A, B) when A < 0 -> mod(A+B, B); \nmod(0, _) -> 0.\n\n% console:\n3> my:mod(-13, 5).\n2\n" }, { "answer_id": 30579079, "author": "adam", "author_id": 2585386, "author_profile": "https://Stackoverflow.com/users/2585386", "pm_score": 1, "selected": false, "text": "rem % mod(-5,-3) C: -5 % -3 == -2\nrem: -5 rem -3 == -2\nY + X rem Y: -3 + -5 rem -3 == -5 !! wrong !!\n flooring division: -5 mod -3 == -2\neuclidean division: -5 mod -3 == 1\n Y + X rem Y\n rem" }, { "answer_id": 41006154, "author": "Joe Eifert", "author_id": 2831651, "author_profile": "https://Stackoverflow.com/users/2831651", "pm_score": 3, "selected": false, "text": "defp mod(x,y) when x > 0, do: rem(x, y);\ndefp mod(x,y) when x < 0, do: rem(x, y) + y;\ndefp mod(0,_y), do: 0\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
353,233
<p>I have the following code in a SQL Server 2005 trigger: </p> <pre> CREATE TRIGGER [myTrigger] ON [myTable] FOR UPDATE,DELETE AS BEGIN DECLARE @OperationType VARCHAR(6) IF EXISTS(SELECT 1 FROM INSERTED) BEGIN SET @OperationType='Update' END ELSE BEGIN SET @OperationType='Delete' END </pre> <p>My question: is there a situation in which @OperationType is not populated correctly? E.G.: the data in the table is changed by a bunch of UPDATE/DELETE statements, but the trigger is not fired once by every one of them? </p> <p>Do you have a better way to determine if the trigger was fired by an UPDATE or DELETE statement?</p>
[ { "answer_id": 353260, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 3, "selected": false, "text": "CREATE TRIGGER [myUpdateTrigger] ON [myTable]\nFOR UPDATE\nAS\nBEGIN\n\nEND\n\nCREATE TRIGGER [myDeleteTrigger] ON [myTable]\nFOR DELETE\nAS\nBEGIN\n\nEND\n" }, { "answer_id": 353271, "author": "mmx", "author_id": 33708, "author_profile": "https://Stackoverflow.com/users/33708", "pm_score": 2, "selected": false, "text": "UPDATE DELETE" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39735/" ]
353,246
<p>I want my emacs buffer to have a different name than the file name. Rather than setting this manually every time, I want to have this happen automatically based on the file contents, something like:</p> <p>// Local Variables:<br> // buffer-name: MyName<br> // End:</p> <p>But this doesn't work because buffer-name is a function, not a variable. How can I do this?</p>
[ { "answer_id": 353369, "author": "Pierre", "author_id": 24449, "author_profile": "https://Stackoverflow.com/users/24449", "pm_score": 5, "selected": true, "text": "// Local Variables:\n// eval: (rename-buffer \"my-buffer-name-here\")\n// end:\n find-file-hook .emacs (defvar pdp-buffer-name nil)\n\n(defun pdp-rename-buffer-if-necessary ()\n \"Rename the current buffer according to the value of variable\"\n (interactive)\n (if (and pdp-buffer-name (stringp pdp-buffer-name))\n (rename-buffer pdp-buffer-name)))\n\n(add-hook 'find-file-hook 'pdp-rename-buffer-if-necessary)\n // Local Variables:\n// pdp-buffer-name: \"pierre\" \n// end:\n" }, { "answer_id": 353895, "author": "Mike K", "author_id": 44634, "author_profile": "https://Stackoverflow.com/users/44634", "pm_score": 2, "selected": false, "text": ";; allow all values for \"pdp-buffer-name\" \n(defadvice safe-local-variable-p (after allow-pdp-buffer-name (sym val) activate) \n (if (eq sym 'pdp-buffer-name) \n (setq ad-return-value t)) \n ) \n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44634/" ]
353,252
<p>How to implement a great search within a mysqldb - within a table if i search with '...LIke %bla%....' not all entrys would be found - if bla within a word for example. a search with soundex would be great to - but if i read the manual i must create an soundex-index to search for soundex-values? </p> <p>So the question whats the "best practice" to write a good db-search vor a keyword within a simple column "title" or someting else.</p> <p>bye</p>
[ { "answer_id": 353369, "author": "Pierre", "author_id": 24449, "author_profile": "https://Stackoverflow.com/users/24449", "pm_score": 5, "selected": true, "text": "// Local Variables:\n// eval: (rename-buffer \"my-buffer-name-here\")\n// end:\n find-file-hook .emacs (defvar pdp-buffer-name nil)\n\n(defun pdp-rename-buffer-if-necessary ()\n \"Rename the current buffer according to the value of variable\"\n (interactive)\n (if (and pdp-buffer-name (stringp pdp-buffer-name))\n (rename-buffer pdp-buffer-name)))\n\n(add-hook 'find-file-hook 'pdp-rename-buffer-if-necessary)\n // Local Variables:\n// pdp-buffer-name: \"pierre\" \n// end:\n" }, { "answer_id": 353895, "author": "Mike K", "author_id": 44634, "author_profile": "https://Stackoverflow.com/users/44634", "pm_score": 2, "selected": false, "text": ";; allow all values for \"pdp-buffer-name\" \n(defadvice safe-local-variable-p (after allow-pdp-buffer-name (sym val) activate) \n (if (eq sym 'pdp-buffer-name) \n (setq ad-return-value t)) \n ) \n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
353,270
<p>I have some critical logic in a finally block (with an empty try block), because I want to guarantee that the code gets executed even if the thread is aborted. However, I'd also like to detect the ThreadAbortException. I've found that wrapping my critical try/finally block in a try/catch does not catch the ThreadAbortException. Is there any way to detect it?</p> <pre> try { try { } finally { // critical logic } } catch(Exception ex) { // ThreadAbortException is not caught here, but exceptions thrown // from within the critical logic are } </pre>
[ { "answer_id": 602693, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 0, "selected": false, "text": "try {\n try { }\n catch (ThreadAbortException)\n {\n ThreadAbortExceptionBool = true;\n }\n finally {\n // critical logic\n if (ThreadAbortExceptionBool)\n // Whatever\n }\n} \ncatch(Exception ex) {\n // ThreadAbortException is not caught here, but exceptions thrown\n // from within the critical logic are\n}\n" }, { "answer_id": 5184623, "author": "Jordão", "author_id": 31158, "author_profile": "https://Stackoverflow.com/users/31158", "pm_score": 4, "selected": true, "text": "bool threadAborted = true;\ntry {\n try { }\n finally { /* critical code */ }\n threadAborted = false;\n}\nfinally {\n Console.WriteLine(\"Thread aborted? {0}\", threadAborted);\n}\nConsole.WriteLine(\"Done\");\n bool threadAborted = true;\ntry {\n try { }\n finally { /* critical code */ }\n threadAborted = AmIEvil();\n}\nfinally {\n Console.WriteLine(\"Thread aborted? {0}\", threadAborted);\n}\nConsole.WriteLine(\"Done\");\n AmIEvil [MethodImpl(MethodImplOptions.NoInlining)]\nstatic bool AmIEvil() {\n return false;\n}\n try {\n try { }\n finally { /* critical code */ }\n NoOp();\n}\ncatch (Exception ex) {\n // ThreadAbortException is caught here now!\n}\n NoOp [MethodImpl(MethodImplOptions.NoInlining)]\nstatic void NoOp() { }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7529/" ]
353,288
<p>I just started diving into ADO.NET Data Services for a project, and I quickly ran into a problem. At first I was amazed by the performance, but then I realized that the data was cached. My project relies on real-time data, and I'd love to use the ADO.NET Data Services REST query syntax (without needing to use WCF or SOAP), but without caching.</p> <p>I saw on the ADO.NET Data Services introduction page (<a href="http://msdn.microsoft.com/en-us/library/cc907912.aspx" rel="nofollow noreferrer">here</a>) that they do not yet have API support for managing the cache duration or anything of the like.</p> <p>Anyone have any ideas of how to accomplish this, or turn off the cache?</p>
[ { "answer_id": 1525662, "author": "Simon Steele", "author_id": 4591, "author_profile": "https://Stackoverflow.com/users/4591", "pm_score": 3, "selected": true, "text": "this.context.MergeOption = MergeOption.OverwriteChanges;\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44636/" ]
353,296
<p>I have a set of objects which I iterate through, however I may decide during the iteration that one (or more) of those objects now need to be deleted. </p> <p>My code goes as follows:</p> <pre><code>if( ! m_Container.empty() ) { for( typedefedcontainer::iterator it = m_Container.begin(); it != m_Container.end(); ++it ) { if( ! ( SomeFunction( (*it), "test", "TEST!", false )) ) { // If function returns false, delete object. m_Container.erase( it ); AsyncResponseStore::iterator it = m_asyncResponses.begin(); } } } </code></pre> <p>But of course, when I erase an object I get an error : "Map / set iterator not incrementable". Can someone suggest a better way of doing this?</p> <p>See: <a href="https://stackoverflow.com/questions/263945/what-happens-if-you-call-erase-on-a-map-element-while-iterating-from-begin-to-e">What happens if you call erase() on a map element while iterating from begin to end?</a></p>
[ { "answer_id": 353370, "author": "Konrad", "author_id": 18664, "author_profile": "https://Stackoverflow.com/users/18664", "pm_score": 0, "selected": false, "text": "for( typedefedcontainer::iterator it = m_Container.begin();\n it != m_Container.end(); \n )\n{\n if( ! ( SomeFunction( (*it), \"test\", \"TEST!\", false )) )\n {\n // If function returns false, delete object.\n m_Container.erase( it++ );\n }\n else\n { \n ++i;\n } \n\n}\n" }, { "answer_id": 353416, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "struct SomePredicate {\n bool operator()(typedefedcontainer::value_type thing) {\n return ! SomeFunction(thing, \"test\", \"TEST\", false);\n }\n};\n\ntypedefedcontainer::iterator it;\nit = std::remove_if(m_Container.begin(), m_Container.end(), SomePredicate());\nm_Container.erase(it, m_Container.end());\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
353,297
<p>I am trying to create an application like the one here:</p> <p><a href="http://www.eigenfaces.com/" rel="nofollow noreferrer">http://www.eigenfaces.com/</a></p> <p>Basically lots of overlapping circles drawn with pygame. I cannot figure out how the blend the circles to make them translucent. That is to have overlapping colors show through. My code so far is this:</p> <pre><code>import sys, random, time import pygame from pygame.locals import * from pygame import draw rand = random.randint pygame.init( ) W = 320 H = 320 size = (W, H) screen = pygame.display.set_mode(size) run = True while 1: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE : run = not run else: sys.exit() if run: xc = rand(1, W) yc = rand(1, H) rc = rand(1, 25) red = rand(1, 255) grn = rand(1, 255) blu = rand(1, 255) draw.circle(screen, (red, grn, blu, 200), (xc, yc), rc, 0) pygame.display.flip() </code></pre>
[ { "answer_id": 353719, "author": "Zoomulator", "author_id": 44563, "author_profile": "https://Stackoverflow.com/users/44563", "pm_score": 3, "selected": false, "text": "import pygame\nfrom pygame.locals import *\n\nTRANSPARENT = (255,0,255)\npygame.init()\nscreen = pygame.display.set_mode((500,500))\n\nsurf1 = pygame.Surface((200,200))\nsurf1.fill(TRANSPARENT)\nsurf1.set_colorkey(TRANSPARENT)\npygame.draw.circle(surf1, (0,0,200,100),(100,100), 100)\n\nsurf2 = pygame.Surface((200,200))\nsurf2.fill(TRANSPARENT)\nsurf2.set_colorkey(TRANSPARENT)\npygame.draw.circle(surf2, (200,0,0,100),(100,100), 100)\n\nsurf1.set_alpha(100)\nsurf2.set_alpha(100)\n\nwhile True:\n screen.fill((255,255,255))\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n\n screen.blit(surf1, (100,100,100,100))\n screen.blit(surf2, (200,200,100,100))\n pygame.display.flip()\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
353,309
<p>I need a <a href="http://www.codeproject.com/KB/dotnet/regextutorial.aspx" rel="nofollow noreferrer">Regular Expressions</a> to get the text within 2 tags.</p> <p>Lets say I want an array returned containing <strong>any text within <code>&lt;data</code>> and <code>&lt;/data</code>> tags.</strong> Or any text <strong>within "(" and ")" tags.</strong></p> <p>How can I do that with RegEx's in C#?</p> <hr> <p>An advanced question would be:</p> <ol> <li>The input string is <strong>"color=rgb(50,20,30)"</strong></li> <li>How can I get the 3 numbers in 3 seperate array slots as returned by the RegEx processor in C#?</li> </ol>
[ { "answer_id": 353319, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$string =~ /color=rgb\\((\\d+),(\\d+),(\\d+)\\)/;\n@array = ($1,$2,$3);\n" }, { "answer_id": 353386, "author": "IgorK", "author_id": 44647, "author_profile": "https://Stackoverflow.com/users/44647", "pm_score": 0, "selected": false, "text": "<data><data>123</data><data>456</data></data> <data>" }, { "answer_id": 353587, "author": "Joel Mueller", "author_id": 24380, "author_profile": "https://Stackoverflow.com/users/24380", "pm_score": 3, "selected": true, "text": "private static readonly Regex RgbValuePattern = new Regex(@\"(?<r>\\d{1,3}) ?, ?(?<g>\\d{1,3}) ?, ?(?<b>\\d{1,3})\",\n RegexOptions.Compiled | RegexOptions.ExplicitCapture);\n var match = RgbValuePattern.Match(value);\n\nif (match.Success)\n{\n int r = Int32.Parse(match.Groups[\"r\"].Value, NumberFormatInfo.InvariantInfo);\n int g = Int32.Parse(match.Groups[\"g\"].Value, NumberFormatInfo.InvariantInfo);\n int b = Int32.Parse(match.Groups[\"b\"].Value, NumberFormatInfo.InvariantInfo);\n return Color.FromArgb(r, g, b);\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41021/" ]
353,326
<p>I have a Rake task (in lib/tasks directory) that I run with cron on my shared web hosting. The problem is that I want to compare a UTF-8 string using case statment but my source code is not UTF-8 encoded. If I save source code as UTF-8 there is error when I try to start it :(</p> <p>What I have to do? </p> <p>May be read this strings from external UTF-8 txt file?</p> <p>P.S. I'm using Ruby 1.8</p> <p>P.S. I mean compare this way:</p> <pre><code>result = case utf8string when 'АБВ': 1 when 'ГДИ': 2 when 'ЙКЛ': 3 when 'МНО': 4 else 5 end </code></pre>
[ { "answer_id": 354272, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 0, "selected": false, "text": "mb_chars result = case utf8string.mb_chars\n when 'АБВ': 1\n when 'ГДИ': 2\n when 'ЙКЛ': 3\n when 'МНО': 4\n else 5\nend\n" }, { "answer_id": 355422, "author": "Julian Popov", "author_id": 44537, "author_profile": "https://Stackoverflow.com/users/44537", "pm_score": 2, "selected": false, "text": "1: Invalid char `\\357' in expression\n1: Invalid char `\\273' in expression\n1: Invalid char `\\277' in expression\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
353,336
<p>I'm completely at loss how the ant task ivy:publish is supposed to work.</p> <p>I would expect that I do my normal build, which creates a bunch of jar files, then I would push those jars to the (local) repository.</p> <p>How can I specify from where to retrieve the built jars, and how would those end up in the repository?</p> <p><strong>Update:</strong></p> <pre><code>&lt;target name="publish-local" description="--&gt; Publish Local"&gt; &lt;ivy:retrieve /&gt; &lt;ivy:publish resolver="local" pubrevision="${release.version}" status="release" update="true" overwrite="true"&gt; &lt;artifacts pattern="${dist.dir}/[organisation]-[module].[ext]" /&gt; &lt;/ivy:publish&gt; &lt;/target&gt; </code></pre> <p>this actually works, I didn't include the retrieve before. </p> <p>But I still have some problems, suppose I want to publish 3 jars, openscada-utils.jar, openscada-utils-sources.jar and openscada-utils-javadocs.jar as openscada-utils-0.9.2.jar, openscada-utils-0.9.2-sources.jar and openscada-utils-0.9.2-javadocs.jar</p> <p>It isn't entirely clear to me, how the actual names are assembled, and where I can specify which names they should get. (Using the fragment above, the jars are always called only utils.jar).</p> <p><strong>Update 1:</strong></p> <p>I got it to work (a bit), but it still doesn't feel right. Somehow all tutorials focus on dependencies from 3rd party projects, but an equally important point for me is to handle project specific dependencies.</p> <p>I have a bunch of sub projects which depend on each other in various ways. Considering ivy:publish it is not clear to me how to start.</p> <ol> <li><p>How do I handle the first version? I have a common version number for all sub projects to indicate that they belong together (lets say 0.9). Therefore the first revision should be 0.9.0, but so far nothing of my projects is in my repository. How do I get Ivy to assign this revision number.</p></li> <li><p>In the course of developing I want to publish the built files again, without changing the revision number so far.</p></li> <li><p>If I'm finished with my work I want to push it to a shared repository (and increase the revision number lets say from 0.9.0 to 0.9.1), what is the recommended approach to do so?</p></li> <li><p>For an actual release, I want to make distributions with dependencies and without, somehow I guess I can use different configurations for that. How can I use that to my advantage?</p></li> </ol>
[ { "answer_id": 353368, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "<ivy:publish resolver=\"local\" pubrevision=\"1.0\"/>\n <artifacts pattern=\"${dist.dir}/[organisation]-[module]-[revision]-[type].[ext]\" />\n <publications>\n <artifact name=\"utils\"/>\n <artifact name=\"utils\" type=\"source\"/>\n <artifact name=\"utils\" type=\"javadocs\"/>\n</publications>\n" }, { "answer_id": 355206, "author": "Jared", "author_id": 44757, "author_profile": "https://Stackoverflow.com/users/44757", "pm_score": 0, "selected": false, "text": "ivy:retrieve ivy:resolve .ivy user.home ivy:publish ivy:resolve ivy:publish <taskdef name=\"ivy-retrieve\" \n classname=\"org.apache.ivy.ant.IvyRetrieve\" \n classpathref=\"ivy.lib\" \n loaderRef=\"ivy.loader\"/>\n<taskdef name=\"ivy-publish\" \n classname=\"org.apache.ivy.ant.IvyPublish\" \n classpathref=\"ivy.lib\" \n loaderRef=\"ivy.loader\"/>\n" }, { "answer_id": 8853823, "author": "Peter Lamberg", "author_id": 1148030, "author_profile": "https://Stackoverflow.com/users/1148030", "pm_score": 2, "selected": false, "text": "<ivy-module version=\"2.0\">\n <info organisation=\"com.example.code\" module=\"MyProject\"\n revision=\"${project.revision}\"/>\n <configurations>\n <conf name=\"runtime\" description=\"\" />\n ... other config elements here...\n </configurations>\n\n <publications defaultconf=\"runtime\">\n <artifact name=\"MyProject\" type=\"jar\" ext=\"jar\" conf=\"runtime\" />\n </publications>\n\n <dependencies>\n ...\n </dependencies>\n</ivy-module>\n <property name=\"project.revision\" value=\"1.0.0\"/>\n\n...\n\n<target name=\"ivy\">\n <ivy:resolve />\n\n <!-- Possible ivy:report, ivy:retrieve and other\n elements for managing your dependencies go here -->\n\n <ivy:deliver conf=\"*(public)\"/> \n</target>\n\n<target name=\"publish\" depends=\"clean, ivy, jar\">\n <ivy:publish resolver=\"local\">\n <!-- possible artifacts elements if your artifacts\n are not in standard location -->\n </ivy:publish>\n</target>\n\n...\n" }, { "answer_id": 12165001, "author": "David W.", "author_id": 368630, "author_profile": "https://Stackoverflow.com/users/368630", "pm_score": 2, "selected": false, "text": "<ivy:deliver/> <ivy:publish> resolver ivy.settings.xml <artifacts> <ivy:publish> ${basedir}/target/archive <ivy:publish resolver=\"public\">\n <artifacts path=\"target/archive/[artifact].[ext]\"/>\n</ivy:publish>\n <ivy:publish> ivy.xml <ivy:deliver> ivy.xml <ivy:publish> ivy.xml <ivy:retrieve> <ivy:deliver> <ivy:publish> pom.xml ivy.xml <ivy:makepom> mvn deploy:deploy-file" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917/" ]
353,342
<p>We have lots of logging calls in our app. Our logger takes a System.Type parameter so it can show which component created the call. Sometimes, when we can be bothered, we do something like:</p> <pre><code>class Foo { private static readonly Type myType = typeof(Foo); void SomeMethod() { Logger.Log(myType, "SomeMethod started..."); } } </code></pre> <p>As this requires getting the Type object only once. However we don't have any actual metrics on this. Anyone got any idea how much this saves over calling this.GetType() each time we log?</p> <p>(I realise I could do the metrics myself with no big problem, but hey, what's StackOverflow for?)</p>
[ { "answer_id": 353435, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "typeof(Test): 2756ms\nTestType (field): 1175ms\ntest.GetType(): 3734ms\n using System;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\n\nclass Test\n{\n const int Iterations = 100000000;\n\n private static readonly Type TestType = typeof(Test);\n\n static void Main()\n {\n int total = 0;\n // Make sure it's JIT-compiled\n Log(typeof(Test)); \n\n Stopwatch sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n total += Log(typeof(Test));\n }\n sw.Stop();\n Console.WriteLine(\"typeof(Test): {0}ms\", sw.ElapsedMilliseconds);\n\n sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n total += Log(TestType);\n }\n sw.Stop();\n Console.WriteLine(\"TestType (field): {0}ms\", sw.ElapsedMilliseconds);\n\n Test test = new Test();\n sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n total += Log(test.GetType());\n }\n sw.Stop();\n Console.WriteLine(\"test.GetType(): {0}ms\", sw.ElapsedMilliseconds);\n }\n\n // I suspect your real Log method won't be inlined,\n // so let's mimic that here\n [MethodImpl(MethodImplOptions.NoInlining)]\n static int Log(Type type)\n {\n return 1;\n }\n}\n" }, { "answer_id": 353436, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 5, "selected": false, "text": "GetType() [MethodImpl(MethodImplOptions.InternalCall)] System.Type GetType() Type Object o1 = new Object();\nType t1 = o1.GetType();\nType t2 = o1.GetType();\nif (object.ReferenceEquals(t1,t2))\n Console.WriteLine(\"same reference\");\n" }, { "answer_id": 353446, "author": "Sam Meldrum", "author_id": 16005, "author_profile": "https://Stackoverflow.com/users/16005", "pm_score": 2, "selected": false, "text": "using System;\n\nnamespace ConsoleApplicationTest {\n class Program {\n static void Main(string[] args) {\n\n int loopCount = 100000000;\n\n System.Diagnostics.Stopwatch timer1 = new System.Diagnostics.Stopwatch();\n timer1.Start();\n Foo foo = new Foo();\n for (int i = 0; i < loopCount; i++) {\n bar.SomeMethod();\n }\n timer1.Stop();\n Console.WriteLine(timer1.ElapsedMilliseconds);\n\n System.Diagnostics.Stopwatch timer2 = new System.Diagnostics.Stopwatch();\n timer2.Start();\n Bar bar = new Bar();\n for (int i = 0; i < loopCount; i++) {\n foo.SomeMethod();\n }\n timer2.Stop();\n Console.WriteLine(timer2.ElapsedMilliseconds);\n\n Console.ReadLine();\n }\n }\n\n public class Bar {\n public void SomeMethod() {\n Logger.Log(this.GetType(), \"SomeMethod started...\");\n }\n }\n\n public class Foo {\n private static readonly Type myType = typeof(Foo); \n public void SomeMethod() { \n Logger.Log(myType, \"SomeMethod started...\"); \n }\n }\n\n public class Logger {\n public static void Log(Type type, string text) {\n }\n }\n}\n" }, { "answer_id": 55802736, "author": "user305874", "author_id": 3399709, "author_profile": "https://Stackoverflow.com/users/3399709", "pm_score": -1, "selected": false, "text": "Object.GetType() typeof(class) Object.GetType() namespace ConsoleApp1\n{\n class Program\n {\n public const int Cycles = 100000000;\n public static int Cycles2 = 100000000;\n public static QSData TestObject = new QSData();\n public static Type TestObjectType;\n\n static void Main(string[] args)\n {\n TestObjectType = TestObject.GetType();\n Console.WriteLine(\"Repeated cycles for each test : \" + Cycles.ToString());\n\n var test1 = TestGetType();\n Console.WriteLine(\"Object.GetType : \" + test1.ToString());\n var test2 = TestTypeOf();\n Console.WriteLine(\"TypeOf(Class) : \" + test2.ToString());\n var test3 = TestVar();\n Console.WriteLine(\"Type var : \" + test3.ToString());\n var test4 = TestEmptyLoop();\n Console.WriteLine(\"Empty Loop : \" + test4.ToString());\n\n Console.WriteLine(\"\\r\\nClean overview:\");\n Console.WriteLine(\"Object.GetType : \" + (test1 - test4).ToString());\n Console.WriteLine(\"TypeOf(Class) : \" + (test2 - test4).ToString());\n Console.WriteLine(\"Type var : \" + (test3 - test4).ToString());\n\n Console.WriteLine(\"\\n\\rPush a button to exit\");\n String input = Console.ReadLine();\n }\n\n static long TestGetType()\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i < Cycles; i++)\n {\n Type aType = TestObject.GetType();\n }\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n\n static long TestTypeOf()\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i < Cycles; i++)\n {\n Type aType = typeof(QSData);\n }\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n\n static long TestVar()\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i < Cycles; i++)\n {\n Type aType = TestObjectType;\n }\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n\n static long TestEmptyLoop()\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i < Cycles; i++)\n {\n Type aType;\n }\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3856/" ]
353,353
<p>I am trying to use onkeypress on an input type="text" control to fire off some javascript if the enter button is pressed. It works on most pages, but I also have some pages with custom .NET controls.</p> <p>The problem is that the .NET submit fires before the onkeypress. Does anybody have an insight on how to make onkeypress fire first?</p> <p>If it helps, here is my javascript:</p> <pre><code> function SearchSiteSubmit(myfield, e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; else return true; if (keycode == 13) { SearchSite(); return false; } else return true; } </code></pre>
[ { "answer_id": 353435, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "typeof(Test): 2756ms\nTestType (field): 1175ms\ntest.GetType(): 3734ms\n using System;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\n\nclass Test\n{\n const int Iterations = 100000000;\n\n private static readonly Type TestType = typeof(Test);\n\n static void Main()\n {\n int total = 0;\n // Make sure it's JIT-compiled\n Log(typeof(Test)); \n\n Stopwatch sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n total += Log(typeof(Test));\n }\n sw.Stop();\n Console.WriteLine(\"typeof(Test): {0}ms\", sw.ElapsedMilliseconds);\n\n sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n total += Log(TestType);\n }\n sw.Stop();\n Console.WriteLine(\"TestType (field): {0}ms\", sw.ElapsedMilliseconds);\n\n Test test = new Test();\n sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n total += Log(test.GetType());\n }\n sw.Stop();\n Console.WriteLine(\"test.GetType(): {0}ms\", sw.ElapsedMilliseconds);\n }\n\n // I suspect your real Log method won't be inlined,\n // so let's mimic that here\n [MethodImpl(MethodImplOptions.NoInlining)]\n static int Log(Type type)\n {\n return 1;\n }\n}\n" }, { "answer_id": 353436, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 5, "selected": false, "text": "GetType() [MethodImpl(MethodImplOptions.InternalCall)] System.Type GetType() Type Object o1 = new Object();\nType t1 = o1.GetType();\nType t2 = o1.GetType();\nif (object.ReferenceEquals(t1,t2))\n Console.WriteLine(\"same reference\");\n" }, { "answer_id": 353446, "author": "Sam Meldrum", "author_id": 16005, "author_profile": "https://Stackoverflow.com/users/16005", "pm_score": 2, "selected": false, "text": "using System;\n\nnamespace ConsoleApplicationTest {\n class Program {\n static void Main(string[] args) {\n\n int loopCount = 100000000;\n\n System.Diagnostics.Stopwatch timer1 = new System.Diagnostics.Stopwatch();\n timer1.Start();\n Foo foo = new Foo();\n for (int i = 0; i < loopCount; i++) {\n bar.SomeMethod();\n }\n timer1.Stop();\n Console.WriteLine(timer1.ElapsedMilliseconds);\n\n System.Diagnostics.Stopwatch timer2 = new System.Diagnostics.Stopwatch();\n timer2.Start();\n Bar bar = new Bar();\n for (int i = 0; i < loopCount; i++) {\n foo.SomeMethod();\n }\n timer2.Stop();\n Console.WriteLine(timer2.ElapsedMilliseconds);\n\n Console.ReadLine();\n }\n }\n\n public class Bar {\n public void SomeMethod() {\n Logger.Log(this.GetType(), \"SomeMethod started...\");\n }\n }\n\n public class Foo {\n private static readonly Type myType = typeof(Foo); \n public void SomeMethod() { \n Logger.Log(myType, \"SomeMethod started...\"); \n }\n }\n\n public class Logger {\n public static void Log(Type type, string text) {\n }\n }\n}\n" }, { "answer_id": 55802736, "author": "user305874", "author_id": 3399709, "author_profile": "https://Stackoverflow.com/users/3399709", "pm_score": -1, "selected": false, "text": "Object.GetType() typeof(class) Object.GetType() namespace ConsoleApp1\n{\n class Program\n {\n public const int Cycles = 100000000;\n public static int Cycles2 = 100000000;\n public static QSData TestObject = new QSData();\n public static Type TestObjectType;\n\n static void Main(string[] args)\n {\n TestObjectType = TestObject.GetType();\n Console.WriteLine(\"Repeated cycles for each test : \" + Cycles.ToString());\n\n var test1 = TestGetType();\n Console.WriteLine(\"Object.GetType : \" + test1.ToString());\n var test2 = TestTypeOf();\n Console.WriteLine(\"TypeOf(Class) : \" + test2.ToString());\n var test3 = TestVar();\n Console.WriteLine(\"Type var : \" + test3.ToString());\n var test4 = TestEmptyLoop();\n Console.WriteLine(\"Empty Loop : \" + test4.ToString());\n\n Console.WriteLine(\"\\r\\nClean overview:\");\n Console.WriteLine(\"Object.GetType : \" + (test1 - test4).ToString());\n Console.WriteLine(\"TypeOf(Class) : \" + (test2 - test4).ToString());\n Console.WriteLine(\"Type var : \" + (test3 - test4).ToString());\n\n Console.WriteLine(\"\\n\\rPush a button to exit\");\n String input = Console.ReadLine();\n }\n\n static long TestGetType()\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i < Cycles; i++)\n {\n Type aType = TestObject.GetType();\n }\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n\n static long TestTypeOf()\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i < Cycles; i++)\n {\n Type aType = typeof(QSData);\n }\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n\n static long TestVar()\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i < Cycles; i++)\n {\n Type aType = TestObjectType;\n }\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n\n static long TestEmptyLoop()\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i < Cycles; i++)\n {\n Type aType;\n }\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42574/" ]
353,354
<p><code>DBCC SHRINKFILE</code> always works when I run it manually on a log file, even when I get the following message:</p> <pre><code>'Cannot shrink log file 2 (Claim_Log) because all logical log files are in use.' </code></pre> <p>When I run it from a job, however, it only shrinks the log about one third of the time. The other times, it just remains large (about 150Gb). There is never any error other than the one listed above. This is the statement that I use:</p> <pre><code>DBCC SHRINKFILE (N'Claim_log' , 0, TRUNCATEONLY) </code></pre> <p>I have "Include step output in history" enabled on the job step. Is there something else I can do to get more information on why this isn't working?</p> <p>Edit: Here is the full message from the log:</p> <pre><code>'Executed as user: *. Cannot shrink log file 2 (Claim_Log) because all logical log files are in use. [SQLSTATE 01000] (Message 9008) DBCC execution completed. If DBCC printed error messages, contact your system administrator. [SQLSTATE 01000] (Message 2528). The step succeeded.' </code></pre> <p>I have already tried kicking users out of the db and setting it to single user mode.</p>
[ { "answer_id": 6591447, "author": "MrEs", "author_id": 211718, "author_profile": "https://Stackoverflow.com/users/211718", "pm_score": 3, "selected": true, "text": "Execute SP_ReplicationDbOption {DBName},Publish,true,1\nGO\nExecute sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1\nGO\nDBCC ShrinkFile({LogFileName},0)\nGO\nExecute SP_ReplicationDbOption {DBName},Publish,false,1\nGO\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22448/" ]
353,379
<p>I have a PHP application that will on occasion have to handle URLs where more than one parameter in the URL will have the same name. Is there an easy way to retrieve all the values for a given key? PHP $_GET returns only the last value. </p> <p>To make this concrete, my application is an OpenURL resolver, and may get URL parameters like this:</p> <pre><code>ctx_ver=Z39.88-2004 &amp;rft_id=info:oclcnum/1903126 &amp;rft_id=http://www.biodiversitylibrary.org/bibliography/4323 &amp;rft_val_fmt=info:ofi/fmt:kev:mtx:book &amp;rft.genre=book &amp;rft.btitle=At last: a Christmas in the West Indies. &amp;rft.place=London, &amp;rft.pub=Macmillan and co., &amp;rft.aufirst=Charles &amp;rft.aulast=Kingsley &amp;rft.au=Kingsley, Charles, &amp;rft.pages=1-352 &amp;rft.tpages=352 &amp;rft.date=1871 </code></pre> <p>(Yes, I know it's ugly, welcome to my world). Note that the key "rft_id" appears twice:</p> <ol> <li><code>rft_id=info:oclcnum/1903126</code></li> <li><code>rft_id=http://www.biodiversitylibrary.org/bibliography/4323</code></li> </ol> <p><code>$_GET</code> will return just <code>http://www.biodiversitylibrary.org/bibliography/4323</code>, the earlier value (<code>info:oclcnum/1903126</code>) having been overwritten.</p> <p>I'd like to get access to both values. Is this possible in PHP? If not, any thoughts on how to handle this problem?</p>
[ { "answer_id": 353400, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 3, "selected": false, "text": "$_SERVER['QUERY_STRING'] $query = $_SERVER['QUERY_STRING'];\n$vars = array();\nforeach (explode('&', $query) as $pair) {\n list($key, $value) = explode('=', $pair);\n $vars[] = array(urldecode($key), urldecode($value));\n}\n $vars array(\n array('ctx_ver' => 'Z39.88-2004'),\n array('rft_id' => 'info:oclcnum/1903126'),\n array('rft_id' => 'http://www.biodiversitylibrary.org/bibliography/4323'),\n array('rft_val_fmt' => 'info:ofi/fmt:kev:mtx:book'),\n array('rft.genre' => 'book'),\n array('rft.btitle' => 'At last: a Christmas in the West Indies.'),\n array('rft.place' => 'London'),\n array('rft.pub' => 'Macmillan and co.'),\n array('rft.aufirst' => 'Charles'),\n array('rft.aulast' => 'Kingsley'),\n array('rft.au' => 'Kingsley, Charles'),\n array('rft.pages' => '1-352'),\n array('rft.tpages' => '352'),\n array('rft.date' => '1871')\n)\n" }, { "answer_id": 353409, "author": "Neil Aitken", "author_id": 13803, "author_profile": "https://Stackoverflow.com/users/13803", "pm_score": 2, "selected": false, "text": "$_GET $_SERVER['QUERY_STRING']" }, { "answer_id": 353423, "author": "benlumley", "author_id": 39161, "author_profile": "https://Stackoverflow.com/users/39161", "pm_score": 6, "selected": false, "text": "someurl.php?name[]=aaa&name[]=bbb\n array(0=>'aaa', 1=>'bbb')\n" }, { "answer_id": 353437, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 7, "selected": true, "text": "$query = explode('&', $_SERVER['QUERY_STRING']);\n$params = array();\n\nforeach( $query as $param )\n{\n // prevent notice on explode() if $param has no '='\n if (strpos($param, '=') === false) $param += '=';\n\n list($name, $value) = explode('=', $param, 2);\n $params[urldecode($name)][] = urldecode($value);\n}\n array(\n 'ctx_ver' => array('Z39.88-2004'),\n 'rft_id' => array('info:oclcnum/1903126', 'http://www.biodiversitylibrary.org/bibliography/4323'),\n 'rft_val_fmt' => array('info:ofi/fmt:kev:mtx:book'),\n 'rft.genre' => array('book'),\n 'rft.btitle' => array('At last: a Christmas in the West Indies.'),\n 'rft.place' => array('London'),\n 'rft.pub' => array('Macmillan and co.'),\n 'rft.aufirst' => array('Charles'),\n 'rft.aulast' => array('Kingsley'),\n 'rft.au' => array('Kingsley, Charles'),\n 'rft.pages' => array('1-352'),\n 'rft.tpages' => array('352'),\n 'rft.date' => array('1871')\n)\n" }, { "answer_id": 11332611, "author": "MonsterDev", "author_id": 1502060, "author_profile": "https://Stackoverflow.com/users/1502060", "pm_score": 2, "selected": false, "text": "public static function getMultipleParameters()\n {\n $query = $_SERVER['QUERY_STRING'];\n $vars = array();\n $second = array();\n foreach (explode('&', $query) as $pair) {\n list($key, $value) = explode('=', $pair);\n if('' == trim($value)){\n continue;\n }\n\n if (array_key_exists($key, $vars)) {\n if (!array_key_exists($key, $second))\n $second[$key][] .= $vars[$key];\n $second[$key][] = $value;\n } else {\n $vars[$key] = urldecode($value);\n }\n }\n return array_merge($vars, $second);\n }\n array (\n 'param1' => '2549',\n 'appname' => \n array (\n 0 => 'appName1',\n 1 => 'appName2',\n 2 => 'appName3',\n 3 => 'appName4',\n 4 => 'appName5',\n ),\n 'apptype' => 'thetype',\n 'idsess' => '1231324567980147dzeze55sd4',\n 'action' => 'myaction',\n);\n" }, { "answer_id": 16464048, "author": "Timo Huovinen", "author_id": 175071, "author_profile": "https://Stackoverflow.com/users/175071", "pm_score": 2, "selected": false, "text": "function parse_mstr($query_string,&$query=array()){\n $query = $query? $query: array();\n $params = explode('&', $query_string);\n foreach( $params as $param ){\n $k = $param;\n $v = '';\n if(strpos($param,'=')){\n list($name, $value) = explode('=', $param);\n $k = rawurldecode($name);\n $v = rawurldecode($value);\n }\n if(array_key_exists($k, $query)){\n if(is_array($query[$k])){\n $query[$k][] = $v;\n }else{\n $query[$k] = array($query[$k],$v);\n }\n }else{\n $query[$k] = $v;\n }\n }\n}\n\n// usage\nparse_mstr('a=1&a=2&b=3', $arr);\n\n// resulting array\n$arr = [\n 'a' => ['1', '2'],\n 'b' => '3'\n]\n" }, { "answer_id": 32701296, "author": "mario", "author_id": 345031, "author_profile": "https://Stackoverflow.com/users/345031", "pm_score": 3, "selected": false, "text": "explode // Replace `&x=1&x=2` into `x[]=1&x[]=2`\n$qs = preg_replace(\"/(?<=^|&)(\\w+)(?==)/\", \"$1[]\", $_SERVER[\"QUERY_STRING\"]);\n parse_str parse_str($qs, $new_GET);\n %xy (id|name) (\\w+)" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9684/" ]
353,380
<p>I realize there's no definitely "right" answer to this question, but when people talk about lines of code, what do they mean? In C++ for example, do you count blank lines? Comments? Lines with just an open or close brace?</p> <p>I know some people use lines of code as a productivity measure, and I'm wondering if there is a standard convention here. Also, I think there's a way to get various compilers to count lines of code - is there a standard convention there?</p>
[ { "answer_id": 353412, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "Dim obj as Object\n If _amount > 0 Then\n _amount += 5\nElse\n _amount -= 5\nEnd If\n" }, { "answer_id": 353420, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 4, "selected": false, "text": "for (i=0; i<100; ++i) printf(\"hello\"); /* How many lines of code is this? */\n" }, { "answer_id": 353548, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 1, "selected": false, "text": "int i = 7; # one statement terminator; one (1) statement\nif (r == 9) # count the if as one (1) statement\n output(\"Yes\"); # one statement terminator; one (1) statement; total (2) for the if\nwhile (n <= 14) { # count the while as one (1) statement\n output(\"n = \", n); # one statement terminator; one (1) statement\n do_something(); # one statement terminator; one (1) statement\n n++ # count this one, one statement (1), even though it doesn't need a statement terminator in some languages\n} # brace doesn't count; total (4) for the while\n" }, { "answer_id": 385206, "author": "Chris Nava", "author_id": 45163, "author_profile": "https://Stackoverflow.com/users/45163", "pm_score": 1, "selected": false, "text": "wc -l" }, { "answer_id": 664274, "author": "Jonas Kölker", "author_id": 58668, "author_profile": "https://Stackoverflow.com/users/58668", "pm_score": 0, "selected": false, "text": "wc -l '\\n' ';' '{' '/'" }, { "answer_id": 73345674, "author": "Rostam Bamasi", "author_id": 16083592, "author_profile": "https://Stackoverflow.com/users/16083592", "pm_score": 0, "selected": false, "text": " (GCI -include *.c -recurse | select-string .).Count\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44444/" ]
353,414
<p>I have inherited an ASP.NET 2.0 project and one of the things I have noticed is that the user has to click a <code>dropdownlist</code> twice in order to expand it - why is this?</p> <p><strong>Sequence of Events</strong></p> <ol> <li>The first click with give the control focus and the second will expand it.</li> <li>The application uses Master/Content pages and is Ajax enabled.</li> </ol> <p>It looks like this doesn't happen in IE6, but does happen in IE7.</p>
[ { "answer_id": 355823, "author": "DilbertDave", "author_id": 31580, "author_profile": "https://Stackoverflow.com/users/31580", "pm_score": 1, "selected": false, "text": " function inputOnFocus(objInput)\n {\n objInput.style.backgroundColor = sHighLightBgColor;\n objInput.style.border = sBorderHighlight;\n\n //objInput.className = \"inputOnFocus\";\n sIDWithFocus = objInput.id;\n }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31580/" ]
353,421
<p>I'm trying to debug an ASP.Net web project that I received. I modified a class in the <code>"Apps_LocalResources"</code> folder. </p> <p>When I debug and the code tries to step into that class, I get </p> <blockquote> <p>"The source file is different from when the module was built.". </p> </blockquote> <p>I rebuilt the solution and didn't get any change. I even published it to a different location and the pdb and dll in the bin folder didn't change so I didn't copy them over. </p> <p>Ideas?</p>
[ { "answer_id": 30935730, "author": "M463", "author_id": 3336376, "author_profile": "https://Stackoverflow.com/users/3336376", "pm_score": 0, "selected": false, "text": "Release" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
353,424
<p>Is it possible to generate a list of all source members within an iSeries source file using SQL?</p> <p>Might be similar to getting table definitions from SYSTABLES and SYSCOLUMNS, but I'm unable to find anything so far.</p>
[ { "answer_id": 362550, "author": "squarefox", "author_id": 33402, "author_profile": "https://Stackoverflow.com/users/33402", "pm_score": 4, "selected": true, "text": "select table_schema , table_name from qsys2.systables where File_type = 'S'\n db2 -S \"select '/QSYS.LIB/' concat table_schema concat '.LIB/' concat table_name concat '.FILE' from qsys2.systables where File_type = 'S'\" | grep '/' | xargs -n1 find >/home/myuser/myfile \n" }, { "answer_id": 22822770, "author": "Michael Delk", "author_id": 3282641, "author_profile": "https://Stackoverflow.com/users/3282641", "pm_score": 0, "selected": false, "text": "SELECT sys_dname, sys_tname \nFROM qsys2/systables \nORDER BY sys_dname, sys_tname\n" }, { "answer_id": 28607340, "author": "stephj", "author_id": 4583979, "author_profile": "https://Stackoverflow.com/users/4583979", "pm_score": 2, "selected": false, "text": "DSPFD FILE(Libname/Filename)\n TYPE(*MBRLIST) \n OUTPUT(*OUTFILE) \n OUTFILE(QTEMP/MBRLIST)\n SELECT MLNAME FROM MBRLIST\n" }, { "answer_id": 34931703, "author": "John Y", "author_id": 95852, "author_profile": "https://Stackoverflow.com/users/95852", "pm_score": 4, "selected": false, "text": "SELECT TABLE_PARTITION FROM SYSPARTITIONSTAT\nWHERE TABLE_NAME = myfile AND TABLE_SCHEMA = mylib\n SYSPARTITIONSTAT" }, { "answer_id": 42103335, "author": "Alfredo", "author_id": 7532001, "author_profile": "https://Stackoverflow.com/users/7532001", "pm_score": 0, "selected": false, "text": "find '/QSYS.LIB/' -name '*.MBR' -exec grep -rins '#IFSIO_H' {} \\; \n" }, { "answer_id": 53676729, "author": "smeep", "author_id": 3780416, "author_profile": "https://Stackoverflow.com/users/3780416", "pm_score": 1, "selected": false, "text": "SELECT SYSTEM_TABLE_MEMBER, SOURCE_TYPE FROM QSYS2/SYSPARTITIONSTAT WHERE\nSYSTEM_TABLE_SCHEMA = 'MYLIB' AND SYSTEM_TABLE_NAME = 'QRPGLESRC'\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23447/" ]
353,425
<p>I have a Stored Procedure called spGetOrders which accepts a few parameters: @startdate and @enddate. This queries an "Orders" table. One of the columns in the table is called "ClosedDate". This column will hold NULL if an order hasn't been closed or a date value if it has. I'd like to add a @Closed parameter which will take a bit value. In a simple world, I'd be able to do.. </p> <pre><code>select * from orders o where o.orderdate between @startdate AND @enddate and (if @Closed = 1 then o.ClosedDate IS NULL else o.ClosedDate IS NOT NULL) </code></pre> <p>Obviously, that's not going to work.. I'm also looking at dynamic sql which is my last resort, but starting to look like the answer.. </p> <p>Please help.. </p>
[ { "answer_id": 353441, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 2, "selected": false, "text": "SELECT * \nFROM orders \nWHERE orderdate BETWEEN @startdate AND @enddate \nAND (@Closed = 1 OR CLosedDate IS NOT NULL)\n" }, { "answer_id": 353449, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 5, "selected": true, "text": "select * from orders o\nwhere o.orderdate between @startdate AND @enddate\nand ((@Closed = 1 And o.ClosedDate IS NULL) Or (@Closed = 0 And o.ClosedDate IS NOT NULL))\n" }, { "answer_id": 353451, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 0, "selected": false, "text": "select * from orders o\nwhere o.orderdate between @startdate AND @enddate\nand ( (@Closed = 1 AND o.ClosedDate IS NULL)\n OR (ISNULL(@Closed, 0) <> 1 AND o.ClosedDate IS NOT NULL)\n )\n" }, { "answer_id": 353456, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select * from orders o\nwhere o.orderdate between @startdate AND @enddate\nand ((@Closed = 1 and o.ClosedDate IS NULL)\n or (@Closed != 1 and o.ClosedDate IS NOT NULL))\n" }, { "answer_id": 73145190, "author": "outis", "author_id": 90527, "author_profile": "https://Stackoverflow.com/users/90527", "pm_score": 0, "selected": false, "text": "if-then-else if-then 1 if p then q if p then q else true closedDate @Closed @Closed closedDate NULL IF IF IF(<test>, <then condition>, <else condition>) IIF CASE @Close 1 IF(@Closed, o.ClosedDate IS NOT NULL, o.ClosedDate IS NULL) IF CASE IF CASE CASE CASE CASE -- simple: compare top <expression> to each WHEN <expression>\nCASE <expression>\n WHEN <expression> THEN ...\n ...\n ELSE ...\nEND\n\n-- searched: test each <expression>\nCASE \n WHEN <expression> THEN ...\n ...\n ELSE ...\nEND\n if-then-else CASE \n WHEN @Closed THEN o.ClosedDate IS NOT NULL\n ELSE o.ClosedDate IS NULL\nEND\n CASE @Closed\n WHEN 1 THEN o.ClosedDate IS NOT NULL\n WHEN 0 THEN o.ClosedDate IS NULL\n ELSE 1\nEND\n CASE @Closed\n WHEN 1 THEN o.ClosedDate IS NOT NULL\n ELSE o.ClosedDate IS NULL\nEND\n\n-- or\nCASE @Closed\n WHEN 0 THEN o.ClosedDate IS NULL\n ELSE o.ClosedDate IS NOT NULL\nEND\n CASE if p then q p implies q p ⇒ q not p or q ¬p ∨ q if p then q else r p ? q : r (if p then q) and (if not p then r) (p ⇒ q) ∧ (¬p ⇒ q) (if p then q and not r) and (if not p then not q and r) (p ⇒ q∧¬r) ∧ (¬p ⇒ ¬q∧r) if-then-else -- interpretation 1\n (NOT <test> OR <then condition>) \nAND ( <test> OR <else condition>)\n\n-- interpretation 2\n (NOT <test> OR ( <then condition> AND NOT <else condition>))\nAND ( <test> OR (NOT <then condition> AND <else condition>)\n IF() CASE q r (@Closed OR o.ClosedDate IS NOT NULL) AND (NOT @Closed OR o.ClosedDate IS NULL)\n IF CASE IF CASE IF CASE IF IF <test> THEN\n SELECT ... WHERE <then condition> ...\nELSE\n SELECT ... WHERE <else condition> ...\nEND IF\n CASE CASE END CASE CASE IF CASE\n WHEN <test> THEN\n SELECT ... WHERE <then condition> ...\n ELSE\n SELECT ... WHERE <else condition> ...\nEND CASE\n IF @Closed THEN\n SELECT *\n FROM Orders o\n WHERE o.OrderDate BETWEEN @startDate AND @endDate\n AND o.ClosedDate IS NOT NULL;\nELSE\n SELECT *\n FROM Orders o\n WHERE o.OrderDate BETWEEN @startDate AND @endDate\n AND o.ClosedDate IS NULL;\nEND IF;\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954/" ]
353,430
<p>I'm building a custom property grid that displays the properties of items in a collection. What I want to do is show only the properties in the grid that are common amongst each item. I am assuming the best way to do this would be to find the the common base class of each type in the collection and display it's properties. Is there any easier way? Can you give me a code example of the best approach to do this?</p>
[ { "answer_id": 353492, "author": "matt_dev", "author_id": 39086, "author_profile": "https://Stackoverflow.com/users/39086", "pm_score": 0, "selected": false, "text": "public int Compare(T x, T y)\n{\n PropertyInfo[] props = x.GetType().GetProperties();\n\n foreach(PropertyInfo info in props)\n {\n if(info.name == y.GetType().Name)\n ....\n }\n\n ...\n" }, { "answer_id": 353533, "author": "Tony Peterson", "author_id": 26140, "author_profile": "https://Stackoverflow.com/users/26140", "pm_score": 3, "selected": true, "text": "static void Main(string[] args)\n{\n Console.WriteLine(\"Common Types: \" + GetCommonBaseClass(new Type[] {typeof(OleDbCommand), typeof(OdbcCommand), typeof(SqlCommand)}).ToString()); \n}\n static Type GetCommonBaseClass(Type[] types)\n {\n if (types.Length == 0)\n return (typeof(object));\n else if (types.Length == 1)\n return (types[0]);\n\n // Copy the parameter so we can substitute base class types in the array without messing up the caller\n Type[] temp = new Type[types.Length];\n\n for (int i = 0; i < types.Length; i++)\n {\n temp[i] = types[i];\n }\n\n bool checkPass = false;\n\n Type tested = null;\n\n while (!checkPass)\n {\n tested = temp[0];\n\n checkPass = true;\n\n for (int i = 1; i < temp.Length; i++)\n {\n if (tested.Equals(temp[i]))\n continue;\n else\n {\n // If the tested common basetype (current) is the indexed type's base type\n // then we can continue with the test by making the indexed type to be its base type\n if (tested.Equals(temp[i].BaseType))\n {\n temp[i] = temp[i].BaseType;\n continue;\n }\n // If the tested type is the indexed type's base type, then we need to change all indexed types\n // before the current type (which are all identical) to be that base type and restart this loop\n else if (tested.BaseType.Equals(temp[i]))\n {\n for (int j = 0; j <= i - 1; j++)\n {\n temp[j] = temp[j].BaseType;\n }\n\n checkPass = false;\n break;\n }\n // The indexed type and the tested type are not related\n // So make everything from index 0 up to and including the current indexed type to be their base type\n // because the common base type must be further back\n else\n {\n for (int j = 0; j <= i; j++)\n {\n temp[j] = temp[j].BaseType;\n }\n\n checkPass = false;\n break;\n }\n }\n }\n\n // If execution has reached here and checkPass is true, we have found our common base type, \n // if checkPass is false, the process starts over with the modified types\n }\n\n // There's always at least object\n return tested;\n }\n" }, { "answer_id": 353672, "author": "Morten Christiansen", "author_id": 4055, "author_profile": "https://Stackoverflow.com/users/4055", "pm_score": 0, "selected": false, "text": "class TypeHandler\n{\n public static List<string> GetCommonProperties(Type[] types)\n {\n Dictionary<string, int> propertyCounts = new Dictionary<string, int>();\n\n foreach (Type type in types)\n {\n foreach (PropertyInfo info in type.GetProperties())\n {\n string name = info.Name;\n if (!propertyCounts.ContainsKey(name)) propertyCounts.Add(name, 0);\n propertyCounts[name]++;\n }\n }\n\n List<string> propertyNames = new List<string>();\n\n foreach (string name in propertyCounts.Keys)\n {\n if (propertyCounts[name] == types.Length) propertyNames.Add(name);\n }\n\n return propertyNames;\n }\n}\n return (from t in types\n from p in t.GetProperties()\n group p by p.Name into pg\n where pg.Count() == types.Length\n select pg.Key).ToList();\n" }, { "answer_id": 353742, "author": "mepcotterell", "author_id": 43312, "author_profile": "https://Stackoverflow.com/users/43312", "pm_score": 2, "selected": false, "text": "public static String[] GetCommonPropertiesByName(Object[] objs)\n{\n List<Type> typeList = new List<Type>(Type.GetTypeArray(objs));\n List<String> propertyList = new List<String>();\n List<String> individualPropertyList = new List<String>();\n\n foreach (Type type in typeList)\n {\n foreach (PropertyInfo property in type.GetProperties())\n {\n propertyList.Add(property.Name);\n }\n }\n\n propertyList = propertyList.Distinct().ToList();\n\n foreach (Type type in typeList)\n {\n individualPropertyList.Clear();\n\n foreach (PropertyInfo property in type.GetProperties())\n {\n individualPropertyList.Add(property.Name);\n }\n\n propertyList = propertyList.Intersect(individualPropertyList).ToList();\n }\n\n return propertyList.ToArray();\n}\n PropertyInfo p = t.GetType().GetProperty(\"some Property String Name\");\np.GetValue(t, null);\np.SetValue(t, someNewValue, null);\n GetCommonPropertiesByName" }, { "answer_id": 355814, "author": "PolyglotProgrammer", "author_id": 34690, "author_profile": "https://Stackoverflow.com/users/34690", "pm_score": 0, "selected": false, "text": "internal class BaseFinder\n{\n public static Type FindBase(params Type[] types)\n {\n if (types == null)\n return null;\n\n if (types.Length == 0)\n return null;\n\n Dictionary<Type, IList<Type>> baseTypeMap = new Dictionary<Type,IList<Type>>();\n\n // get all the base types and note the one with the longest base tree\n int maxBaseCount = 0;\n Type typeWithLongestBaseTree = null;\n foreach (Type type in types)\n {\n IList<Type> baseTypes = GetBaseTree(type);\n if (baseTypes.Count > maxBaseCount)\n {\n typeWithLongestBaseTree = type;\n maxBaseCount = baseTypes.Count;\n }\n baseTypeMap.Add(type, baseTypes);\n }\n\n // walk down the tree until we get to a common base type\n IList<Type> longestBaseTree = baseTypeMap[typeWithLongestBaseTree];\n for (int baseIndex = 0; baseIndex < longestBaseTree.Count;baseIndex++)\n {\n int commonBaseCount = 0;\n foreach (Type type in types)\n {\n IList<Type> baseTypes = baseTypeMap[type];\n if (!baseTypes.Contains(longestBaseTree[baseIndex]))\n break;\n commonBaseCount++;\n }\n if (commonBaseCount == types.Length)\n return longestBaseTree[baseIndex];\n }\n return null;\n }\n\n private static IList<Type> GetBaseTree(Type type)\n {\n List<Type> result = new List<Type>();\n Type baseType = type.BaseType;\n do\n {\n result.Add(baseType);\n baseType = baseType.BaseType;\n } while (baseType != typeof(object));\n return result;\n }\n}\n" }, { "answer_id": 701880, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public static Type GetCommonBaseClass (params Type[] types)\n{\n if (types.Length == 0)\n return typeof(object);\n\n Type ret = types[0];\n\n for (int i = 1; i < types.Length; ++i)\n {\n if (types[i].IsAssignableFrom(ret))\n ret = types[i];\n else\n {\n // This will always terminate when ret == typeof(object)\n while (!ret.IsAssignableFrom(types[i]))\n ret = ret.BaseType;\n }\n }\n\n return ret;\n}\n Type t = GetCommonBaseClass(typeof(OleDbCommand),\n typeof(OdbcCommand),\n typeof(SqlCommand));\n typeof(DbCommand) Type t = GetCommonBaseClass(typeof(OleDbCommand),\n typeof(OdbcCommand),\n typeof(SqlCommand),\n typeof(Component));\n typeof(Compoment) Type t = GetCommonBaseClass(typeof(OleDbCommand),\n typeof(OdbcCommand),\n typeof(SqlCommand),\n typeof(Component),\n typeof(Component).BaseType);\n typeof(MarshalByRefObject) Type t = GetCommonBaseClass(typeof(OleDbCommand),\n typeof(OdbcCommand),\n typeof(SqlCommand),\n typeof(Component),\n typeof(Component).BaseType,\n typeof(int));\n typeof(object)" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
353,464
<p>Is there a way to use verbatim String literals in managed C++? Similar to C#'s</p> <pre><code>String Docs = @"c:\documents and settings\" </code></pre>
[ { "answer_id": 15201457, "author": "Wang", "author_id": 1492613, "author_profile": "https://Stackoverflow.com/users/1492613", "pm_score": 4, "selected": true, "text": "cout<<R\"((\\\"ddd\\aa)\\n)\"<<endl;\ncout<<R\"delimiter((\\\"ddd\\aa)\\n)delimiter\"<<endl;\n (\\\"ddd\\aa)\\n\n(\\\"ddd\\aa)\\n\n" }, { "answer_id": 26284953, "author": "Cameron", "author_id": 86375, "author_profile": "https://Stackoverflow.com/users/86375", "pm_score": 2, "selected": false, "text": "String^ f = gcnew String(R\"(C:\\foo\\bar.txt)\");\n char *x = R\"(C:\\foo\\bar.txt)\";\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831/" ]
353,481
<p>I know this is particularly difficult with CSS and the current set of browsers, but nonetheless I have the requirement.</p> <p>I need to be able to have 3 divs in a column. Each div should be able to take up a certain percentage of the vertical space (for example, 33%). The contents of each div <em>could</em> end up being larger than the available space, so the div should be able to overflow and give the user scrollbars.</p> <p>My problem is that I'm having trouble figuring out how to give each panel that vertical height. Any ideas?</p>
[ { "answer_id": 353522, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 1, "selected": false, "text": "<html>\n<head>\n<style type=\"text/css\">\n#one {height: 33%; overflow: auto;}\n#two {height: 33%; overflow: auto;}\n#three {height: 33%; overflow: auto;}\n</style>\n</head>\n\n<body>\n\n<p id=\"one\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget pede et eros adipiscing ornare. Sed ipsum dui, pulvinar eget, iaculis at, fermentum ac, lorem. Phasellus bibendum diam a nibh. In turpis lacus, condimentum id, faucibus ut, rhoncus id, enim. Quisque nec nunc at lacus placerat facilisis. Etiam mi lectus, placerat sit amet, ultricies at, tempus in, augue. Nunc in ante et erat ullamcorper pulvinar. Etiam turpis sapien, consequat vel, dignissim in, porttitor at, lectus. Integer dictum, massa eu scelerisque pretium, magna ligula auctor sapien, et tincidunt sem libero ac arcu. In at metus. Quisque quis diam at ipsum eleifend volutpat. Mauris tempor rutrum lectus. Proin fermentum nisi eu sem. Nulla eu eros. Donec velit metus, tristique tincidunt, egestas sed, tincidunt fermentum, nibh. In hac habitasse platea dictumst. Vivamus porta. Proin rhoncus ullamcorper leo. Nulla viverra, eros a dictum interdum, ante diam luctus metus, non placerat tellus metus ac lacus.</p>\n\n<p id=\"two\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget pede et eros adipiscing ornare. Sed ipsum dui, pulvinar eget, iaculis at, fermentum ac, lorem. Phasellus bibendum diam a nibh. In turpis lacus, condimentum id, faucibus ut, rhoncus id, enim. Quisque nec nunc at lacus placerat facilisis. Etiam mi lectus, placerat sit amet, ultricies at, tempus in, augue. Nunc in ante et erat ullamcorper pulvinar. Etiam turpis sapien, consequat vel, dignissim in, porttitor at, lectus. Integer dictum, massa eu scelerisque pretium, magna ligula auctor sapien, et tincidunt sem libero ac arcu. In at metus. Quisque quis diam at ipsum eleifend volutpat. Mauris tempor rutrum lectus. Proin fermentum nisi eu sem. Nulla eu eros. Donec velit metus, tristique tincidunt, egestas sed, tincidunt fermentum, nibh. In hac habitasse platea dictumst. Vivamus porta. Proin rhoncus ullamcorper leo. Nulla viverra, eros a dictum interdum, ante diam luctus metus, non placerat tellus metus ac lacus.</p>\n\n<p id=\"three\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget pede et eros adipiscing ornare. Sed ipsum dui, pulvinar eget, iaculis at, fermentum ac, lorem. Phasellus bibendum diam a nibh. In turpis lacus, condimentum id, faucibus ut, rhoncus id, enim. Quisque nec nunc at lacus placerat facilisis. Etiam mi lectus, placerat sit amet, ultricies at, tempus in, augue. Nunc in ante et erat ullamcorper pulvinar. Etiam turpis sapien, consequat vel, dignissim in, porttitor at, lectus. Integer dictum, massa eu scelerisque pretium, magna ligula auctor sapien, et tincidunt sem libero ac arcu. In at metus. Quisque quis diam at ipsum eleifend volutpat. Mauris tempor rutrum lectus. Proin fermentum nisi eu sem. Nulla eu eros. Donec velit metus, tristique tincidunt, egestas sed, tincidunt fermentum, nibh. In hac habitasse platea dictumst. Vivamus porta. Proin rhoncus ullamcorper leo. Nulla viverra, eros a dictum interdum, ante diam luctus metus, non placerat tellus metus ac lacus.</p>\n\n</body>\n\n</html>\n" }, { "answer_id": 353523, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 4, "selected": true, "text": " <div id=\"column\">\n <div id=\"a\" class=\"cell\">A</div>\n <div id=\"b\" class=\"cell\">B</div>\n <div id=\"c\" class=\"cell\">C</div>\n </div>\n #column\n {\n height: 100%;\n width: 20%;\n }\n\n #column .cell\n {\n height: 31%;\n margin: 1%;\n background-color: green;\n overflow: auto;\n }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/353481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]