qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
265,650
<p>I have a question regarding a symptom of my misuse of CreateProcess. I'm using the lpcommandline parameter to feed the path to my executable and parameters. My misuse is that I have not surrounded the path to the exe with quotes. </p> <p>My question is, why does the CreateProcess work just fine on most computers and not others? I know that the path will have a space in most of the time, yet on 90% of XP machines it works. I of course found out my issue on those 10% where it did not. But I'm wondering what is different on the machines where it does not work? Is there a setting or a policy that any of you folks know about. And yes, I am going to fix the quote issue. Just curious about why something like this would not have just failed off the bat. </p> <p>So the code would look something like below and the szCommandLine Parameter would be something like below. Notice no quotes around the path to the exe.</p> <p>"C:\Program Files\My Company\doit.exe parameter1 parameter2"</p> <pre><code>CreateProcess( NULL, szCommandLine, NULL, NULL, FALSE, NULL, NULL, NULL, &amp;si, &amp;pi ) </code></pre>
[ { "answer_id": 265847, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "char commandline[] = \"C:\\Program Files\\My Company\\doit.exe parameter1 parameter2\";\nCreateProcess(NULL,commandline, .... );\n" }, { "answer_id": 308119, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 3, "selected": false, "text": "\"c:\\program.exe\" files\\sub dir\\program name arg1 arg2\n\"c:\\program files\\sub.exe\" dir\\program name arg1 arg2\n\"c:\\program files\\sub dir\\program.exe\" name arg1 arg2\n\"c:\\program files\\sub dir\\program name.exe\" arg1 arg2\n" }, { "answer_id": 1922171, "author": "nopopem", "author_id": 233823, "author_profile": "https://Stackoverflow.com/users/233823", "pm_score": 2, "selected": false, "text": "char cmdline[] = \"C:\\Program Files\\App One\\bin\\app.exe param1 param2\";\nCreateProcess(NULL, cmdline, ...);\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24979/" ]
265,669
<p>I have some code that opens a word document using VBScript on an ASP.net page:</p> <pre><code>set objWord = CreateObject("Word.Application") objWord.Visible = True objWord.Documents.Open "c:\inetpub\wwwroot\JSWordTest\test.doc", False, False, False </code></pre> <p>This works great but opens the word doc in another window. Ideally I would like to make this look as if it is contained in the current page perhaps in an IFrame. I have some other buttons which paste text into the word document when clicked. </p> <p>I cannot just set the src of the iframe to the word document as need a reference to the word document (objWord) to allow me to paste text into it in real time again using Vbscript to do this.</p> <p>Not sure if this is possible but any ideas/alternatives welcome?</p> <p>Requirements: The word doc needs to be displayed from web browser</p> <p>At the side of the word document will be some buttons which when clicked paste text into it</p>
[ { "answer_id": 267116, "author": "unrealtrip", "author_id": 11130, "author_profile": "https://Stackoverflow.com/users/11130", "pm_score": 2, "selected": false, "text": "' Declare an object for the word application '\nSet objWord = CreateObject(\"Word.Application\")\n\nobjWord.Visible = False ' Don''t show word '\nobjWord.Documents.open(\"C:\\test.doc\") ' Open document '\nobjWord.Selection.WholeStory ' Select everything in the doc '\nstrText = objWord.Selection.Text ' Assign document contents to var'\nobjWord.Quit False ' Close Word, don't save ' \n" }, { "answer_id": 18613564, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Const wdFormatHTML = 8\n\ndim doc\nset doc = objWord.Documents.open(\"C:\\test.doc\")\ndoc.SaveAs \"doc.htm\", wdFormatHTML \n\n' etc ...\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23066/" ]
265,679
<p>I want to do something like this from within Eclipse: <a href="http://svn.collab.net/viewvc/svn?view=rev&amp;revision=33845" rel="nofollow noreferrer">http://svn.collab.net/viewvc/svn?view=rev&amp;revision=33845</a></p> <p>I use Subversive 0.7.5 with the Native JavaHL 1.5.3 (r33570) Connector.</p> <p>I tried to change something in a my working copy of a branch i'd like to tag and creating a Tag with Team -&gt; Tag... But I got the error message:</p> <blockquote> <p>Tag operation for some of selected resources failed.</p> <p>A path under version control is needed for this operation</p> </blockquote> <p>I tried only a tag name and one with full repository path. Both resulted in the same error. This is the error I get:</p> <pre><code>*** Tag svn copy &quot;C:/workspace/some_branch&quot; &quot;http://server:8080/svn/project/tags/TagWithChange&quot; -r WORKING -m &quot;TagWithChange&quot; --username &quot;masi&quot; A path under version control is needed for this operation </code></pre> <p>Is it possible from within Eclipse?</p> <p>How would you do something like this from the command line? See my own answer.</p> <p>Though if I use the following at the command line I get an error:</p> <pre><code>svn copy &quot;C:/workspace/some_branch&quot; &quot;http://server:8080/svn/project/tags/TagWithChange&quot; -r WORKING -m &quot;TagWithChange&quot; --username &quot;masi&quot; </code></pre> <p>Error:</p> <blockquote> <p>svn: Syntax error in revision argument 'WORKING'</p> </blockquote> <p>I'm using the svn client 1.5.4.</p>
[ { "answer_id": 265697, "author": "masi", "author_id": 12398, "author_profile": "https://Stackoverflow.com/users/12398", "pm_score": 2, "selected": false, "text": "svn copy some_branch http://server:8080/svn/tags/TagWithChange -m\"TagWithChange\"\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12398/" ]
265,680
<p>I'm using AspectJ to advice all the public methods which do have an argument of a chosen class. I tried the following:</p> <pre><code>pointcut permissionCheckMethods(Session sess) : (execution(public * *(.., Session)) &amp;&amp; args(*, sess)); </code></pre> <p>This is working wonderfully for methods with at least 2 arguments:</p> <pre><code>public void delete(Object item, Session currentSession); </code></pre> <p>but it does not work with methods like:</p> <pre><code>public List listAll(Session currentSession); </code></pre> <p>How may I change my pointcut to advice both methods executions? In other words: I expected the ".." wildcard to represent "zero or more arguments", but it looks like it means instead "one or more"...</p>
[ { "answer_id": 320404, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 4, "selected": true, "text": "pointcut permissionCheckMethods(EhealthSession eheSess) : \n (execution(public * *(.., EhealthSession)) && args(*, eheSess))\n && !within(it.___.security.PermissionsCheck);\n\npointcut permissionCheckMethods2(EhealthSession eheSess) : \n (execution(public * *(EhealthSession)) && args(eheSess))\n && !within(it.___.security.PermissionsCheck)\n && !within(it.___.app.impl.EhealthApplicationImpl);\n\nbefore(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods(eheSess)\n{\n Signature sig = thisJoinPointStaticPart.getSignature(); \n check(eheSess, sig);\n}\n\nbefore(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods2(eheSess)\n{\n Signature sig = thisJoinPointStaticPart.getSignature(); \n check(eheSess, sig);\n}\n" }, { "answer_id": 974466, "author": "Tahir Akhtar", "author_id": 18027, "author_profile": "https://Stackoverflow.com/users/18027", "pm_score": 2, "selected": false, "text": "pointcut permissionCheckMethods(Session sess) : \n(execution(public * *(..)) && args(.., sess));\n" }, { "answer_id": 11882677, "author": "kriegaex", "author_id": 1082681, "author_profile": "https://Stackoverflow.com/users/1082681", "pm_score": 2, "selected": false, "text": "args EhealthSession eheSess pointcut permissionCheckMethods() : execution(public * *(..));\n\nbefore() throws AuthorizationException : permissionCheckMethods() {\n for (Object arg : thisJoinPoint.getArgs()) {\n if (arg instanceof EhealthSession)\n check(arg, thisJoinPointStaticPart.getSignature());\n }\n}\n within(SomeBaseClass+) within(*Postfix) within(com.company.package..*)" }, { "answer_id": 43723129, "author": "Iomanip", "author_id": 1945856, "author_profile": "https://Stackoverflow.com/users/1945856", "pm_score": 2, "selected": false, "text": "pointcut permissionCheckMethods(Session sess) : \n (execution(public * *(.., Session , ..)) );\n && args(*, sess) sess" }, { "answer_id": 61189787, "author": "Chirag Thakkar", "author_id": 5690380, "author_profile": "https://Stackoverflow.com/users/5690380", "pm_score": 0, "selected": false, "text": "@Before(value = \"execution(public * *(.., org.springframework.data.domain.Pageable , ..))\")\nprivate void isMethodPageable () {\n log.info(\"in a Aspect point cut isPageableParameterAvailable()\");\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4690/" ]
265,708
<p>A fairly basic question, but I don't see it asked anywhere.</p> <p>Let's say we have a global struct (in C) like so:</p> <pre><code>struct foo { int written_frequently1; int read_only; int written_frequently2; }; </code></pre> <p>It seems clear to me that if we have lots of threads reading and writing, we need a semaphore (or other lock) on the <code>written_frequently</code> members, even for reading, since we can't be 100% sure that assignments to this struct will be atomic.</p> <p>If we want lots of threads to read the <code>read_only</code> member, and none to write, to we need a semaphore on the struct access just for reading?</p> <p>(I'm inclined to say no, because the fact that the locations immediately before and after are constantly changed shouldn't affect the <code>read_only</code> member, and multiple threads reading the value shouldn't interfere with each other. But I'm not sure.)</p> <hr> <p>[Edit: I realize now I should have asked this question much better, in order to clarify <em>very specifically</em> what I meant. Naturally, I didn't really grok all of the issues involved when I first asked the question. Of course, if I comprehensively edit the question now, I will ruin all of these great answers. What I meant is more like:</p> <pre><code>struct bar { char written_frequently1[LONGISH_LEN]; char read_only[LONGISH_LEN]; char written_frequently2[LONGISH_LEN]; }; </code></pre> <p>The major issue I asked about is, since this data is part of a struct, is it at all influenced by the other struct members, and might it influence them in return?</p> <p>The fact that the members were ints, and therefore writes are likely atomic, is really just a red herring in this case.]</p>
[ { "answer_id": 265748, "author": "Yogi", "author_id": 32801, "author_profile": "https://Stackoverflow.com/users/32801", "pm_score": 2, "selected": false, "text": "int read_only read_only" }, { "answer_id": 267617, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "if (++seconds > 59) { // Was the time hh:mm:59?\n seconds = 0; // Wrap seconds..\n if (++minutes > 59) { // ..and increment minutes. Was it hh:59:59?\n minutes = 0; // Wrap minutes..\n if (++hours > 23) // ..and increment hours. Was it 23:59:59?\n hours = 0; // Wrap hours.\n }\n}\n hours minutes seconds" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15456/" ]
265,720
<p>In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class: <a href="http://docs.python.org/library/httplib.html#httplib.HTTPConnection" rel="nofollow noreferrer">http://docs.python.org/library/httplib.html#httplib.HTTPConnection</a></p> <p>However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the <b>request</b>, not the connection. This doesn't seem to be supported by httplib.</p> <p>Is there any way to emulate this behavior?</p>
[ { "answer_id": 265741, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "import socket\n\ntimeout = 10\nsocket.setdefaulttimeout(timeout)\n" }, { "answer_id": 4453301, "author": "Pankrat", "author_id": 63392, "author_profile": "https://Stackoverflow.com/users/63392", "pm_score": 3, "selected": false, "text": "settimeout connection = HTTPConnection('slow.service.com')\nconnection.request(...)\nconnection.sock.settimeout(5.0)\nresponse = connection.getresponse()\nresponse.read()\nconnection.close()\n socket.error" }, { "answer_id": 51402077, "author": "Bob Baeck", "author_id": 4042961, "author_profile": "https://Stackoverflow.com/users/4042961", "pm_score": 0, "selected": false, "text": "connection = HTTPConnection(<IP of URL>, <port or None>, <timeout>)\n...\n connection = HTTPConnection('slow.service.com', None, 20.0)\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16148/" ]
265,722
<p>I'm trying to create an ASP page that has a bridged connection with an SQL Server 2005 database (separate sever from the ASP's server). For this I am trying to use a Windows Authentication setup. I have my name with full rights to the SQL server yet I am still getting the error 'Login failed for user COMPANY\name'. To see if this was just a Windows Authentication problem I tried to do a SQL Server Authentication; This also will not let me login. I have no idea why there would be a problem with the SQL Authentication, but I could really use some help figuring out why the Windows Authentication won't work. Thank you for your time.</p> <p>Regards,</p> <p>Franco</p>
[ { "answer_id": 266238, "author": "Dave Swersky", "author_id": 34796, "author_profile": "https://Stackoverflow.com/users/34796", "pm_score": 0, "selected": false, "text": "<identity impersonate=\"true\" />\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
265,725
<p>I have some constants that represent the valid options in one of my model's fields. What's the best way to handle these constants in Ruby?</p>
[ { "answer_id": 265767, "author": "Micah", "author_id": 19964, "author_profile": "https://Stackoverflow.com/users/19964", "pm_score": 4, "selected": false, "text": "class MyClass < ActiveRecord::Base\n ACTIVE_STATUS = \"active\"\n INACTIVE_STATUS = \"inactive\"\n PENDING_STATUS = \"pending\"\nend\n @model.status = MyClass::ACTIVE_STATUS\n@model.save\n" }, { "answer_id": 265783, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 6, "selected": true, "text": "OPTIONS = ['one', 'two', 'three']\nOPTIONS = {:one => 1, :two => 2, :three => 3}\n class Enumeration\n def Enumeration.add_item(key,value)\n @hash ||= {}\n @hash[key]=value\n end\n\n def Enumeration.const_missing(key)\n @hash[key]\n end \n\n def Enumeration.each\n @hash.each {|key,value| yield(key,value)}\n end\n\n def Enumeration.values\n @hash.values || []\n end\n\n def Enumeration.keys\n @hash.keys || []\n end\n\n def Enumeration.[](key)\n @hash[key]\n end\nend\n class Values < Enumeration\n self.add_item(:RED, '#f00')\n self.add_item(:GREEN, '#0f0')\n self.add_item(:BLUE, '#00f')\nend\n Values::RED => '#f00'\nValues::GREEN => '#0f0'\nValues::BLUE => '#00f'\n\nValues.keys => [:RED, :GREEN, :BLUE]\nValues.values => ['#f00', '#0f0', '#00f']\n" }, { "answer_id": 266003, "author": "Dema", "author_id": 407003, "author_profile": "https://Stackoverflow.com/users/407003", "pm_score": 3, "selected": false, "text": "\nclass MyModel\n\n SOME_ATTR_OPTIONS = {\n :first_option => 1,\n :second_option => 2, \n :third_option => 3\n }\nend\n \n\nif x == MyModel::SOME_ATTR_OPTIONS[:first_option]\n do this\nend\n\n" }, { "answer_id": 266747, "author": "Dave", "author_id": 34841, "author_profile": "https://Stackoverflow.com/users/34841", "pm_score": 3, "selected": false, "text": "class Model < ActiveRecord::Base\n ONE = 1\n TWO = 2\n\n validates_inclusion_of :value, :in => [ONE, TWO]\nend\n >> m=Model.new\n=> #<Model id: nil, value: nil, created_at: nil, updated_at: nil>\n>> m.valid?\n=> false\n>> m.value = 1\n=> 1\n>> m.valid?\n=> true\n" }, { "answer_id": 21023503, "author": "Simone Carletti", "author_id": 123527, "author_profile": "https://Stackoverflow.com/users/123527", "pm_score": 3, "selected": false, "text": "class Conversation < ActiveRecord::Base\n enum status: [ :active, :archived ]\nend\n\nconversation.archived!\nconversation.active? # => false\nconversation.status # => \"archived\"\n\nConversation.archived # => Relation for all archived Conversations\n" }, { "answer_id": 41910047, "author": "Ady Rosen", "author_id": 2200274, "author_profile": "https://Stackoverflow.com/users/2200274", "pm_score": 0, "selected": false, "text": "class Runner < ApplicationRecord\n module RUN_TYPES\n SYNC = 0\n ASYNC = 1\n end\nend\n > Runner::RUN_TYPES::SYNC\n => 0\n> Runner::RUN_TYPES::ASYNC\n => 1\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34746/" ]
265,750
<p>I have a xml build of</p> <pre><code>&lt;elig&gt; &lt;subscriber code="1234"/&gt; &lt;date to="12/30/2004" from="12/31/2004"/&gt; &lt;person name="bob" ID="654321"/&gt; &lt;dog type="labrador" color="white"/&gt; &lt;location name="hawaii" islandCode="01"/&gt; &lt;/subscriber&gt; &lt;/elig&gt; </code></pre> <p>In XSL I have:</p> <pre><code>&lt;xsl:template match="subscriber"&gt; &lt;xsl:for-each select="date"&gt; &lt;xsl:apply-templates match="person" /&gt; &lt;xsl:apply-templates match="location" /&gt; &lt;xsl:apply-templates match="dog" /&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; </code></pre> <p>The problem I have is that I need the location block in between the person and the dog block. I have tried ../ and it does not work. I simplified this majorly but the point comes across. I can't seem to remember what I need to place in front of location to get it to work. Thanks.</p>
[ { "answer_id": 265828, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 1, "selected": false, "text": "<elig>\n <subscriber code=\"1234\">\n <date to=\"12/30/2004\" from=\"12/31/2004\"/>\n <person name=\"bob\" ID=\"654321\"/>\n <dog type=\"labrador\" color=\"white\"/>\n <location name=\"hawaii\" islandCode=\"01\"/>\n </subscriber>\n</elig>\n <xsl:template match=\"subscriber\">\n <xsl:for-each select=\"date\">\n <xsl:apply-templates select=\"../person\" />\n <xsl:apply-templates select=\"../location\" />\n <xsl:apply-templates select=\"../dog\" />\n </xsl:for-each>\n</xsl:template>\n\n<xsl:template match=\"person\">person</xsl:template>\n<xsl:template match=\"location\">location</xsl:template>\n<xsl:template match=\"dog\">dog</xsl:template>\n personlocationdog\n" }, { "answer_id": 266090, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": true, "text": "<date/> <date/> <subscriber/> <subscriber/> <xsl:template match=\"subscriber\">\n <xsl:for-each select=\"date\"> \n <!-- from here on we're in the context of the date-tag -->\n <xsl:apply-templates match=\"../person\" />\n <xsl:apply-templates match=\"../location\" />\n <xsl:apply-templates match=\"../dog\" />\n </xsl:for-each>\n</xsl:template>\n" }, { "answer_id": 1254057, "author": "Alderath", "author_id": 151344, "author_profile": "https://Stackoverflow.com/users/151344", "pm_score": 0, "selected": false, "text": "<xsl:template match=\"subscriber\">\n <xsl:for-each select=\"date\">\n <!-- Perform the processing of the date tags here-->\n </xsl:for-each>\n\n <xsl:apply-templates match=\"person\" />\n <xsl:apply-templates match=\"location\" />\n <xsl:apply-templates match=\"dog\" />\n</xsl:template>\n" }, { "answer_id": 1442150, "author": "Laxmikanth Samudrala", "author_id": 144414, "author_profile": "https://Stackoverflow.com/users/144414", "pm_score": 1, "selected": false, "text": "<xsl:template match=\"subscriber\">\n <xsl:apply-templates match=\"date\" />\n</xsl:template>\n\n<xsl:template match=\"date\">\n <xsl:apply-templates match=\"../person\" />\n <xsl:apply-templates match=\"../location\" />\n <xsl:apply-templates match=\"../dog\" />\n</xsl:template>\n\n instead of xsl:for-each on date better practice is having a template match for date.\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16354/" ]
265,761
<p>In the iPhone 2.x firmware, can you make the iPhone vibrate for durations other than the system-defined:</p> <pre><code>AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); </code></pre> <p>In jailbroken phones, you used to be able to use the MeCCA.framework to do this:</p> <p><a href="http://pastie.org/94481" rel="nofollow noreferrer">http://pastie.org/94481</a></p> <pre><code>MeCCA_Vibrator *v = new MeCCA_Vibrator; v-&gt;activate(1); sleep(5); v-&gt;deactivate(); </code></pre> <p>But MeCCA.framework doesn't exist on my 2.x iPhone.</p>
[ { "answer_id": 281614, "author": "KevinButler", "author_id": 34463, "author_profile": "https://Stackoverflow.com/users/34463", "pm_score": 5, "selected": true, "text": "extern void * _CTServerConnectionCreate(CFAllocatorRef, int (*)(void *, CFStringRef, CFDictionaryRef, void *), int *);\nextern int _CTServerConnectionSetVibratorState(int *, void *, int, int, float, float, float);\n\nstatic void* connection = nil;\nstatic int x = 0;\n connection = _CTServerConnectionCreate(kCFAllocatorDefault, &vibratecallback, &x);\n _CTServerConnectionSetVibratorState(&x, connection, 3, intensity, 0, 0, 0);\n _CTServerConnectionSetVibratorState(&x, connection, 0, 0, 0, 0, 0);\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34463/" ]
265,762
<p>Always when I run java application it will display in Windows Task Manager is java.exe or javaw.exe. How to rename java.exe or javaw.exe process without wrapper by other programming languages.</p>
[ { "answer_id": 46060331, "author": "jbilander", "author_id": 7253471, "author_profile": "https://Stackoverflow.com/users/7253471", "pm_score": 1, "selected": false, "text": "javapackager -name MyTestApp -native image MyTestApp.exe" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24550/" ]
265,769
<p>I'm designing a database table which will hold filenames of uploaded files. What is the maximum length of a filename in NTFS as used by Windows XP or Vista?</p>
[ { "answer_id": 265782, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 9, "selected": true, "text": "MAX_PATH" }, { "answer_id": 265785, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 4, "selected": false, "text": "\"<NUL>\"" }, { "answer_id": 1771846, "author": "fane", "author_id": 215615, "author_profile": "https://Stackoverflow.com/users/215615", "pm_score": -1, "selected": false, "text": "\\\\" }, { "answer_id": 3557156, "author": "Dominik Weber", "author_id": 428708, "author_profile": "https://Stackoverflow.com/users/428708", "pm_score": 4, "selected": false, "text": "NameLength $Filename" }, { "answer_id": 18747460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "// max # of characters we support using the \"\\\\?\\\" syntax\n// (0x7FFF + 1 for NULL terminator)\n#define PATHCCH_MAX_CCH 0x8000\n" }, { "answer_id": 30509008, "author": "SzB", "author_id": 2866161, "author_profile": "https://Stackoverflow.com/users/2866161", "pm_score": -1, "selected": false, "text": "set \"fname=\"\nfor /l %%i in (1, 1, 27) do @call :setname\n@echo %fname%\nfor /l %%i in (1, 1, 100) do @call :check\ngoto :EOF\n:setname\nset \"fname=%fname%_123456789\"\ngoto :EOF\n:check\nset \"fname=%fname:~0,-1%\"\n@echo xx>%fname%\nif not exist %fname% goto :eof\ndir /b\npause\ngoto :EOF\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
265,774
<p>Consider the following code:</p> <pre><code>&lt;a href="#label2"&gt;GoTo Label2&lt;/a&gt; ... [content here] ... &lt;a name="label0"&gt;&lt;/a&gt;More content &lt;a name="label1"&gt;&lt;/a&gt;More content &lt;a name="label2"&gt;&lt;/a&gt;More content &lt;a name="label3"&gt;&lt;/a&gt;More content &lt;a name="label4"&gt;&lt;/a&gt;More content </code></pre> <p>Is there a way to emulate clicking on the "GoTo Label2" link to scroll to the appropriate region on the page through code?</p> <p><strong>EDIT</strong>: An acceptable alternative would be to scroll to an element with a unique-id, which already exists on my page. I would be adding the anchor tags if this is a viable solution.</p>
[ { "answer_id": 265789, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 2, "selected": false, "text": "window.location=\"<yourCurrentUri>#label2\";\n" }, { "answer_id": 265805, "author": "Ken Pespisa", "author_id": 30812, "author_profile": "https://Stackoverflow.com/users/30812", "pm_score": -1, "selected": false, "text": "http://www.example.com/mypage.htm#label2 location.href = location.href + '#label2';\n" }, { "answer_id": 265806, "author": "CubanX", "author_id": 27555, "author_profile": "https://Stackoverflow.com/users/27555", "pm_score": 4, "selected": false, "text": "window.location.href = '#label2';\n" }, { "answer_id": 265880, "author": "MikeeMike", "author_id": 6447, "author_profile": "https://Stackoverflow.com/users/6447", "pm_score": 7, "selected": true, "text": "document.getElementById('MyID').scrollIntoView(true);\n" }, { "answer_id": 265937, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "document.getElementsByName('label2')[0].focus();\n" }, { "answer_id": 4211333, "author": "sebarmeli", "author_id": 506570, "author_profile": "https://Stackoverflow.com/users/506570", "pm_score": 1, "selected": false, "text": "document.getElementById('MyID').scrollIntoView(true);\n window.location.href = window.location.protocol + \"//\" + window.location.host + \n window.location.pathname + window.location.search + \n \"#MyAnchor\";\n" }, { "answer_id": 24017343, "author": "Gareth Williams", "author_id": 1029827, "author_profile": "https://Stackoverflow.com/users/1029827", "pm_score": 2, "selected": false, "text": "ClientScript.RegisterStartupScript(this.GetType(), \"hash\", \"location.hash = '#form';\", true);\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
265,807
<p>I have a control that is basically functioning as a client-side timer countdown control.</p> <p>I want to fire a server-side event when the count down has reached a certain time.</p> <p>Does anyone have an idea how this could be done?</p> <p>So, when timer counts down to 0, a server-side event is fired.</p>
[ { "answer_id": 265840, "author": "wonderchook", "author_id": 32113, "author_profile": "https://Stackoverflow.com/users/32113", "pm_score": 1, "selected": false, "text": "function NotifyServer()\n{\n xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n xmlHttp.onreadystatechange = OnNotifyServerComplete;\n xmlHttp.open(\"GET\", \"serverpage.aspx\", true);\n xmlHttp.send();\n}\nfunction OnNotifyServerComplete()\n{\n if (xmlHttp.readyState == 4)\n {\n if (xmlHttp.status == 200)\n {\n if (xmlHttp.responseText != \"1\")\n //do something\n }\n }\n\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5853/" ]
265,809
<p>I'm scouring the internet for a definition of the term &quot;Internal Node.&quot; I cannot find a succinct definition. Every source I'm looking at uses the term without defining it, and the usage doesn't yield a proper definition of what an internal node actually is.</p> <p>Here are the two places I've been mainly looking: <a href="https://planetmath.org/ExternalNode" rel="nofollow noreferrer">Link</a> assumes that internal nodes are nodes that have two subtrees that aren't null, but doesn't say what nodes in the original tree are internal vs. external. <br /></p> <p><a href="http://www.math.bas.bg/%7Enkirov/2008/NETB201/slides/ch06/ch06-2.html" rel="nofollow noreferrer">http://www.math.bas.bg/~nkirov/2008/NETB201/slides/ch06/ch06-2.html</a> seems to insinuate that internal nodes only exist in proper binary trees and doesn't yield much useful information about them.</p> <p>What actually <em>is</em> an internal node!?</p>
[ { "answer_id": 265823, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": " I ROOT (root is also an INTERNAL NODE, unless it is leaf)\n / \\\n I I INTERNAL NODES\n / / \\\no o o EXTERNAL NODES (or leaves)\n" }, { "answer_id": 26893602, "author": "user3083948", "author_id": 3083948, "author_profile": "https://Stackoverflow.com/users/3083948", "pm_score": 3, "selected": false, "text": " \n I \n / \\\n * I\n /\\\n * *\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29119/" ]
265,814
<p>How can I create a regex for a string such as this:</p> <pre><code>&lt;SERVER&gt; &lt;SERVERKEY&gt; &lt;COMMAND&gt; &lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt; &lt;LOGTO&gt; &lt;OPTIONAL-MAXSIZE&gt; &lt;OPTIONAL-OFFSET&gt; </code></pre> <p>Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended.</p> <p>Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file.</p> <p>The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset.</p> <p>Heres some examples:</p> <pre><code>loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 </code></pre> <p>Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath.</p> <p>Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't.</p> <p>Heres my regex:</p> <pre><code>^(\s+)?(?P&lt;SRCHOST&gt;.+)(\s+)(?P&lt;SRCKEY&gt;.+)(\s+)(?P&lt;COMMAND&gt;COPY)(\s+)(?P&lt;SRCDIR&gt;.+)(\s+)(?P&lt;RETENTION&gt;\d+)(\s+)(?P&lt;TRANSFER_MODE&gt;BIN|ASC|BINARY|ASCII)(\s+)(?P&lt;DSTDIR&gt;.+)(\s+)(?P&lt;LOGFILE&gt;.+)(\s+)?(?P&lt;SIZE&gt;\d+)?(\s+)?(?P&lt;OFFSET&gt;\d+)?$ </code></pre>
[ { "answer_id": 265940, "author": "Stroboskop", "author_id": 23428, "author_profile": "https://Stackoverflow.com/users/23428", "pm_score": 0, "selected": false, "text": "<OUTPUTPATH> <LOGTO>\n c:\\ 12 bin \\ 250 bin \\output\n <FOLDERPATH> <RETENTION> <TRANSFERMODE> <OUTPUTPATH>\n <SERVER>, <SERVERKEY>, <COMMAND> no spaces -> [^]+\n<FOLDERPATH> allow anything -> .+\n<RETENTION> integer -> [0-9]+\n<TRANSFERMODE> allow only bin and ascii -> (bin|ascii)\n<OUTPUTPATH> allow anything -> .+\n<LOGTO> allow anything -> .+\n<OPTIONAL-MAXSIZE>[0-9]*\n<OPTIONAL-OFFSET>[0-9]*\n [^]+ [^]+ [^]+ .+ [0-9]+ (bin|ascii) .+ \\> .+( [0-9]* ( [0-9]*)?)?\n" }, { "answer_id": 266010, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": true, "text": "SERVER SERVERKEY COMMAND \\S+ FOLDERPATH /.*? RETENTION \\d+ TRANSFERMODE \\S+ OUTPUTPATH [A-Z]:\\\\.*?\\\\ LOGTO NO [A-Z]:\\\\.*? MAXSIZE OFFSET \\d+ ^\\s*\n(?P<SERVER>\\S+)\\s+\n(?P<SERVERKEY>\\S+)\\s+\n(?P<COMMAND>\\S+)\\s+\n(?P<FOLDERPATH>/.*?)\\s+ # Slash not that important, but should start with non-whitespace\n(?P<RETENTION>\\d+)\\s+\n(?P<TRANSFERMODE>\\S+)\\s+\n(?P<OUTPUTPATH>[A-Z]:\\\\.*?\\\\)\\s+ # Could also support network paths\n(?P<LOGTO>NO|[A-Z]:\\\\.*?)\n(?:\n \\s+(?P<MAXSIZE>\\d+)\n (?:\n \\s+(?P<OFFSET>\\d+)\n )?\n)?\n\\s*$\n ^\\s*(?P<SERVER>\\S+)\\s+(?P<SERVERKEY>\\S+)\\s+(?P<COMMAND>\\S+)\\s+(?P<FOLDERPATH>/.*?)\\s+(?P<RETENTION>\\d+)\\s+(?P<TRANSFERMODE>\\S+)\\s+(?P<OUTPUTPATH>[A-Z]:\\\\.*?\\\\)\\s+(?P<LOGTO>NO|[A-Z]:\\\\.*?)(?:\\s+(?P<MAXSIZE>\\d+)(?:\\s+(?P<OFFSET>\\d+))?)?\\s*$\n >>> import re\n>>> p = re.compile(r'^(?P<SERVER>\\S+)\\s+(?P<SERVERKEY>\\S+)\\s+(?P<COMMAND>\\S+)\\s+(?P<FOLDERPATH>/.*?)\\s+(?P<RETENTION>\\d+)\\s+(?P<TRANSFERMODE>\\S+)\\s+(?P<OUTPUTPATH>[A-Z]:\\\\.*?\\\\)\\s+(?P<LOGTO>NO|[A-Z]:\\\\.*?)(?:\\s+(?P<MAXSIZE>\\d+)(?:\\s+(?P<OFFSET>\\d+))?)?\\s*$',re.M)\n>>> data = r\"\"\"loveserver love copy /muffin* 20 bin C:\\Puppies\\ NO 256 300\n... loveserver love copy /muffin* 20 bin C:\\Puppies\\ NO 256\n... loveserver love copy /hats* 300 ascii C:\\Puppies\\no\\ C:\\log\\love.log 256\"\"\"\n>>> import pprint\n>>> for match in p.finditer(data):\n... print pprint.pprint(match.groupdict())\n...\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/muffin*',\n 'LOGTO': 'NO',\n 'MAXSIZE': '256',\n 'OFFSET': '300',\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\',\n 'RETENTION': '20',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'bin'}\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/muffin*',\n 'LOGTO': 'NO',\n 'MAXSIZE': '256',\n 'OFFSET': None,\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\',\n 'RETENTION': '20',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'bin'}\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/hats*',\n 'LOGTO': 'C:\\\\log\\\\love.log',\n 'MAXSIZE': '256',\n 'OFFSET': None,\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\no\\\\',\n 'RETENTION': '300',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'ascii'}\n>>>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34395/" ]
265,849
<p>That's it. It's a dumb dumb (embarrassing!) question, but I've never used C# before, only C++ and I can't seem to figure out how to access a Label on my main form from a secondary form and change the text. If anybody can let me know real quick what to do I'd be so grateful!</p> <p>BTW, I should really clarify. Sorry: I've got two separate .cs files that each look about like below. I was using the [Designer] in VS2008 to add in the label in Form1. When I type something like Form1.label1 it doesn't understand. The dropdown shows a list of methods and properties for Form1, but there's only about 7, like ControlCollection, Equals, MouseButtons, and a couple others... I can publicly define a variable in Form1 and that shows, but I don't know how to access the label...</p> <pre><code>namespace AnotherProgram { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } } </code></pre>
[ { "answer_id": 265885, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "this public class Form1 : Form \n{\n private Label label;\n\n // Construction etc as normal\n\n public string LabelText\n {\n get { return label.Text; }\n set { label.Text = value; }\n }\n\n public Form2 CreateForm2()\n {\n return new Form2(this);\n }\n}\n\npublic class Form2 : Form\n{\n private Form1 form1;\n\n public Form2(Form1 form1)\n {\n this.form1 = form1;\n // Normal construction\n }\n\n public void SayHello()\n {\n form1.LabelText = \"Hello\";\n }\n}\n" }, { "answer_id": 265887, "author": "Craig Norton", "author_id": 24804, "author_profile": "https://Stackoverflow.com/users/24804", "pm_score": 0, "selected": false, "text": "Public Class Form1\n Inherits Form\n\n\n Friend label1 As New Label\n\n\n Public Sub openForm2()\n Dim f As New Form2(Me)\n f.Show()\n End Sub\n\n\nEnd Class\n\n\nPublic Class Form2\n Inherits Form\n\n\n Private _ref As Form1\n\n\n Public Sub New()\n _ref = Nothing\n End Sub\n\n\n Public Sub New(ByVal formRef As Form1)\n _ref = formRef\n End Sub\n\n\n Public Sub accessLabel(ByVal setText As String)\n If (_ref IsNot Nothing) Then\n _ref.label1.Text = setText\n Else\n Throw New NullReferenceException(\"_ref is NULL\")\n End If\n End Sub\n\n\nEnd Class\n" }, { "answer_id": 268172, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 0, "selected": false, "text": "public delegate void AddItemDelegate(string item);\npublic AddItemDelegate AddItemCallback;\n private void btnScenario2_Click(object sender, EventArgs e)\n{\n\n FrmDialog dlg = new FrmDialog();\n //Subscribe this form for callback\n dlg.AddItemCallback = new AddItemDelegate(this.AddItemCallbackFn);\n dlg.ShowDialog();\n\n}\nprivate void AddItemCallbackFn(string item)\n{\n\n lstBx.Items.Add(item);\n\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
265,850
<p>Usually, I need to retrieve data from a table in some range; for example, a separate page for each search result. In MySQL I use LIMIT keyword but in DB2 I don't know. Now I use this query for retrieve range of data.</p> <pre><code>SELECT * FROM( SELECT SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO , DATA_KEY_VALUE , SHOW_PRIORITY FROM EMPLOYEE WHERE NAME LIKE 'DEL%' ORDER BY NAME DESC FETCH FIRST 20 ROWS ONLY ) AS TMP ORDER BY TMP.RUNNING_NO ASC FETCH FIRST 10 ROWS ONLY </code></pre> <p>but I know it's bad style. So, how to query for highest performance?</p>
[ { "answer_id": 273106, "author": "Paul Morgan", "author_id": 16322, "author_profile": "https://Stackoverflow.com/users/16322", "pm_score": 2, "selected": false, "text": "SELECT SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO,\n DATA_KEY_VALUE,\n SHOW_PRIORITY\n FROM EMPLOYEE\n WHERE NAME LIKE 'DEL%'\n ORDER BY NAME DESC\n FETCH FIRST 10 ROWS ONLY" }, { "answer_id": 3033351, "author": "Fuangwith S.", "author_id": 24550, "author_profile": "https://Stackoverflow.com/users/24550", "pm_score": 4, "selected": true, "text": "SELECT * FROM TABLE LIMIT 5 OFFSET 20\n" }, { "answer_id": 4592072, "author": "Pixie", "author_id": 526308, "author_profile": "https://Stackoverflow.com/users/526308", "pm_score": 2, "selected": false, "text": "SELECT * FROM ( \n SELECT \n ROW_NUMBER() OVER (ORDER BY ID_USER ASC) AS ROWNUM, \n ID_EMPLOYEE, FIRSTNAME, LASTNAME \n FROM EMPLOYEE \n WHERE FIRSTNAME LIKE 'DEL%' \n ) AS A WHERE A.rownum\nBETWEEN 1 AND 25\n" }, { "answer_id": 58862567, "author": "Kélisson Jean", "author_id": 5116302, "author_profile": "https://Stackoverflow.com/users/5116302", "pm_score": 0, "selected": false, "text": "LIMIT (pageSize) OFFSET ((currentPage) * (pageSize))\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24550/" ]
265,855
<p>I've got a database here that runs entirely on GMT. The client machines, however, may run on many different time zones (including BST). When you pull data back using SqlConnection, it will translate the datetime value so, for instance</p> <p>19 August 2008</p> <p>becomes</p> <p>18 August 2008 23:00:00.</p> <p>My question is, is there a way to specify to the connection that you do not wish this translation to take place?</p>
[ { "answer_id": 265971, "author": "Craig Norton", "author_id": 24804, "author_profile": "https://Stackoverflow.com/users/24804", "pm_score": 2, "selected": false, "text": "returnedDataTable.Columns(\"ColumnName\").DateTimeMode = DataSetDateTime.Unspecified\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
265,875
<p>I have always initialized my strings to NULL, with the thinking that NULL means the absence of a value and &quot;&quot; or String.Empty is a valid value. I have seen more examples lately of code where String.Empty is considered the default value or represents no value. This strikes me as odd, with the newly added nullable types in c# it seems like we are taking strides backwards with strings by not using the NULL to represent 'No Value'.</p> <p><strong>What do you use as the default initializer and why?</strong></p> <p><em>Edit: Based on the answers I futher my further thoughts</em></p> <ol> <li><p><strong>Avoiding error handling</strong> If the value shouldn't be null, why did it get set to <code>NULL</code> in the first place? Perhaps it would be better to identify the error at the place where it occurs rather than cover it up through out the rest of your codebase?</p> </li> <li><p><strong>Avoiding null checks</strong> If you are tired of doing null checks in code, wouldn't it be better to abstract the null checks? Perhaps wrap (or extend!) the string methods to make them <code>NULL</code> safe? What happens if you constantly use <code>String.Empty</code> and a null happens to work it's way into your system, do you start adding <code>NULL</code> checks anyways?</p> </li> </ol> <p>I can't help but return to the opinion that it is laziness. Any DBA would slap you nine ways to silly if you used '' instead of <code>null</code> in his\her database. I think the same principles apply in programming and there should be somebody to smack those upside the head who use <code>String.Empty</code> rather than <code>NULL</code> to represent no value.</p> <blockquote> <h3>Related Questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/263191/in-c-should-i-use-stringempty-or-stringempty-or">In C#, should I use string.Empty or String.Empty or “” ?</a></li> <li><a href="https://stackoverflow.com/questions/151472/what-is-the-difference-between-stringempty-and">What is the difference between String.Empty and “”</a></li> <li><a href="https://stackoverflow.com/questions/167952/null-or-empty-string-to-represent-no-data-in-table-column">Null or empty string to represent no data in table column?</a></li> </ul> </blockquote>
[ { "answer_id": 265900, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": false, "text": "Empty null NullReferenceException IsNullOrEmpty()" }, { "answer_id": 266272, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": false, "text": "if (s == \"value\")\n s String.Compare Enum String.Empty string msg = Validate(item);\nif (msg != null)\n{\n DisplayErrorMessage(msg);\n return;\n}\n Validate String.Empty String.Empty null" }, { "answer_id": 267562, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 2, "selected": false, "text": "NULL string.IsNullOrEmpty(someString)" }, { "answer_id": 1177166, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "string name = null; // or String.Empty\nif (condition)\n{\n name = \"foo\";\n}\nelse\n{\n name = \"bar\";\n}\n\nreturn name;\n string name = null; // or String.Empty\nif (condition)\n{\n name = \"foo\";\n}\nelse if (othercondition)\n{\n name = \"bar\";\n}\n\nreturn name; //returns null when condition and othercondition are false\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24279/" ]
265,879
<p>I am interested in using/learning RoR in a project where I have to use a .NET dll. Is Ruby capable of importing a .NET dll?</p>
[ { "answer_id": 266032, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 2, "selected": false, "text": "\"Your Ruby Code\" -> RubyCOM -> \"COM-Callable Wrappers\" -> \"Your .NET objects\"\n" }, { "answer_id": 266403, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": true, "text": "win32ole ComVisibleAttribute using System;\nusing System.IO;\n\nnamespace ComLib\n{\n public class LogWriter\n {\n public void WriteLine( string line )\n {\n using( var log = new StreamWriter( File.OpenWrite( @\"c:\\log.file\" ) ) )\n {\n log.WriteLine( line );\n }\n }\n }\n}\n Properties AssemblyInfo.cs [assembly: ComVisible( false )]\n AssemblyInfo.cs [ComVisible( true )]\npublic class LogWriter ....\n Build require 'win32ole'\n\nlib = WIN32OLE.new('[Solution name].ComLib.LogWriter')\nlib.WriteLine('calling .net from ruby via COM, hooray!')\n c:\\log.file" }, { "answer_id": 7852643, "author": "Rich", "author_id": 8261, "author_profile": "https://Stackoverflow.com/users/8261", "pm_score": 2, "selected": false, "text": "extern \"C\" __declspec ( dllexport ) void CallManagedMethod() {\n Something^ myManagedObject ...\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34766/" ]
265,896
<p>I've got a junk directory where I toss downloads, one-off projects, email drafts, and other various things that might be useful for a few days but don't need to be saved forever. To stop this directory from taking over my machine, I wrote a program that will delete all files older than a specified number of days and logs some statistics about the number of files deleted and their size just for fun.</p> <p>I noticed that a few project folders were living way longer than they should, so I started to investigate. In particular, it seemed that folders for projects in which I had used SVN were sticking around. It turns out that the read-only files in the .svn directories are not being deleted. I just did a simple test on a read-only file and discovered that <code>System.IO.File.Delete</code> and <code>System.IO.FileInfo.Delete</code> will not delete a read-only file.</p> <p>I don't care about protecting files in this particular directory; if something important is in there it's in the wrong place. Is there a .NET class that can delete read-only files, or am I going to have to check for read-only attributes and strip them?</p>
[ { "answer_id": 265916, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 1, "selected": false, "text": ">del /F *\n" }, { "answer_id": 265938, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 8, "selected": true, "text": "using System.IO;\n\nFile.SetAttributes(filePath, FileAttributes.Normal);\nFile.Delete(filePath);\n" }, { "answer_id": 8310592, "author": "Neil", "author_id": 148593, "author_profile": "https://Stackoverflow.com/users/148593", "pm_score": 5, "selected": false, "text": "FileInfo file.IsReadOnly = false;\nfile.Delete();\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ]
265,898
<p>I'm coding a small CMS to get a better understanding of how they work and to learn some new things about PHP. I have however come across a problem.</p> <p>I want to use mod_rewrite (though if someone has a better solution I'm up for trying it) to produce nice clean URLs, so site.com/index.php?page=2 can instead be site.com/tools</p> <p>By my understanding I need to alter my .htaccess file each time I add a new page and this is where I strike a problem, my PHP keeps telling me that I can't update it because it hasn't the permissions. A quick bit of chmod reveals that even with 777 permissions it can't do it, am I missing something?</p> <p>My source for mod_rewrite instructions is currently <a href="http://wettone.com/code/clean-urls" rel="noreferrer">this page here</a> incase it is important/useful.</p>
[ { "answer_id": 265934, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 4, "selected": true, "text": "RewriteEngine on\nRewriteBase /\n\n# only rewrite if the requested file doesn't exist\nRewriteCond %{REQUEST_FILENAME} !-s \n\n# pass the rest of the request into index.php to handle \nRewriteRule ^(.*)$ /index.php/$1 [L]\n" }, { "answer_id": 265948, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": ".htaccess .htaccess" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
265,919
<p>I'm working on a program that processes many requests, none of them reaching more than 50% of CPU (<strong>currently I'm working on a dual core</strong>). So I created a thread for each request, the whole process is faster. Processing 9 requests, a single thread lasts 02min08s, while with 3 threads working simultaneously the time decreased to 01min37s, but it keeps not using 100% CPU, only around 50%.</p> <p>How could I allow my program to use full processors capability?</p> <p><strong>EDIT</strong> The application isn't IO or Memory bounded, they're at reasonable levels all the time.</p> <p>I think it has something to do with the 'dual core' thing.</p> <p>There is a locked method invocation that every request uses, but it is really fast, I don't think this is the problem.</p> <p>The more cpu-costly part of my code is the call of a dll via COM (the same external method is called from all threads). This dll is also no Memory or IO-bounded, it is an AI recognition component, I'm doing an OCR recognition of paychecks, a paycheck for request.</p> <p><strong>EDIT2</strong></p> <p>It is very probable that the STA COM Method is my problem, I contacted the component owners in order to solve this problem.</p>
[ { "answer_id": 265935, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 2, "selected": false, "text": "class Test\n{\n static void Main() //This will be an MTA thread by default\n {\n var o = new COMObjectClass();\n // Did a new thread pop into existence when that line was executed?\n // If so, .NET created an STA thread for it to live in.\n }\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21668/" ]
265,930
<p>I'm generating and showing a new WinForms window on top of a Main Window. How can I achieve that the original (Main Window) keeps the focus? Setting the focus back after showing the new window does not solve my problem because I need to prevent the Main Window's title bar from flickering. The new window has to stay on top of the Main Window so I have to set topMost=true. However, this makes no difference for the problem I think.</p> <p>Thank you!</p>
[ { "answer_id": 265987, "author": "Spidey", "author_id": 4236, "author_profile": "https://Stackoverflow.com/users/4236", "pm_score": 2, "selected": false, "text": "private void button1_Click(object sender, EventArgs e)\n{\n Form2 f2 = new Form2();\n f2.TopMost = true;\n f2.Show();\n this.Focus(); \n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
265,944
<p>How do you reverse the effect of a merge on polarised branches without dying of agony?</p> <p>This problem has been plaguing me for <strong>months</strong> and I have finally given up. </p> <p>You have 1 Repository, with 2 <strong>Named</strong> Branches. A and B. </p> <p>Changes that occur to A will inevitably occur on B. </p> <p>Changes that occur directly on B MUST NEVER occur on A. </p> <p>In such a configuration, merging "B" into "A" produces a dire problem in the repository, as all the changes to B appear in A as if they were made in A. </p> <p>The only "normal" way to recover from this situation appears to be "backing out" the merge, ie: </p> <pre><code> hg up -r A hg backout -r BadMergeRev --parent BadMergerevBeforeOnA </code></pre> <p>Which looks all fine and dandy, until you decide to merge later in the correct direction, and you end up with all sorts of nasty things happening and code that was erased / commented out on specifically branch B suddenly becomes unerased or uncommented. </p> <p>There has not been a working viable solution to this so far other than "let it do its thing, and then hand fix all the problems" and that to be honest is a bit fubar. </p> <p>Here is an image clarifying the problem: </p> <p><em>[Original image lost]</em></p> <p>Files C &amp; E ( or changes C &amp; E ) must appear only on branch b, and not on branch a. Revision A9 here ( branch a, revno 9 ) is the start of the problem. </p> <p>Revisions A10 and A11 are the "Backout merge" and "merge the backout" phases. </p> <p>And revision B12 is mercurial, erroneously repeatedly dropping a change that was intended not to be dropped. </p> <p>This Dilemma has caused much frustration and blue smoke and I would like to put an end to it. </p> <h3>Note</h3> <p>It may be the obvious answer to try prohibiting the reverse merge from occurring, either with hooks or with policies, I have found the ability to muck this up is rather high and the chance of it happening so likely that even with countermeasures, you <em>must</em> still assume that inevitably, it <em>will</em> happen so that you can solve it when it does.</p> <h3>To Elaborate</h3> <p>In the model I have used Seperate files. These make the problem sound simple. These merely represent <em>arbitrary changes</em> which could be a separate line. </p> <p>Also, to add insult to injury, there have been substantial changes on branch A which leaves the standing problem "do the changes in branch A conflict with the changes in branch B which just turned up ( and got backed out ) which looks like a change on branch A instead " </p> <h3>On History Rewriting Tricks:</h3> <p>The problem with all these retro-active solutions is as follows:</p> <ol> <li>We have 9000 commits. </li> <li>Cloning freshly thus takes half an hour</li> <li>If there exists <em>even one</em> bad clone of the repository <em>somewhere</em>, there is a liklihood of it comming back in contact with the original repository, and banging it up all over again. </li> <li>Everyone has cloned this repository already, and now several days have passed with on-going commits.</li> <li>One such clone, happens to be a live site, so "wiping that one and starting from scratch" = "big nono" </li> </ol> <p>( I admit, many of the above are a bit daft, but they are outside of my control ). </p> <p>The only solutions that are viable are the ones that assume that people <em>can</em> and <em>will</em> do everything wrong, and that there is a way to 'undo' this wrongness. </p>
[ { "answer_id": 2093167, "author": "oenli", "author_id": 251438, "author_profile": "https://Stackoverflow.com/users/251438", "pm_score": 6, "selected": false, "text": "hg update 11 $EDITOR some/file.txt hg commit -m \"generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9\" hg merge 12 hg revert -a --no-backup -r 14 hg commit -m \"throwing away wrong merge from BRANCH_V9\" hg merge hg commit -m \"merged two heads used to revert from bad merge\" hg update BRANCH_V9 hg merge 14 hg commit -m \"Merging in last good state of BRANCH_V8\" hg merge 15 hg revert -a --no-backup -r 17 hg commit -m \"Merging in bad merge from BRANCH_V8 and its fix and throwing it all away\" hg merge BRANCH_V8 hg commit -m \"merging changes from BRANCH_V8\"" }, { "answer_id": 10203239, "author": "Kevin", "author_id": 1340389, "author_profile": "https://Stackoverflow.com/users/1340389", "pm_score": 2, "selected": false, "text": "hg graft r1 r2 r3\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15614/" ]
265,953
<p>Basically, I would like to check if I have rights to open the file before I actually try to open it; I do not want to use a try/catch for this check unless I have to. Is there a file access property I can check before hand?</p>
[ { "answer_id": 265958, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 7, "selected": false, "text": ".Exists()" }, { "answer_id": 266316, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": false, "text": "Exception List<FileStream>" }, { "answer_id": 806994, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 5, "selected": false, "text": "/// <summary>\n/// Tries to open a file, with a user defined number of attempt and Sleep delay between attempts.\n/// </summary>\n/// <param name=\"filePath\">The full file path to be opened</param>\n/// <param name=\"fileMode\">Required file mode enum value(see MSDN documentation)</param>\n/// <param name=\"fileAccess\">Required file access enum value(see MSDN documentation)</param>\n/// <param name=\"fileShare\">Required file share enum value(see MSDN documentation)</param>\n/// <param name=\"maximumAttempts\">The total number of attempts to make (multiply by attemptWaitMS for the maximum time the function with Try opening the file)</param>\n/// <param name=\"attemptWaitMS\">The delay in Milliseconds between each attempt.</param>\n/// <returns>A valid FileStream object for the opened file, or null if the File could not be opened after the required attempts</returns>\npublic FileStream TryOpen(string filePath, FileMode fileMode, FileAccess fileAccess,FileShare fileShare,int maximumAttempts,int attemptWaitMS)\n{\n FileStream fs = null;\n int attempts = 0;\n\n // Loop allow multiple attempts\n while (true)\n {\n try\n {\n fs = File.Open(filePath, fileMode, fileAccess, fileShare);\n\n //If we get here, the File.Open succeeded, so break out of the loop and return the FileStream\n break;\n }\n catch (IOException ioEx)\n {\n // IOExcception is thrown if the file is in use by another process.\n\n // Check the numbere of attempts to ensure no infinite loop\n attempts++;\n if (attempts > maximumAttempts)\n {\n // Too many attempts,cannot Open File, break and return null \n fs = null;\n break;\n }\n else\n {\n // Sleep before making another attempt\n Thread.Sleep(attemptWaitMS);\n\n }\n\n }\n\n }\n // Reutn the filestream, may be valid or null\n return fs;\n}\n" }, { "answer_id": 2469199, "author": "Rudzitis", "author_id": 296423, "author_profile": "https://Stackoverflow.com/users/296423", "pm_score": -1, "selected": false, "text": "public static FileStream GetFileStream(String filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, ref int attempts, int attemptWaitInMilliseconds)\n{ \n try\n {\n return File.Open(filePath, fileMode, fileAccess, fileShare);\n }\n catch (UnauthorizedAccessException unauthorizedAccessException)\n {\n if (attempts <= 0)\n {\n throw unauthorizedAccessException;\n }\n else\n {\n Thread.Sleep(attemptWaitInMilliseconds);\n attempts--;\n return GetFileStream(filePath, fileMode, fileAccess, fileShare, ref attempts, attemptWaitInMilliseconds);\n }\n }\n}\n" }, { "answer_id": 42547543, "author": "dj shahar", "author_id": 7645413, "author_profile": "https://Stackoverflow.com/users/7645413", "pm_score": 2, "selected": false, "text": "var fileIOPermission = new FileIOPermission(FileIOPermissionAccess.Read,\n System.Security.AccessControl.AccessControlActions.View,\n MyPath);\n\nif (fileIOPermission.AllFiles == FileIOPermissionAccess.Read)\n{\n // Do your thing here...\n}\n" }, { "answer_id": 56004764, "author": "Omid Matouri", "author_id": 3808936, "author_profile": "https://Stackoverflow.com/users/3808936", "pm_score": -1, "selected": false, "text": "public static bool IsFileLocked(string filename)\n{\n try\n {\n using var fs = File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n }\n catch (IOException)\n {\n return true;\n }\n return false;\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12333/" ]
265,956
<p>I am pretty new to php, but I am learning! I have a simple form on a client website. I am testing the form and when I click submit, I get the following error:</p> <p>Form Mail Script</p> <pre><code>Wrong referrer (referring site). For security reasons the form can only be used, if the referring page is part of this website. Note for the Admin: Please add the name of your server to the referrer variable in the index.php configuration file: mywebsite.com </code></pre> <p>Powered by Form Mail Script</p> <p>I am looking through the forms configuration and support files but I do not understand exactly what it is I need to change.</p> <p>Can someone please explain to me what the Admin note above means and how to fix it?</p>
[ { "answer_id": 266105, "author": "pd.", "author_id": 19066, "author_profile": "https://Stackoverflow.com/users/19066", "pm_score": 2, "selected": false, "text": "$referring_server = 'http://www.mywebsite.com, scripts';\n $referring_server = 'yourdomain.com';\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30043/" ]
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
[ { "answer_id": 265995, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "import re, string\ns = \"string. With. Punctuation?\" # Sample string \nout = re.sub('[%s]' % re.escape(string.punctuation), '', s)\n" }, { "answer_id": 266000, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": ">>> s = \"string. With. Punctuation?\" # Sample string\n>>> import string\n>>> for c in string.punctuation:\n... s= s.replace(c,\"\")\n...\n>>> s\n'string With Punctuation'\n" }, { "answer_id": 266162, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 11, "selected": true, "text": "s.translate(None, string.punctuation)\n s.translate(str.maketrans('', '', string.punctuation))\n exclude = set(string.punctuation)\ns = ''.join(ch for ch in s if ch not in exclude)\n import re, string, timeit\n\ns = \"string. With. Punctuation\"\nexclude = set(string.punctuation)\ntable = string.maketrans(\"\",\"\")\nregex = re.compile('[%s]' % re.escape(string.punctuation))\n\ndef test_set(s):\n return ''.join(ch for ch in s if ch not in exclude)\n\ndef test_re(s): # From Vinko's solution, with fix.\n return regex.sub('', s)\n\ndef test_trans(s):\n return s.translate(table, string.punctuation)\n\ndef test_repl(s): # From S.Lott's solution\n for c in string.punctuation:\n s=s.replace(c,\"\")\n return s\n\nprint \"sets :\",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)\nprint \"regex :\",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)\nprint \"translate :\",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)\nprint \"replace :\",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)\n sets : 19.8566138744\nregex : 6.86155414581\ntranslate : 2.12455511093\nreplace : 28.4436721802\n" }, { "answer_id": 2402306, "author": "pyrou", "author_id": 288908, "author_profile": "https://Stackoverflow.com/users/288908", "pm_score": 6, "selected": false, "text": "myString.translate(None, string.punctuation)\n" }, { "answer_id": 6577965, "author": "David Vuong", "author_id": 781292, "author_profile": "https://Stackoverflow.com/users/781292", "pm_score": 3, "selected": false, "text": "import string\nf = lambda x: ''.join([i for i in x if i not in string.punctuation])\n" }, { "answer_id": 7268456, "author": "Björn Lindqvist", "author_id": 189247, "author_profile": "https://Stackoverflow.com/users/189247", "pm_score": 5, "selected": false, "text": "string.punctuation # -*- coding: utf-8 -*-\nfrom unicodedata import category\ns = u'String — with - «punctation »...'\ns = ''.join(ch for ch in s if category(ch)[0] != 'P')\nprint 'stripped', s\n ''.join(ch for ch in s if category(ch)[0] not in 'SP')\n ~*+§$" }, { "answer_id": 15853920, "author": "Disk Giant", "author_id": 2252764, "author_profile": "https://Stackoverflow.com/users/2252764", "pm_score": -1, "selected": false, "text": "def scrub(abc):\n while abc[-1] is in list(string.punctuation):\n abc=abc[:-1]\n while abc[0] is in list(string.punctuation):\n abc=abc[1:]\n return abc\n" }, { "answer_id": 16799238, "author": "Eratosthenes", "author_id": 1499713, "author_profile": "https://Stackoverflow.com/users/1499713", "pm_score": 8, "selected": false, "text": "import re\ns = \"string. With. Punctuation?\"\ns = re.sub(r'[^\\w\\s]','',s)\n" }, { "answer_id": 18570395, "author": "Martijn Pieters", "author_id": 100297, "author_profile": "https://Stackoverflow.com/users/100297", "pm_score": 4, "selected": false, "text": "str unicode str.translate() None import string\n\nremove_punct_map = dict.fromkeys(map(ord, string.punctuation))\ns.translate(remove_punct_map)\n dict.fromkeys() None import unicodedata\nimport sys\n\nremove_punct_map = dict.fromkeys(i for i in range(sys.maxunicode)\n if unicodedata.category(chr(i)).startswith('P'))\n" }, { "answer_id": 32719664, "author": "Dr.Tautology", "author_id": 5363840, "author_profile": "https://Stackoverflow.com/users/5363840", "pm_score": 3, "selected": false, "text": "def stripPunc(wordList):\n \"\"\"Strips punctuation from list of words\"\"\"\n puncList = [\".\",\";\",\":\",\"!\",\"?\",\"/\",\"\\\\\",\",\",\"#\",\"@\",\"$\",\"&\",\")\",\"(\",\"\\\"\"]\n for punc in puncList:\n for word in wordList:\n wordList=[word.replace(punc,'') for word in wordList]\n return wordList\n" }, { "answer_id": 33192523, "author": "Dom Grey", "author_id": 4304362, "author_profile": "https://Stackoverflow.com/users/4304362", "pm_score": 3, "selected": false, "text": "''.join([c for c in s if c.isalnum() or c.isspace()])\n" }, { "answer_id": 36122360, "author": "Tim P", "author_id": 5480398, "author_profile": "https://Stackoverflow.com/users/5480398", "pm_score": 3, "selected": false, "text": "import string\n\"l*ots! o(f. p@u)n[c}t]u[a'ti\\\"on#$^?/\".translate(str.maketrans({a:None for a in string.punctuation}))\n" }, { "answer_id": 37221663, "author": "SparkAndShine", "author_id": 3067748, "author_profile": "https://Stackoverflow.com/users/3067748", "pm_score": 6, "selected": false, "text": "import string\n\ns = \"string. With. Punctuation?\"\ntable = string.maketrans(\"\",\"\")\nnew_s = s.translate(table, string.punctuation) # Output: string without punctuation\n import string\n\ns = \"string. With. Punctuation?\"\ntable = str.maketrans(dict.fromkeys(string.punctuation)) # OR {key: None for key in string.punctuation}\nnew_s = s.translate(table) # Output: string without punctuation\n" }, { "answer_id": 37894054, "author": "Blairg23", "author_id": 1224827, "author_profile": "https://Stackoverflow.com/users/1224827", "pm_score": 4, "selected": false, "text": "\\w \\d \\s import re\ns = \"string. With. Punctuation?\" # Sample string \nout = re.sub(ur'[^\\w\\d\\s]+', '', s)\n" }, { "answer_id": 39115253, "author": "Pablo Rodriguez Bertorello", "author_id": 5141805, "author_profile": "https://Stackoverflow.com/users/5141805", "pm_score": 3, "selected": false, "text": ">>> s = \"string. With. Punctuation?\"\n>>> s = re.sub(r'[^\\w\\s]','',s)\n>>> re.split(r'\\s*', s)\n\n\n['string', 'With', 'Punctuation']\n" }, { "answer_id": 39901522, "author": "Zach", "author_id": 345660, "author_profile": "https://Stackoverflow.com/users/345660", "pm_score": 4, "selected": false, "text": "string.punctuation import regex\ns = u\"string. With. Some・Really Weird、Non?ASCII。 「(Punctuation)」?\"\nremove = regex.compile(ur'[\\p{C}|\\p{M}|\\p{P}|\\p{S}|\\p{Z}]+', regex.UNICODE)\nremove.sub(u\" \", s).strip()\n \\{S} $ \\{Pd}" }, { "answer_id": 40885971, "author": "ngub05", "author_id": 1952350, "author_profile": "https://Stackoverflow.com/users/1952350", "pm_score": 3, "selected": false, "text": "import string\n\ninput_text = \"!where??and!!or$$then:)\"\npunctuation_replacer = string.maketrans(string.punctuation, ' '*len(string.punctuation)) \nprint ' '.join(input_text.translate(punctuation_replacer).split()).strip()\n\nOutput>> where and or then\n" }, { "answer_id": 41423791, "author": "Animeartist", "author_id": 4404805, "author_profile": "https://Stackoverflow.com/users/4404805", "pm_score": 2, "selected": false, "text": "# FIRST METHOD\n# Storing all punctuations in a variable \npunctuation='!?,.:;\"\\')(_-'\nnewstring ='' # Creating empty string\nword = raw_input(\"Enter string: \")\nfor i in word:\n if(i not in punctuation):\n newstring += i\nprint (\"The string without punctuation is\", newstring)\n\n# SECOND METHOD\nword = raw_input(\"Enter string: \")\npunctuation = '!?,.:;\"\\')(_-'\nnewstring = word.translate(None, punctuation)\nprint (\"The string without punctuation is\",newstring)\n\n\n# Output for both methods\nEnter string: hello! welcome -to_python(programming.language)??,\nThe string without punctuation is: hello welcome topythonprogramminglanguage\n" }, { "answer_id": 41462367, "author": "Isayas Wakgari Kelbessa", "author_id": 7373754, "author_profile": "https://Stackoverflow.com/users/7373754", "pm_score": 2, "selected": false, "text": "with open('one.txt','r')as myFile:\n\n str1=myFile.read()\n\n print(str1)\n\n\n punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '\"', \"'\"] \n\nfor i in punctuation:\n\n str1 = str1.replace(i,\" \") \n myList=[]\n myList.extend(str1.split(\" \"))\nprint (str1) \nfor i in myList:\n\n print(i,end='\\n')\n print (\"____________\")\n" }, { "answer_id": 41479924, "author": "Isayas Wakgari Kelbessa", "author_id": 7373754, "author_profile": "https://Stackoverflow.com/users/7373754", "pm_score": -1, "selected": false, "text": "print('====THIS IS HOW TO REMOVE STOP WORS====')\n\nwith open('one.txt','r')as myFile:\n\n str1=myFile.read()\n\n stop_words =\"not\", \"is\", \"it\", \"By\",\"between\",\"This\",\"By\",\"A\",\"when\",\"And\",\"up\",\"Then\",\"was\",\"by\",\"It\",\"If\",\"can\",\"an\",\"he\",\"This\",\"or\",\"And\",\"a\",\"i\",\"it\",\"am\",\"at\",\"on\",\"in\",\"of\",\"to\",\"is\",\"so\",\"too\",\"my\",\"the\",\"and\",\"but\",\"are\",\"very\",\"here\",\"even\",\"from\",\"them\",\"then\",\"than\",\"this\",\"that\",\"though\",\"be\",\"But\",\"these\"\n\n myList=[]\n\n myList.extend(str1.split(\" \"))\n\n for i in myList:\n\n if i not in stop_words:\n\n print (\"____________\")\n\n print(i,end='\\n')\n" }, { "answer_id": 42012909, "author": "Haythem HADHAB", "author_id": 7508353, "author_profile": "https://Stackoverflow.com/users/7508353", "pm_score": 3, "selected": false, "text": "import re\ns = \"string. With. Punctuation?\" # Sample string \nout = re.sub(r'[^a-zA-Z0-9\\s]', '', s)\n" }, { "answer_id": 50215739, "author": "krinker", "author_id": 920085, "author_profile": "https://Stackoverflow.com/users/920085", "pm_score": 3, "selected": false, "text": "re.compile table = str.maketrans({key: None for key in string.punctuation})\n table = str.maketrans('', '', string.punctuation)\n import re, string, timeit\n\ns = \"string. With. Punctuation\"\n\n\ndef test_set(s):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in s if ch not in exclude)\n\n\ndef test_set2(s):\n _punctuation = set(string.punctuation)\n for punct in set(s).intersection(_punctuation):\n s = s.replace(punct, ' ')\n return ' '.join(s.split())\n\n\ndef test_re(s): # From Vinko's solution, with fix.\n regex = re.compile('[%s]' % re.escape(string.punctuation))\n return regex.sub('', s)\n\n\ndef test_trans(s):\n table = str.maketrans({key: None for key in string.punctuation})\n return s.translate(table)\n\n\ndef test_trans2(s):\n table = str.maketrans('', '', string.punctuation)\n return(s.translate(table))\n\n\ndef test_repl(s): # From S.Lott's solution\n for c in string.punctuation:\n s=s.replace(c,\"\")\n return s\n\n\nprint(\"sets :\",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000))\nprint(\"sets2 :\",timeit.Timer('f(s)', 'from __main__ import s,test_set2 as f').timeit(1000000))\nprint(\"regex :\",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000))\nprint(\"translate :\",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000))\nprint(\"translate2 :\",timeit.Timer('f(s)', 'from __main__ import s,test_trans2 as f').timeit(1000000))\nprint(\"replace :\",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000))\n sets : 3.1830138750374317\nsets2 : 2.189873124472797\nregex : 7.142953420989215\ntranslate : 4.243278483860195\ntranslate2 : 2.427158243022859\nreplace : 4.579746678471565\n" }, { "answer_id": 57249726, "author": "Dehua Li", "author_id": 10333117, "author_profile": "https://Stackoverflow.com/users/10333117", "pm_score": 3, "selected": false, "text": " ''.join(filter(str.isalnum, s)) \n" }, { "answer_id": 62187210, "author": "Rajan saha Raju", "author_id": 8589823, "author_profile": "https://Stackoverflow.com/users/8589823", "pm_score": 0, "selected": false, "text": "from unicodedata import category\ntext = 'hi, how are you?'\ntext_without_punc = ''.join(ch for ch in text if not category(ch).startswith('P'))\n" }, { "answer_id": 63500846, "author": "Zain Sarwar", "author_id": 10873786, "author_profile": "https://Stackoverflow.com/users/10873786", "pm_score": 2, "selected": false, "text": "import re\n\npunct = re.compile(r'(\\w+)')\n\nsentence = 'This ! is : a # sample $ sentence.' # Text with punctuation\ntokenized = [m.group() for m in punct.finditer(sentence)]\nsentence = ' '.join(tokenized)\nprint(sentence) \n'This is a sample sentence'\n\n" }, { "answer_id": 63701027, "author": "Vivian", "author_id": 14147996, "author_profile": "https://Stackoverflow.com/users/14147996", "pm_score": 2, "selected": false, "text": "regex.sub(r'\\p{P}','', s)\n" }, { "answer_id": 66818521, "author": "aloha", "author_id": 3097391, "author_profile": "https://Stackoverflow.com/users/3097391", "pm_score": 3, "selected": false, "text": "import re \n\ns = \"string. With. Punctuation?\" \ns = re.sub(r'[\\W\\s]', ' ', s)\n\nprint(s)\n'string With Punctuation '\n" }, { "answer_id": 67282473, "author": "mohannatd", "author_id": 14111556, "author_profile": "https://Stackoverflow.com/users/14111556", "pm_score": 0, "selected": false, "text": "import string\n' '.join(word.strip(string.punctuation) for word in 'text'.split())\n" }, { "answer_id": 68774177, "author": "Dexter Legaspi", "author_id": 918858, "author_profile": "https://Stackoverflow.com/users/918858", "pm_score": 2, "selected": false, "text": "you're anal-retentive # using lambda\n''.join(filter(lambda c: c not in string.punctuation, s))\n\n# using list comprehension\n''.join('' if c in string.punctuation else c for c in s)\n" }, { "answer_id": 69451380, "author": "Bob Kline", "author_id": 1357340, "author_profile": "https://Stackoverflow.com/users/1357340", "pm_score": 1, "selected": false, "text": "translate #!/usr/bin/env python3\n\n\"\"\"Determination of most efficient way to remove punctuation in Python 3.\n\nResults in Python 3.8.10 on my system using the default arguments:\n\nset : 51.897\nregex : 17.901\ntranslate : 2.059\nreplace : 13.209\n\"\"\"\n\nimport argparse\nimport re\nimport string\nimport timeit\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--filename\", \"-f\", default=argparse.__file__)\nparser.add_argument(\"--iterations\", \"-i\", type=int, default=10000)\nopts = parser.parse_args()\nwith open(opts.filename) as fp:\n s = fp.read()\nexclude = set(string.punctuation)\ntable = str.maketrans(\"\", \"\", string.punctuation)\nregex = re.compile(f\"[{re.escape(string.punctuation)}]\")\n\ndef test_set(s):\n return \"\".join(ch for ch in s if ch not in exclude)\n\ndef test_regex(s): # From Vinko's solution, with fix.\n return regex.sub(\"\", s)\n\ndef test_translate(s):\n return s.translate(table)\n\ndef test_replace(s): # From S.Lott's solution\n for c in string.punctuation:\n s = s.replace(c, \"\")\n return s\n\nopts = dict(globals=globals(), number=opts.iterations)\nsolutions = \"set\", \"regex\", \"translate\", \"replace\"\nfor solution in solutions:\n elapsed = timeit.timeit(f\"test_{solution}(s)\", **opts)\n print(f\"{solution:<10}: {elapsed:6.3f}\")\n" }, { "answer_id": 70186138, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 0, "selected": false, "text": "regex \\p{X} \\P{X} [:name:] pip install regex pip3 install regex regex.sub(r'[\\p{P}\\p{S}]', '', text) # to remove one by one\nregex.sub(r'[\\p{P}\\p{S}]+', '', text) # to remove all consecutive punctuation/symbols with one go\nregex.sub(r'[[:punct:]]+', '', text) # Same with a POSIX character class\n import regex\n\ntext = 'भारत India <><>^$.,,! 002'\nnew_text = regex.sub(r'[\\p{P}\\p{S}\\s]+', ' ', text).lower().strip()\n# OR\n# new_text = regex.sub(r'[[:punct:]\\s]+', ' ', text).lower().strip()\n\nprint(new_text)\n# => भारत india 002\n \\s" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
265,970
<p>I'm more of a programmer than a designer, and I'm trying to embrace <code>&lt;div&gt;</code>s rather than using tables but am getting stuck.</p> <p>Here's what I'm trying to do. I am setting up a survey page. I want each question's text to sit at the top of the blue div, and wrap if it's too long. I want all of the red divs to line up at the top right corner of the container div.</p> <p><a href="http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg" rel="nofollow noreferrer">Layout http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg</a></p> <p>Here's what I've started with, it works fine so long as the frame is more than 420 pixels wide. Then the red div skips to the next line. I think I may have approached it wrong, perhaps I should be floating things to the right?</p> <pre><code>.greencontainer{ width:100%; spacing : 10 10 10 10 ; float: left; } .redcontainer{ float: left; width: 20px; padding: 2 0 2 0; font-size: 11px; font-family: sans-serif; text-align: center; } .bluecontainer{ clear: both; float: left; width: 400px; padding: 2 2 2 10; font-size: 11px; font-family: sans-serif; text-align: left; } </code></pre>
[ { "answer_id": 266007, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 3, "selected": true, "text": "<div class=\"greencontainer\">\n <div class=\"redcontainer\">\n <input type=\"checkbox\" />\n </div>\n <div class=\"bluecontainer\">\n <label>Text about this checkbox...</label>\n </div>\n</div>\n .greencontainer{\n float:left;\n clear:left;\n width:100%;\n }\n .redcontainer{\n float:right;\n width:20px;\n }\n .bluecontainer{\n margin-right:20px;\n }\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28351/" ]
265,973
<p>I've inherited someone else's monster of a BASH script. The script was written in such a way that it uses a ridiculous amount of memory (around 1GB). I can run it from a shell with out issue, but if I run it from cron I crashes with a sig fault. </p> <p>Apart from digging into the poorly commented behemoth, is there a way to run it from cron with out running into the sig fault? </p> <p>Cheers,</p> <p>Steve</p>
[ { "answer_id": 266161, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": -1, "selected": false, "text": "/path/to/bigscript.sh &> /dev/null\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
265,984
<p>Let's say we have defined a CSS class that is being applied to various elements on a page.</p> <pre><code>colourful { color: #DD00DD; background-color: #330033; } </code></pre> <p>People have complained about the colour, that they don't like pink/purple. So you want to give them the ability to change the style as they wish, and they can pick their favourite colours. You have a little colour-picker widget that invokes a Javascript function:</p> <pre><code>function changeColourful(colorRGB, backgroundColorRGB) { // answer goes here } </code></pre> <p>What goes in the body of that function?</p> <p>The intent being that when the user picks a new colour on the colour-picker all the elements with <code>class="colourful"</code> will have their style changed.</p>
[ { "answer_id": 266023, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": -1, "selected": false, "text": "function changeColourful(colorRGB, backgroundColorRGB)\n {changeColor (document, colorRGB, backgroundColorRGB)}\n\nfunction changeColor (node, color, changeToColor)\n{\n for(var ii = 0 ; ii < node.childNodes.length; ii++)\n {\n if(node.childNodes[ii].childNodes.length > 0)\n {\n changeColor(node.childNodes[ii], color, changeToColor);\n }\n\n if(node[ii].style.backgroundColor == color)\n {\n node[ii].style.backgroundColor = changeToColor;\n }\n\n }\n\n\n}\n" }, { "answer_id": 266043, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 3, "selected": false, "text": "colourful {\n color: ${userPrefs.colourfulColour};\n background-color: ${userPrefs.colourfulBackgroundColour};\n} \n" }, { "answer_id": 266062, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "document.styleSheets" }, { "answer_id": 266103, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 3, "selected": true, "text": "$('.colourful').css('background-color', 'purple').css('color','red');\n" }, { "answer_id": 266104, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "var setStyleRule = function(selector, rule) {\n var stylesheet = document.styleSheets[(document.styleSheets.length - 1)];\n if(stylesheet.addRule) {\n stylesheet.addRule(selector, rule)\n } else if(stylesheet.insertRule) {\n stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);\n }\n};\n" }, { "answer_id": 266110, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "function changeColourful(colorRGB, backgroundColorRGB)\n{\n $('.colourful').css({color:colorRGB,backgroundColor:backgroundColorRGB});\n}\n" }, { "answer_id": 266875, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 2, "selected": false, "text": "<style id=\"customstyle\" type=\"text/css\"></style>\n $(\"#customstyle\").text(\".colourful { color: #345 ; }\");\n $(\"#customstyle\").append(\".colourful { color: #345 ; }\");\n var csscontent = $(\"#customstyle\").text();\n" }, { "answer_id": 8695784, "author": "megar", "author_id": 1070873, "author_profile": "https://Stackoverflow.com/users/1070873", "pm_score": 1, "selected": false, "text": "function changeBgImg(newimage) {\n var i,n;\n var ssheets = document.styleSheets; // all styleSheets. Find the right one\n var ssheet;\n\n // find the last one whose href contain \"myhref\"\n n = ssheets.length;\n for (i=n-1; i>=0 ;i--) {\n var thisheet = ssheets[i];\n if ( (null != thisheet.href) && (thisheet.href.indexOf(\"mycss.css\") != -1) ) {\n ssheet = thisheet; break;\n }\n }\n\n if ( (null == ssheet) || (\"undefined\" == typeof(ssheet.cssRules))) {\n // stylesheet not found or internet explorer 6\n return;\n }\n\n // find the right rule\n var rule;\n n = ssheet.cssRules.length;\n for (i=0; i<n; i++) {\n var r = ssheet.cssRules.item(i);\n if (typeof(r.selectorText) == \"undefined\") { continue; }\n if (r.selectorText.indexOf(\"MYCSSRULE\") != -1) {\n rule = r; break;\n }\n }\n\n if (null == rule) {\n // not found\n return;\n }\n\n rule.style.backgroundImage = \"url(\" + newImage + \")\";\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34778/" ]
266,002
<p>I'm using this XPath to get the value of a field:</p> <pre class="lang-none prettyprint-override"><code>//input[@type="hidden"][@name="val"]/@value </code></pre> <p>I get several results, but I only want the first. Using</p> <pre class="lang-none prettyprint-override"><code>//input[@type="hidden"][@name="val"]/@value[1] </code></pre> <p>Doesn't work. Once I have this, how do I pick up the value in Greasemonkey? I am trying things like:</p> <pre><code>alert("val " + val.snapshotItem); </code></pre> <p>But I think that's for the node, rather than the string.</p>
[ { "answer_id": 266083, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "var result = document.evaluate(\n \"//input[@type='hidden' and @name='var' and position()=1]/@value\",\n document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null\n);\n\nvar hiddenval = result.snapshotItem(0);\n\nif (hiddenval)\n alert(\"Found: \" + hiddenval.nodeValue); \nelse\n alert(\"Not found.\");\n \"position()=1\" snapshotItem(0) ORDERED_NODE_SNAPSHOT_TYPE" }, { "answer_id": 266337, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 2, "selected": false, "text": "var result = document.evaluate(\n \"//input[@type='hidden' and @name='var']\",\n document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);\n\nvar input = result.iterateNext();\n\nif (input)\n alert(\"Found: \" + input.value); \nelse\n alert(\"Not found.\");\n value" }, { "answer_id": 609403, "author": "Daniel X Moore", "author_id": 68210, "author_profile": "https://Stackoverflow.com/users/68210", "pm_score": -1, "selected": false, "text": "// ==UserScript==\n// @name MyScript\n// @namespace http://example.com\n// @description Example\n// @include *\n//\n// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js\n// ==/UserScript==\n\nvar input = $(\"input[type='hidden'][name='var']\");\n\nif (input) {\n alert(\"Found: \" + input.val()); \n} else {\n alert(\"Not found.\");\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
266,015
<p>I want to have two items on the same line using <code>float: left</code> for the item on the left.</p> <p>I have no problems achieving this alone. The problem is, I want the two items to <strong>stay</strong> on the same line <em>even when you resize the browser very small</em>. You know... like how it was with tables.</p> <p>The goal is to keep the item on the right from wrapping <em>no matter what</em>.</p> <p>How to I tell the browser using CSS that I would rather <strong>stretch the containing <code>div</code></strong> than wrap it so the the <code>float: right;</code> div is below the <code>float: left;</code> <code>div</code>?</p> <p>what I want:</p> <pre><code> \ +---------------+ +------------------------/ | float: left; | | float: right; \ | | | / | | |content stretching \ Screen Edge | | |the div off the screen / &lt;--- +---------------+ +------------------------\ / </code></pre>
[ { "answer_id": 266025, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 7, "selected": true, "text": "<div> <div> .minwidth { min-width:100px; width: auto !important; width: 100px; }\n !important min-width min-width width: 100px !important" }, { "answer_id": 9978234, "author": "Inserve", "author_id": 1308275, "author_profile": "https://Stackoverflow.com/users/1308275", "pm_score": 7, "selected": false, "text": ".parent {\n white-space: nowrap;\n}\n .child {\n display:inline-block;\n width:300px;\n white-space: normal;\n}\n" }, { "answer_id": 16628726, "author": "ScubaSteve", "author_id": 787958, "author_profile": "https://Stackoverflow.com/users/787958", "pm_score": -1, "selected": false, "text": "<div class=\"floatNoWrap\">\n <div id=\"A\" style=\"float: left;\">\n Content A\n </div>\n <div id=\"B\" style=\"float: left;\">\n Content B\n </div>\n <div style=\"clear: both;\"></div>\n</div>\n .floatNoWrap\n{\n width: 100%;\n height: 100%;\n}\n $(\"[class~='floatNoWrap']\").each(function () {\n $(this).css(\"width\", $(this).outerWidth());\n});\n" }, { "answer_id": 43114964, "author": "Nebojsha", "author_id": 3801270, "author_profile": "https://Stackoverflow.com/users/3801270", "pm_score": 1, "selected": false, "text": ".floated {\n float: left;\n ...\n box-sizing: border-box;\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
266,026
<p>Just looking for the relevant documentation. An example is not necessary, but would be appreciated. </p> <p>We have a situation where we are having to create 100s of virtual directories manually, and it seems like automating this would be a good way to make the process more efficient for now. </p> <p>Perhaps next year we can rework the server environment to allow something more sane, such as URL rewriting (unfortunately this does not seem feasible in the current cycle of the web application). Isn't it great to inherit crap code?</p> <p>~ William Riley-Land</p>
[ { "answer_id": 266045, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.DirectoryServices;\nusing System.IO;\n\nnamespace Common.DirectoryServices\n{\n public class IISManager\n {\n\n private string _webSiteID;\n\n public string WebSiteID\n {\n get { return _webSiteID; }\n set { _webSiteID = value; }\n }\n\n private string _strServerName;\n public string ServerName\n {\n get\n {\n return _strServerName;\n }\n set\n {\n _strServerName = value;\n }\n }\n\n private string _strVDirName;\n public string VDirName\n {\n get\n {\n return _strVDirName;\n }\n set\n {\n _strVDirName = value;\n }\n }\n\n private string _strPhysicalPath;\n public string PhysicalPath\n {\n get\n {\n return _strPhysicalPath;\n }\n set\n {\n _strPhysicalPath = value;\n }\n }\n\n private VDirectoryType _directoryType;\n public VDirectoryType DirectoryType\n {\n get\n {\n return _directoryType;\n }\n set\n {\n _directoryType = value;\n }\n }\n\n public enum VDirectoryType\n {\n FTP_DIR, WEB_IIS_DIR\n };\n\n public string CreateVDir()\n {\n System.DirectoryServices.DirectoryEntry oDE;\n System.DirectoryServices.DirectoryEntries oDC;\n System.DirectoryServices.DirectoryEntry oVirDir;\n //try\n // {\n //check whether to create FTP or Web IIS Virtual Directory\n if (this.DirectoryType == VDirectoryType.WEB_IIS_DIR)\n {\n oDE = new DirectoryEntry(\"IIS://\" +\n this._strServerName + \"/W3SVC/\" + _webSiteID + \"/Root\");\n }\n else\n {\n oDE = new DirectoryEntry(\"IIS://\" +\n this._strServerName + \"/MSFTPSVC/1/Root\");\n }\n\n //Get Default Web Site\n oDC = oDE.Children;\n\n //Add row\n oVirDir = oDC.Add(this._strVDirName,\n oDE.SchemaClassName.ToString());\n\n //Commit changes for Schema class File\n oVirDir.CommitChanges();\n\n //Create physical path if it does not exists\n if (!Directory.Exists(this._strPhysicalPath))\n {\n Directory.CreateDirectory(this._strPhysicalPath);\n }\n\n //Set virtual directory to physical path\n oVirDir.Properties[\"Path\"].Value = this._strPhysicalPath;\n\n //Set read access\n oVirDir.Properties[\"AccessRead\"][0] = true;\n\n //Create Application for IIS Application (as for ASP.NET)\n if (this.DirectoryType == VDirectoryType.WEB_IIS_DIR)\n {\n oVirDir.Invoke(\"AppCreate\", true);\n oVirDir.Properties[\"AppFriendlyName\"][0] = this._strVDirName;\n }\n\n //Save all the changes\n oVirDir.CommitChanges();\n\n return null;\n\n // }\n //catch (Exception exc)\n //{\n // return exc.Message.ToString();\n //}\n }\n }\n}\n" }, { "answer_id": 266058, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "' This code creates a virtual directory in the default Web Site\n' ---------------------------------------------------------------\n' From the book \"Windows Server Cookbook\" by Robbie Allen\n' ISBN: 0-596-00633-0\n' ---------------------------------------------------------------\n\n' ------ SCRIPT CONFIGURATION ------\nstrComputer = \"rallen-w2k3\"\nstrVdirName = \"<VdirName>\" 'e.g. employees\nstrVdirPath = \"<Path>\" 'e.g. D:\\resumes\n' ------ END CONFIGURATION ---------\nset objIIS = GetObject(\"IIS://\" & strComputer & \"/W3SVC/1\")\nset objWebSite = objIIS.GetObject(\"IISWebVirtualDir\",\"Root\")\nset objVdir = objWebSite.Create(\"IISWebVirtualDir\",strVdirName)\nobjVdir.AccessRead = True\nobjVdir.Path = strVdirPath\nobjVdir.SetInfo\nWScript.Echo \"Successfully created virtual directory: \" & objVdir.Name\n" }, { "answer_id": 266061, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 3, "selected": true, "text": "$objIIS = new-object System.DirectoryServices.DirectoryEntry(\"IIS://localhost/W3SVC/1/Root\")\n$children = $objIIS.psbase.children\n$vDir = $children.add(\"NewFolder\",$objIIS.psbase.SchemaClassName)\n$vDir.psbase.CommitChanges()\n$vDir.Path = \"C:\\Documents and Settings\\blah\\Desktop\\new\"\n$vDir.defaultdoc = \"Default.htm\"\n$vDir.psbase.CommitChanges()\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17847/" ]
266,028
<p>We are looking to provide two <strong>custom Platform switches</strong> (the <strong>platform dropdown</strong> in the configuration manager) for our projects <strong>in Visual Studio</strong>. </p> <p>For example one for 'Desktop' and one for 'Web'. The target build tasks then compile the code in a custom way based on the platform switch. We don't want to add to the Debug Release switch because we would need those for each Desktop and Web platforms.</p> <p>We found one way to attempt this, is to modify the .csproj file to add something like this</p> <pre><code>&lt;Platform Condition=" '$(Platform)' == '' "&gt;Desktop&lt;/Platform&gt; </code></pre> <p>and add propertygroups like,</p> <pre><code> &lt;PropertyGroup Condition=" '$(Platform)' == 'Web' "&gt; &lt;DefineConstants&gt;/define Web&lt;/DefineConstants&gt; &lt;PlatformTarget&gt;Web&lt;/PlatformTarget&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup Condition=" '$(Platform)' == 'Desktop' "&gt; &lt;DefineConstants&gt;/define Desktop&lt;/DefineConstants&gt; &lt;PlatformTarget&gt;Desktop&lt;/PlatformTarget&gt; &lt;/PropertyGroup&gt; </code></pre> <p>But still this doesn't work, and compiler throws an error</p> <p><em>Invalid option 'Desktop' for /platform; must be anycpu, x86, Itanium or x64</em></p> <p>So does it have to be one of those options and can't we add our custom platforms?</p> <p>Has anyone been able to do this? any pointers would be helpful.</p> <p>Update: Using DebugDesktop and ReleaseDesktop will make it more complicated for users. Because 'desktop' and 'web' are actually platforms and also there is ability to add new platforms in the dropdown (i.e. ), I believe 'platform' switch should be used for the exact same purpose.</p>
[ { "answer_id": 6463259, "author": "aster.x", "author_id": 506499, "author_profile": "https://Stackoverflow.com/users/506499", "pm_score": 3, "selected": false, "text": "<PropertyGroup Condition=\" '$(Platform)' == 'Web' \">\n <DefineConstants>Web</DefineConstants>\n <PlatformTarget>AnyCPU</PlatformTarget>\n</PropertyGroup>\n<PropertyGroup Condition=\" '$(Platform)' == 'Desktop' \">\n <DefineConstants>Desktop</DefineConstants>\n <PlatformTarget>AnyCPU</PlatformTarget>\n</PropertyGroup>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747/" ]
266,082
<p>How do I tell if my application (compiled in Visual&nbsp;Studio&nbsp;2008 as <em>Any CPU</em>) is running as a 32-bit or 64-bit application?</p>
[ { "answer_id": 266084, "author": "Redwood", "author_id": 1512, "author_profile": "https://Stackoverflow.com/users/1512", "pm_score": 3, "selected": false, "text": "public static bool Is64BitMode() {\n return System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8;\n}\n" }, { "answer_id": 397695, "author": "Perica Zivkovic", "author_id": 31822, "author_profile": "https://Stackoverflow.com/users/31822", "pm_score": 7, "selected": true, "text": "if (IntPtr.Size == 8) \n{\n // 64 bit machine\n} \nelse if (IntPtr.Size == 4) \n{\n // 32 bit machine\n}\n" }, { "answer_id": 3461579, "author": "Sam", "author_id": 417602, "author_profile": "https://Stackoverflow.com/users/417602", "pm_score": 7, "selected": false, "text": "Environment.Is64BitProcess\n" }, { "answer_id": 7297127, "author": "Scott Ge", "author_id": 927204, "author_profile": "https://Stackoverflow.com/users/927204", "pm_score": 3, "selected": false, "text": "IsWow64Process() static bool Is64BitProcess(IntPtr hProcess)\n{\n bool flag = false;\n\n if (Environment.Is64BitOperatingSystem)\n {\n // On 64-bit OS, if a process is not running under Wow64 mode, \n // the process must be a 64-bit process.\n flag = !(NativeMethods.IsWow64Process(hProcess, out flag) && flag);\n }\n\n return flag;\n}\n" }, { "answer_id": 45617262, "author": "Owen Pauling", "author_id": 1688439, "author_profile": "https://Stackoverflow.com/users/1688439", "pm_score": 0, "selected": false, "text": "System.Runtime.InteropServices.RuntimeInformation.OSArchitecture" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow noreferrer">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
[ { "answer_id": 266509, "author": "Null303", "author_id": 13787, "author_profile": "https://Stackoverflow.com/users/13787", "pm_score": 1, "selected": false, "text": "manager.py" }, { "answer_id": 624603, "author": "Idan Gazit", "author_id": 29451, "author_profile": "https://Stackoverflow.com/users/29451", "pm_score": 0, "selected": false, "text": "mod_wsgi mod_wsgi" }, { "answer_id": 624751, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 0, "selected": false, "text": "mod_wsgi environ wsgi_start_response envrion environ['PATH_INFO'] wsgi_start_response wsgi_start_response(output_response, output_headers)\n output_response 200 OK output_headers [(\"Content-type\", \"text/html\")] spawning spawn scriptname.my_wsgi_function_nae" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
266,115
<p>The title is kind of obscure. What I want to know is if this is possible:</p> <pre><code>string typeName = &lt;read type name from somwhere&gt;; Type myType = Type.GetType(typeName); MyGenericClass&lt;myType&gt; myGenericClass = new MyGenericClass&lt;myType&gt;(); </code></pre> <p>Obviously, MyGenericClass is described as:</p> <pre><code>public class MyGenericClass&lt;T&gt; </code></pre> <p>Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.</p>
[ { "answer_id": 266282, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "using System;\nusing System.Reflection;\n\npublic class Generic<T>\n{\n public Generic()\n {\n Console.WriteLine(\"T={0}\", typeof(T));\n }\n}\n\nclass Test\n{\n static void Main()\n {\n string typeName = \"System.String\";\n Type typeArgument = Type.GetType(typeName);\n\n Type genericClass = typeof(Generic<>);\n // MakeGenericType is badly named\n Type constructedClass = genericClass.MakeGenericType(typeArgument);\n\n object created = Activator.CreateInstance(constructedClass);\n }\n}\n Type genericClass = typeof(IReadOnlyDictionary<,>);\nType constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);\n" }, { "answer_id": 26368508, "author": "Chris Marisic", "author_id": 37055, "author_profile": "https://Stackoverflow.com/users/37055", "pm_score": 2, "selected": false, "text": "public class Encoder() {\npublic void Markdown(IEnumerable<FooContent> contents) { do magic }\npublic void Markdown(IEnumerable<BarContent> contents) { do magic2 }\n}\n var fooContents = new List<FooContent>(fooContent)\nnew Encoder().Markdown(fooContents)\n var listType = typeof(List<>).MakeGenericType(myType);\nvar dynamicList = Activator.CreateInstance(listType);\n((IList)dynamicList).Add(fooContent);\n Markdown(IEnumerable<FooContent> contents) new Encoder().Markdown( (dynamic) dynamicList)\n dynamic dynamicList List<FooContent> IEnumerable<FooContent> Markdown" }, { "answer_id": 30814072, "author": "Master P", "author_id": 5005127, "author_profile": "https://Stackoverflow.com/users/5005127", "pm_score": 2, "selected": false, "text": "namespace GenericTest\n{\n public class Item\n {\n }\n}\n\nnamespace GenericTest\n{\n public class GenericClass<T>\n {\n }\n}\n var t = Type.GetType(\"GenericTest.GenericClass`1[[GenericTest.Item, GenericTest]], GenericTest\");\nvar a = Activator.CreateInstance(t);\n" }, { "answer_id": 53961816, "author": "Todd Skelton", "author_id": 1212994, "author_profile": "https://Stackoverflow.com/users/1212994", "pm_score": 0, "selected": false, "text": "public class Type1 { }\n\npublic class Type2 { }\n\npublic class Generic<T> { }\n\npublic class Program\n{\n public static void Main()\n {\n var typeName = nameof(Type1);\n\n switch (typeName)\n {\n case nameof(Type1):\n var type1 = new Generic<Type1>();\n // do something\n break;\n case nameof(Type2):\n var type2 = new Generic<Type2>();\n // do something\n break;\n }\n }\n}\n" }, { "answer_id": 56587641, "author": "EGN", "author_id": 1234374, "author_profile": "https://Stackoverflow.com/users/1234374", "pm_score": 0, "selected": false, "text": "void AddValue<T>(object targetList, T valueToAdd)\n{\n var addMethod = targetList.GetType().GetMethod(\"Add\");\n addMethod.Invoke(targetList, new[] { valueToAdd } as object[]);\n}\n\nvar listType = typeof(List<>).MakeGenericType(new[] { dynamicType }); // dynamicType is the type you want\nvar list = Activator.CreateInstance(listType);\n\nAddValue(list, 5);\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9209/" ]
266,116
<p>How do you programmatically obtain a picture of a .Net control?</p>
[ { "answer_id": 266139, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "Control c = new TextBox();\nSystem.Drawing.Bitmap bmp = new System.Drawing.Bitmap(c.Width, c.Height);\nc.DrawToBitmap(bmp, c.ClientRectangle);\n" }, { "answer_id": 266142, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 2, "selected": false, "text": "public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds);\n" }, { "answer_id": 266146, "author": "Joey", "author_id": 25962, "author_profile": "https://Stackoverflow.com/users/25962", "pm_score": 3, "selected": false, "text": " Dim formImage As New Bitmap(\"C:\\File.bmp\")\n Me.DrawToBitmap(formImage, Me.Bounds)\n Bitmap formImage = New Bitmap(\"C:\\File.bmp\")\n this.DrawToBitmap(formImage, this.Bounds)\n" }, { "answer_id": 6293657, "author": "R Muruganandhan", "author_id": 791012, "author_profile": "https://Stackoverflow.com/users/791012", "pm_score": 1, "selected": false, "text": "Panel1.Dock = DockStyle.None ' If Panel Dockstyle is in Fill mode\nPanel1.Width = 5000 ' Original Size without scrollbar\nPanel1.Height = 5000 ' Original Size without scrollbar\n\nDim bmp As New Bitmap(Me.Panel1.Width, Me.Panel1.Height)\nMe.Panel1.DrawToBitmap(bmp, New Rectangle(0, 0, Me.Panel1.Width, Me.Panel1.Height))\n'Me.Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)\nbmp.Save(\"C:\\panel.jpg\", System.Drawing.Imaging.ImageFormat.Jpeg)\n\nPanel1.Dock = DockStyle.Fill\n" }, { "answer_id": 16408849, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 2, "selected": false, "text": "Form Rectangle r = this.Bounds;\n r.Offset(-r.X,-r.Y);\n Bitmap bitmap = new Bitmap(r.Width,r.Height);\n this.DrawToBitmap(bitmap, r);\n Clipboard.SetImage(bitmap);\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34787/" ]
266,123
<p>Maybe I should further qualify this - Is there a way to specify which direction a ComboBox will open without copying and pasting the entire ComboBox class and ripping out the code where it determines which direction it will open in...</p> <p>I'm my specific case - I need it to open upwards - always.</p> <p>UPDATE: You can't fix this by subclassing it because the function that handles the direction of the opening is:</p> <pre><code>private function displayDropdown(show:Boolean, trigger:Event = null):void </code></pre> <p>And that bad boy uses a fair amount of private variables which my subclass wouldn't have access to...</p>
[ { "answer_id": 268915, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 3, "selected": true, "text": "private function initMenu(): void {\n var m:Menu = new Menu();\n m.dataProvider = theMenuData;\n m.addEventListener(MenuEvent.ITEM_CLICK, menuClick);\n m.showRoot = false;\n // m.x = ... <-- probably don't need to tweak this.\n // m.y = ... <-- this is really the interesting one :-)\n theMenu.popUp = m;\n}\n<mx:PopUpButton id=\"theMenu\" creationComplete=\"initMenu()\" ... />\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
266,168
<p>Can someone post a simple example of starting two (Object Oriented) threads in C++. </p> <p>I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.</p> <p>I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.</p>
[ { "answer_id": 266180, "author": "LorenzCK", "author_id": 3118, "author_profile": "https://Stackoverflow.com/users/3118", "pm_score": 3, "selected": false, "text": "class RThread : public wxThread {\n\npublic:\n RThread()\n : wxThread(wxTHREAD_JOINABLE){\n }\nprivate:\n RThread(const RThread &copy);\n\npublic:\n void *Entry(void){\n //Do...\n\n return 0;\n }\n\n};\n\nwxThread *CreateThread() {\n //Create thread\n wxThread *_hThread = new RThread();\n\n //Start thread\n _hThread->Create();\n _hThread->Run();\n\n return _hThread;\n}\n" }, { "answer_id": 266198, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 6, "selected": false, "text": "std::thread #include <boost/thread.hpp>\n\nvoid task1() {\n // do stuff\n}\n\nvoid task2() {\n // do stuff\n}\n\nint main (int argc, char ** argv) {\n using namespace boost;\n thread thread_1 = thread(task1);\n thread thread_2 = thread(task2);\n\n // do other stuff\n thread_2.join();\n thread_1.join();\n return 0;\n}\n" }, { "answer_id": 11229853, "author": "MasterMastic", "author_id": 825637, "author_profile": "https://Stackoverflow.com/users/825637", "pm_score": 10, "selected": true, "text": "void task1(std::string msg)\n{\n std::cout << \"task1 says: \" << msg;\n}\n thread std::thread t1(task1, \"Hello\");\n #include <thread> std::thread t1.join();\n #include <string>\n#include <iostream>\n#include <thread>\n\nusing namespace std;\n\n// The function we want to execute on the new thread.\nvoid task1(string msg)\n{\n cout << \"task1 says: \" << msg;\n}\n\nint main()\n{\n // Constructs the new thread and runs it. Does not block execution.\n thread t1(task1, \"Hello\");\n\n // Do other things...\n\n // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.\n t1.join();\n}\n -std=c++0x -pthread" }, { "answer_id": 16091180, "author": "Hohenheimsenberg", "author_id": 560678, "author_profile": "https://Stackoverflow.com/users/560678", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\n#include <iostream>\n\nvoid *task(void *argument){\n char* msg;\n msg = (char*)argument;\n std::cout << msg << std::endl;\n}\n\nint main(){\n pthread_t thread1, thread2;\n int i1, i2;\n i1 = pthread_create(&thread1, NULL, task, (void*) \"thread 1\");\n i2 = pthread_create(&thread2, NULL, task, (void*) \"thread 2\");\n\n pthread_join(thread1, NULL);\n pthread_join(thread2, NULL);\n return 0;\n}\n" }, { "answer_id": 44452404, "author": "Caner", "author_id": 448625, "author_profile": "https://Stackoverflow.com/users/448625", "pm_score": 5, "selected": false, "text": "#include <thread>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nvoid doSomething(int id) {\n cout << id << \"\\n\";\n}\n\n/**\n * Spawns n threads\n */\nvoid spawnThreads(int n)\n{\n std::vector<thread> threads(n);\n // spawn n threads:\n for (int i = 0; i < n; i++) {\n threads[i] = thread(doSomething, i + 1);\n }\n\n for (auto& th : threads) {\n th.join();\n }\n}\n\nint main()\n{\n spawnThreads(10);\n}\n" }, { "answer_id": 46286270, "author": "livingtech", "author_id": 18961, "author_profile": "https://Stackoverflow.com/users/18961", "pm_score": 4, "selected": false, "text": "class DataManager\n{\npublic:\n bool hasData;\n void getData();\n bool dataAvailable();\n};\n #include \"DataManager.h\"\n\nvoid DataManager::getData()\n{\n // perform background data munging\n hasData = true;\n // be sure to notify on the main thread\n}\n\nbool DataManager::dataAvailable()\n{\n if (hasData)\n {\n return true;\n }\n else\n {\n std::thread t(&DataManager::getData, this);\n t.detach(); // as opposed to .join, which runs on the current thread\n }\n}\n" }, { "answer_id": 47171594, "author": "Daksh Gupta", "author_id": 5662469, "author_profile": "https://Stackoverflow.com/users/5662469", "pm_score": 4, "selected": false, "text": "int main() {\n int localVariable = 100;\n\n thread th { [=]() {\n cout << \"The value of local variable => \" << localVariable << endl;\n }};\n\n th.join();\n\n return 0;\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112692/" ]
266,184
<p>I'm trying to be responsible with my "DOM" references in this little Flash 8/AS2 project.</p> <p>What has become increasingly frustrating is obtaining references to other movie clips and objects. For example, currently my code to access the submit button of a form looks something like this</p> <pre><code>var b:Button = _level0.instance4.submitBtn; </code></pre> <p>I was hoping there was an instance-retrieval method for AS2 similar to AS3's <code>MovieClip.getChildByName()</code> or even Javascript's <code>document.getElementById()</code>. Because hard-coding the names of these anonymous instances (like <code>instance4</code> in the above) just feel really, really dirty.</p> <p>But, I can't find anything of the sort at <a href="http://flash-reference.icod.de/" rel="nofollow noreferrer">this AS2 Reference</a>.</p>
[ { "answer_id": 266604, "author": "moritzstefaner", "author_id": 23069, "author_profile": "https://Stackoverflow.com/users/23069", "pm_score": 2, "selected": true, "text": "var my_MC=createEmptyMovieClip(\"instanceName\", depth);\n _parentClip.instanceName my_MC." }, { "answer_id": 266912, "author": "Luke", "author_id": 21406, "author_profile": "https://Stackoverflow.com/users/21406", "pm_score": 0, "selected": false, "text": "MovieClip.prototype.getElementByName = function(name : String) : Object\n{\n var s : String;\n var mc : Movieclip = null;\n\n for( s in this )\n {\n if( this[s] instanceof MovieClip )\n {\n if( s == name )\n {\n mc = this[ s ];\n break;\n }\n\n mc = this[s].getElementByName( name );\n }\n }\n\n return( mc );\n}\n" }, { "answer_id": 279989, "author": "user36432", "author_id": 36432, "author_profile": "https://Stackoverflow.com/users/36432", "pm_score": 1, "selected": false, "text": "var b:Button = _root.instance4.submitBtn;\n var b:Button = _root[\"instance4\"].submitBtn;\n for( var i:Number = 0; i < 101; i++)\n{\n var button:Button = _root[\"instance\"+i].submitBtn;\n button._alpha = 0;\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8815/" ]
266,196
<p>I'm looking at having certain users access one database and other users accessing another database based on the company they belong to. What would be the best way to handle the connection strings and make sure the user connects to the right db when they login?</p> <p>Thanks for any ideas.</p>
[ { "answer_id": 266225, "author": "GeekyMonkey", "author_id": 29900, "author_profile": "https://Stackoverflow.com/users/29900", "pm_score": 4, "selected": true, "text": "<connectionStrings>\n <add name=\"ConnectionForDudes\" providerName=\"System.Data.SqlClient\"\n connectionString=\"Data Source=___MALECONNECTIONHERE___\"/>\n <add name=\"ConnectionForChicks\" providerName=\"System.Data.SqlClient\"\n connectionString=\"Data Source=___FEMALECONNECTIONHERE___\"/>\n</connectionStrings>\n bool UserIsMale = true;\nstring ConnectionStringName = \"ConnectionFor\" + UserIsMale ? \"Dudes\" : \"Chicks\";\nstring ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34571/" ]
266,199
<p>I'm trying to do a very simple button that changes color based on mouseover, mouseout and click, I'm doing this in prototype and the weird thing is if I used mouseover and mouseout, after I clicked on the button, the button wouldn't change to white, seems like it is because of the mouseout, here's my code</p> <pre><code>$("izzy").observe('mouseover', function() { $('izzy').setStyle({ color: '#FFFFFF' }); }); $("izzy").observe('mouseout', function() { $('izzy').setStyle({ color: '#666666' }); }); $("izzy").observe('click', function() { $('izzy').setStyle({ color: '#FFFFFF' }); }); </code></pre> <p>how can I fix it? Thanks.</p>
[ { "answer_id": 266223, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 2, "selected": false, "text": "var wasClicked = false;\n\n$(\"izzy\").observe('mouseover', function() {\n if (!wasClicked) $('izzy').setStyle({ color: '#FFFFFF' });\n});\n\n$(\"izzy\").observe('mouseout', function() {\n if (!wasClicked) $('izzy').setStyle({ color: '#666666' });\n});\n\n$(\"izzy\").observe('click', function() {\n $('izzy').setStyle({ color: '#FFFFFF' });\n wasClicked = true;\n});\n" }, { "answer_id": 266226, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "var clicked = false\n$(\"izzy\").observe('mouseover', function() {\n if(!clicked) {\n $('izzy').setStyle({ color: '#FFFFFF' });\n }\n});\n\n$(\"izzy\").observe('mouseout', function() {\n if(!clicked) {\n $('izzy').setStyle({ color: '#666666' });\n }\n});\n\n$(\"izzy\").observe('click', function() {\n clicked = true\n $('izzy').setStyle({ color: '#cccccc' });\n});\n" }, { "answer_id": 266228, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": true, "text": "#izzy:hover { color: '#FFFFFF'; }\n $(\"izzy\").observe('click', function() {\n $('izzy').addClass('selected');\n});\n #izzy { color: '#666666'; }\n#izzy:hover, #izzy.selected { color: '#FFFFFF'; }\n" }, { "answer_id": 342011, "author": "thoughtcrimes", "author_id": 37814, "author_profile": "https://Stackoverflow.com/users/37814", "pm_score": 0, "selected": false, "text": "$(\"izzy\").observe('click', function(e) {\n e.element().setStyle({ color: '#FFFFFF' });\n e.element().stopObserving('mouseout');\n});\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34797/" ]
266,202
<h2>There seems to be two major conventions for organizing project files and then many variations.</h2> <p><strong>Convention 1: High-level type directories, project sub-directories</strong></p> <p>For example, the <a href="http://svn.wxwidgets.org/svn/wx/wxWidgets/trunk/" rel="nofollow noreferrer">wxWidgets</a> project uses this style:</p> <pre><code>/solution /bin /prj1 /prj2 /include /prj1 /prj2 /lib /prj1 /prj2 /src /prj1 /prj2 /test /prj1 /prj2 </code></pre> <p><strong>Pros:</strong></p> <ul> <li>If there are project dependencies, they can be managed from a single file</li> <li>Flat build file structure</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>Since test has its own header and cpp files, when you generate the unit test applications for EXE files rather than libraries, they need to include the <a href="https://en.wikipedia.org/wiki/Object_file" rel="nofollow noreferrer">object files</a> from the application you are testing. This requires you to create inference rules and expand out relative paths for all the source files.</li> <li>Reusing any of the projects in another solution requires you to extract the proper files out of the tree structure and modify any build scripts</li> </ul> <p><strong>Convention 2: High-level project directories, type sub-directories</strong></p> <p>For example, the <a href="http://anonsvn.wireshark.org/wireshark/trunk/" rel="nofollow noreferrer">Wireshark</a> project uses this style</p> <pre><code>/solution /prj1 /bin /include /lib /src /test /prj2 /bin /include /lib /src /test </code></pre> <p><strong>Pros:</strong></p> <ul> <li>Projects themselves are self-contained within their folders, making them easier to move and reuse</li> <li>Allows for shorter inference rules in the build tools</li> <li>Facilitates hierarchical build scripts</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>If there are dependencies between projects, you need an additional layer of build scripts above the project directories to manage the build order</li> </ul> <p>We are currently using convention 1 on our project and so far it has worked fairly well. Now, I am in the process of adding unit testing (via CxxTest) and facilitating the migration to continuous integration using <a href="https://en.wikipedia.org/wiki/Make_%28software%29#Modern_versions" rel="nofollow noreferrer">nmake</a>, convention 1 is causing some serious headaches in the creation of the proper nmake files.</p> <h2>My primary requirements/goals are:</h2> <ul> <li><p>Reduce the level of effort to maintain the build scripts of the entire solution.</p></li> <li><p>De-couple projects and their build steps within a solution from other projects.</p></li> <li><p>Facilitate continuous integration via the use of build scripts for check-out to release media generation for each commit (obviously leveraging other tools such as CruiseControl as well).</p></li> <li><p>Make adding or removing additional projects or source files as easy and least error-prone as possible for the developers.</p></li> </ul> <h2>So I ask:</h2> <ul> <li>Are there other pros and cons of either of these methods?</li> <li>Is there a clear agrument that favors only one of these conventions?</li> </ul>
[ { "answer_id": 268485, "author": "Thomas L Holaday", "author_id": 29403, "author_profile": "https://Stackoverflow.com/users/29403", "pm_score": 1, "selected": false, "text": "mkdir /solution/test\nlinkd /solution/test/prj1 /solution/prj1/test\nlinkd /solution/test/prj2 /solution/prj2/test\n /solution\n /test\n /prj1\n /prj2 \n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2233/" ]
266,206
<p>I'm relatively new to C++. In Java, it's easy for me to instantiate and use a hashmap. I'd like to know how to do it in a simple way in C++, since I saw many different implementations and none of them looked simple to me.</p>
[ { "answer_id": 266233, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 6, "selected": true, "text": "std::hash_map C++0x std::unordered_map int char bool char * hash_map MyClass size_t MyClass::HashValue() const { /* something */ }\nbool MyClass::Equals(const MyClass& other) const { /* something */ }\n struct MyClassHash {\n size_t operator()(const MyClass& p) const {\n return p.HashValue();\n }\n};\n\nstruct MyClassEqual {\n bool operator()(const MyClass& c1, const MyClass& c2) const {\n return c1.Equals(c2);\n }\n};\n hash_map hash_set hash_map<MyClass, DataType, MyClassHash, MyClassEqual> my_hash_map;\nhash_set<MyClass, MyClassHash, MyClassEqual> my_hash_set;\n" }, { "answer_id": 266452, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 4, "selected": false, "text": "unordered_map #include <unordered_map>\n#include <string>\n#include <iostream>\n\nint main()\n{\n typedef std::tr1::unordered_map< std::string, int > hashmap;\n hashmap numbers;\n\n numbers[\"one\"] = 1;\n numbers[\"two\"] = 2;\n numbers[\"three\"] = 3;\n\n std::tr1::hash< std::string > hashfunc = numbers.hash_function();\n for( hashmap::const_iterator i = numbers.begin(), e = numbers.end() ; i != e ; ++i ) {\n std::cout << i->first << \" -> \" << i->second << \" (hash = \" << hashfunc( i->first ) << \")\" << std::endl;\n }\n return 0;\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33857/" ]
266,213
<p>Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG? </p> <p>The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension. </p> <p>so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different. </p> <p>Thanks! </p>
[ { "answer_id": 266273, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 3, "selected": true, "text": "function isImage(url, callback) {\n var img = document.createElement('img');\n img.onload = function() {\n callback(url);\n }\n img.src = url;\n}\n isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });\n function isImage(url) {\n var img = document.createElement('img');\n img.onload = function() {\n isImageCallback(url, true);\n }\n img.onerror = function() {\n isImageCallback(url, false);\n }\n img.src = url;\n }\n\n function isImageCallback(url, result) {\n if (result)\n alert(url + ' is an image');\n else\n alert(url + ' is not an image');\n }\n" }, { "answer_id": 266356, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "function isImage(url)\n{\n var http = getHTTPObject();\n http.onreadystatechange = function ()\n {\n if (http.readyState == 4)\n {\n var contentType = http.getResponseHeader(\"Content Type\");\n if (contentType == \"image/gif\" || contentType == \"image/jpeg\")\n return true;\n else\n return false;\n }\n }\n\n http.open(\"HEAD\",url,true);\n http.send(null);\n}\n\n\nfunction getHTTPObject() \n{\n if (window.XMLHttpRequest)\n {\n return new XMLHttpRequest();\n }\n else \n {\n if (window.ActiveXObject)\n {\n return new ActiveXObject(\"Microsoft.XMLHTTP\"); \n }\n }\n return false;\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8349/" ]
266,245
<p>I have a git repository with remote foo.</p> <p>foo is a web app, is contains some files and dirs directly in its root:</p> <pre><code>Rakefile app ... public script </code></pre> <p>My main git repository is a larger system which comprises this web app. I want to pull the commits from foo, but I need the files to reside inside the <code>web</code> dir. So they should become <code>web/app</code>, <code>web/public</code>, etc.</p> <p>I don't want to use foo as a submodule. I want to merge foo into the main repository and then get rid of it.</p>
[ { "answer_id": 12243677, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "/path/to/B dir-B $ git remote add -f Bproject /path/to/B\n$ git merge -s ours --no-commit Bproject/master\n$ git read-tree --prefix=dir-B/ -u Bproject/master\n$ git commit -m \"Merge B project as our subdirectory\"\n\n$ git pull -s subtree Bproject master\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
266,250
<p>I'm learning some PowerShell. Is it possible to see the source code for a built-in cmdlet like <a href="http://technet.microsoft.com/en-us/library/hh849800.aspx" rel="noreferrer">Get-ChildItem</a>?</p>
[ { "answer_id": 267600, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 5, "selected": false, "text": "Get-Command Get-ChildItem | Reflect-Cmdlet\n" }, { "answer_id": 20484505, "author": "ImpossibleSqui", "author_id": 3085094, "author_profile": "https://Stackoverflow.com/users/3085094", "pm_score": 4, "selected": false, "text": "$metadata = New-Object system.management.automation.commandmetadata (Get-Command Get-Process)\n[System.management.automation.proxycommand]::Create($MetaData) | out-file C:\\powershell\\get-process.ps1\n" }, { "answer_id": 32189485, "author": "Michael Kropat", "author_id": 27581, "author_profile": "https://Stackoverflow.com/users/27581", "pm_score": 4, "selected": false, "text": ".dll (Get-Command Get-ChildItem).DLL\n Get-ChildItem PS C:\\Windows\\system32> (Get-Command Get-StoragePool).DLL\n\nPS C:\\Windows\\system32> \n .dll & dotPeek64.exe (Get-Command Get-ChildItem).DLL\n" }, { "answer_id": 39058300, "author": "Zev Spitz", "author_id": 111794, "author_profile": "https://Stackoverflow.com/users/111794", "pm_score": 5, "selected": false, "text": "Get-ChildItem" }, { "answer_id": 66993858, "author": "user2173353", "author_id": 2173353, "author_profile": "https://Stackoverflow.com/users/2173353", "pm_score": 1, "selected": false, "text": "Install-Module Install-Module -Name PSnmap\n Definition Get-Command Invoke-PSnmap | Format-List\n DLL" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
266,255
<p>I try to instantiate an instance of <code>SPSite</code> on the farm server in a custom process (MyApp.exe) and I give it as parameter the whole URI (<a href="http://mysite:80/" rel="nofollow noreferrer">http://mysite:80/</a>). I also made sure that the account running <code>MyApp.exe</code> is <code>Site Collection Administrator</code>.</p> <p>However, I can't make an instance of <code>SPSite</code> whatever I am trying to do. It always throws a <code>FileNotFoundException</code>.</p> <p>Anyone got an idea?</p> <p>StackTrace:</p> <blockquote> <p>at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)<br> at Microsoft.SharePoint.SPSite..ctor(String requestUrl) at MyCompanyName.Service.HelperClass.GetItemStateInSharePoint(SharePointItem item) in C:\Workspaces\MyCompanyName\Development\Main\MyCompanyName.SharePoint\Service\HelperClass.cs:line 555</p> </blockquote> <p>Another side note... I have a Web Application + Site collection that I can access through the browser without any problem.</p>
[ { "answer_id": 266333, "author": "Lars Fastrup", "author_id": 27393, "author_profile": "https://Stackoverflow.com/users/27393", "pm_score": 5, "selected": true, "text": "System.IO.FileNotFoundException : The site http://server/sites/bah could not be found in the Web application SPWebApplication \nName=SharePoint - 80 Parent=SPWebService.\nat Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)\nat Microsoft.SharePoint.SPSite..ctor(String requestUrl)\n" }, { "answer_id": 266344, "author": "Abs", "author_id": 1245, "author_profile": "https://Stackoverflow.com/users/1245", "pm_score": 2, "selected": false, "text": "http://mysite http://machinename" }, { "answer_id": 383238, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 1, "selected": false, "text": "SPSite site = new SPSite(\"http://webapp/sites/site\")\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
266,308
<p>Is there a way to compile a .vbproj or .csproj project file directly, just like Visual Studio does?</p> <p>When you compile in Visual Studio, the "output" window shows the actual call to the compiler, which normally looks like:</p> <p>vbc.exe [bunch of options] [looooong list of .vb files]</p> <p>I would like to programatically call "something" that would take the .vbproj file and do whatever Visual Studio does to generate this long command line. I know i <em>could</em> parse the .vbproj myself and generate that command line, but I'd rather save myself all the reverse engineering and trial-and-error...</p> <p>Is there a tool to do this? I'd rather be able to do it in a machine without having Visual Studio installed. However, if there's a way to call Visual Studio with some parameters to do it, then that'll be fine too.</p> <p>I looked briefly at MSBuild, and it looks like it works from a .proj project file that i'd have to make especially, and that I'd need to update every time I add a file to the .vbproj file. (I did look <em>briefly</em> at it, so it's very likely I missed something important)</p> <p>Any help will be greatly appreciated</p>
[ { "answer_id": 266319, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "msbuild /property:Configuration=Release MyFile.vbproj\n" }, { "answer_id": 18820303, "author": "JWPlatt", "author_id": 2782594, "author_profile": "https://Stackoverflow.com/users/2782594", "pm_score": -1, "selected": false, "text": "<NoVBRuntimeReference>On</NoVBRuntimeReference>\n" }, { "answer_id": 46141807, "author": "Alexander Ivanov", "author_id": 2311055, "author_profile": "https://Stackoverflow.com/users/2311055", "pm_score": 1, "selected": false, "text": "msbuild wpfapp1.sln /p:BuildProjectReferences=true\n C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
266,321
<p>I'm interested to find which way of creating box shadows with css is most effective. But that I mean : ease of implementation, flexibility, and cross browser compatibility. </p>
[ { "answer_id": 50398229, "author": "allenski", "author_id": 9132582, "author_profile": "https://Stackoverflow.com/users/9132582", "pm_score": 0, "selected": false, "text": "box-shadow: 3px 3px 3px rgba(0,0,0,0.33);\n inset box-shadow: 3px 3px 3px rgba(0,0,0,0.33) inset;\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32582/" ]
266,326
<p>Am I safe in casting a C++ bool to a Windows API BOOL via this construct</p> <pre><code>bool mybool = true; BOOL apiboolean = mybool ? TRUE : FALSE; </code></pre> <p>I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears. </p> <p><em>Thanks to Dima for (gently) pointing out my carelessness in the way I'd originally phrased the question.</em> </p>
[ { "answer_id": 266338, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 4, "selected": true, "text": "\nbool b;\n...\nBOOL apiboolean = b ? TRUE : FALSE;\n" }, { "answer_id": 266468, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "bool b;\n...\nBOOL apiboolean = (BOOL) b;\n bool bb = (bool) apiboolean;\n" }, { "answer_id": 4853474, "author": "Martin Ba", "author_id": 321013, "author_profile": "https://Stackoverflow.com/users/321013", "pm_score": 1, "selected": false, "text": "bool b = true;\nBOOL apiboolean = b;\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
266,327
<p>A pattern that's started to show up a lot in one of the web apps I'm working are links that used to just be a regular a-tag link now need a popup box asking "are you sure?" before the link will go. (If the user hits cancel, nothing happens.)</p> <p>We've got a solution that works, but somehow we're a web app shop without a Javascript expert, so I'm left with this crawling feeling like there's a better way to get the job done.</p> <p>So, JS experts, what's the most standards-compliant, cross-browser way to get this done?</p> <p>(For the record, this is already a site that requires JS, so no need to have a "non-JS" version. But, it does need to work in any and all reasonably modern browsers.)</p> <p>(Also, for bonus points it would be nice if people with JS turned off didn't have the links work, rather than bypassing the confirm box.)</p>
[ { "answer_id": 266347, "author": "Electrons_Ahoy", "author_id": 19074, "author_profile": "https://Stackoverflow.com/users/19074", "pm_score": 3, "selected": false, "text": "<a href=\"#\" onClick=\"goThere(); return false;\">Go to new page</a>`\n\nfunction goThere() \n{ \n if( confirm(\"Are you sure?\") ) \n { \n window.location.href=\"newPage.aspx\"; \n } \n}\n" }, { "answer_id": 266349, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "<a href=\"http://...\" onclick=\"return confirm('are you sure?')\">text</a>\n" }, { "answer_id": 266430, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "// dangerous - warnings on potentially harmful actions\n// usage: add class=\"dangerous\" to <a>, <input> or <button>\n// Optionally add custom confirmation message to title attribute\n\nfunction dangerous_bind() {\n var lists= [\n document.getElementsByTagName('input'),\n document.getElementsByTagName('button'),\n document.getElementsByTagName('a')\n ];\n for (var listi= lists.length; listi-->0;) { var els= lists[listi];\n for (var eli= els.length; eli-->0;) { var el= els[eli];\n if (array_contains(el.className.split(' '), 'dangerous'))\n el.onclick= dangerous_click;\n }\n }\n}\n\nfunction array_contains(a, x) {\n for (var i= a.length; i-->0;)\n if (a[i]==x) return true;\n return false;\n}\n\nfunction dangerous_click() {\n return confirm(this.title || 'Are you sure?');\n}\n\ndangerous_bind();\n" }, { "answer_id": 266432, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 2, "selected": false, "text": "$(\"a\").click(function() {if(confirm('yadda yadda')) event.stopPropagation();});\n $(\".conf\").click(function() {if(confirm('yadda yadda')) event.stopPropagation();});\n" }, { "answer_id": 266435, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "var links = document.getElementsByTagName('A');\n\nfor (var i = 0; i < links.length; i++)\n{ \n links[i].onclick = function ()\n { \n return Confirm(\"Are you sure?\");\n }\n}\n" }, { "answer_id": 266443, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 5, "selected": true, "text": "var link = document.getElementById('confirmToFollow');\n\nlink.onclick = function () {\n return confirm(\"Are you sure?\");\n};\n <a href=\"#\" id=\"confirmToFollow\"...\n var link = document.getElementById('confirmToFollow');\n\nlink.onclick = function () {\n if( confirm(\"Are you sure?\") ) {\n window.location = \"http://www.stackoverflow.com/\";\n }\n return false;\n};\n var allLinks = document.getElementsByTagName('a');\nfor (var i=0; i < allLinks.length; i++) {\n allLinks[i].onclick = function () {\n return confirm(\"Are you sure?\");\n };\n}\n <a href=\"mypage.html\" onclick=\"...\n <a href=\"javascript: confirmLink() ...\n" }, { "answer_id": 266445, "author": "Esteban Küber", "author_id": 34813, "author_profile": "https://Stackoverflow.com/users/34813", "pm_score": 2, "selected": false, "text": "jQuery(document).ready(\n jQuery(\"a\").click(){\n //you'd place here your extra logic\n document.location.href = this.href;\n }\n);\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
266,332
<p>I have a <strong>MS Access</strong> form with a <strong>Datasheet</strong> subform.<br> Using code, I change the <strong>ColumnHidden</strong> property of various of its columns. But, when I close the form, I'm asked whether to save the table layout of the Datasheet's table.</p> <ul> <li>How can I stop the form from asking the user to same the table layout continually?</li> <li>Do I have no choice but to change the Datasheet to a regular subform?</li> </ul>
[ { "answer_id": 271263, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 0, "selected": false, "text": " DoCmd.Close acForm, Me.Name, acSaveNo\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15884/" ]
266,357
<p>I have been trying to tokenize a string using SPACE as delimiter but it doesn't work. Does any one have suggestion on why it doesn't work?</p> <p>Edit: tokenizing using:</p> <pre><code>strtok(string, " "); </code></pre> <p>The code is like the following</p> <pre><code>pch = strtok (str," "); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " "); } </code></pre>
[ { "answer_id": 266405, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 6, "selected": false, "text": "char s[256];\nstrcpy(s, \"one two three\");\nchar* token = strtok(s, \" \");\nwhile (token) {\n printf(\"token: %s\\n\", token);\n token = strtok(NULL, \" \");\n}\n strtok const char*" }, { "answer_id": 266407, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": false, "text": "strtok strtok char *p = strtok(str, \" \");\nwhile(p != NULL) {\n printf(\"%s\\n\", p);\n p = strtok(NULL, \" \");\n}\n NULL strtok" }, { "answer_id": 266425, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "#include <string.h>\n#include <stdio.h>\n\nint main()\n{\n char str[100], *s = str, *t = NULL;\n\n strcpy(str, \"a space delimited string\");\n while ((t = strtok(s, \" \")) != NULL) {\n s = NULL;\n printf(\":%s:\\n\", t);\n }\n return 0;\n}\n" }, { "answer_id": 266478, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 3, "selected": false, "text": "char strprint[256];\nchar text[256];\nstrcpy(text, \"My string to test\");\nwhile ( sscanf( text, \"%s %s\", strprint, text) > 0 ) {\n printf(\"token: %s\\n\", strprint);\n}\n" }, { "answer_id": 18580007, "author": "Fernando", "author_id": 2740941, "author_profile": "https://Stackoverflow.com/users/2740941", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <string.h>\n\nchar POSTREQ[255] = \"pwd=123456&apply=Apply&d1=88&d2=100&pwr=1&mpx=Internal&stmo=Stereo&proc=Processor&cmp=Compressor&ip1=192&ip2=168&ip3=10&ip4=131&gw1=192&gw2=168&gw3=10&gw4=192&pt=80&lic=&A=A\";\n\nint findchar(char *string, int Start, char C) {\n while((string[Start] != 0)) { Start++; if(string[Start] == C) return Start; }\n return -1;\n}\n\nint findcharn(char *string, int Times, char C) {\n int i = 0, pos = 0, fnd = 0;\n\n while(i < Times) {\n fnd = findchar(string, pos, C);\n if(fnd < 0) return -1;\n if(fnd > 0) pos = fnd;\n i++;\n }\n return fnd;\n}\n\nvoid mid(char *in, char *out, int start, int end) {\n int i = 0;\n int size = end - start;\n\n for(i = 0; i < size; i++){\n out[i] = in[start + i + 1];\n }\n out[size] = 0;\n}\n\nvoid getvalue(char *out, int index) {\n mid(POSTREQ, out, findcharn(POSTREQ, index, '='), (findcharn(POSTREQ, index, '&') - 1));\n}\n\nvoid main() {\n char n_pwd[7];\n char n_d1[7];\n\n getvalue(n_d1, 1);\n\n printf(\"Value: %s\\n\", n_d1);\n} \n" }, { "answer_id": 19721184, "author": "jitsceait", "author_id": 2671935, "author_profile": "https://Stackoverflow.com/users/2671935", "pm_score": -1, "selected": false, "text": "int not_in_delimiter(char c, char *delim){\n\n while(*delim != '\\0'){\n if(c == *delim) return 0;\n delim++;\n }\n return 1;\n}\n\nchar *token_separater(char *source, char *delimiter, char **last){\n\nchar *begin, *next_token;\nchar *sbegin;\n\n/*Get the start of the token */\nif(source)\n begin = source;\nelse\n begin = *last;\n\nsbegin = begin;\n\n/*Scan through the string till we find character in delimiter. */\nwhile(*begin != '\\0' && not_in_delimiter(*begin, delimiter)){\n begin++;\n}\n\n/* Check if we have reached at of the string */\nif(*begin == '\\0') {\n/* We dont need to come further, hence return NULL*/\n *last = NULL;\n return sbegin;\n}\n/* Scan the string till we find a character which is not in delimiter */\n next_token = begin;\n while(next_token != '\\0' && !not_in_delimiter(*next_token, delimiter)) {\n next_token++;\n }\n /* If we have not reached at the end of the string */\n if(*next_token != '\\0'){\n *last = next_token--;\n *next_token = '\\0';\n return sbegin;\n}\n}\n\n void main(){\n\n char string[10] = \"abcb_dccc\";\n char delim[10] = \"_\";\n char *token = NULL;\n char *last = \"\" ;\n token = token_separater(string, delim, &last);\n printf(\"%s\\n\", token);\n while(last){\n token = token_separater(NULL, delim, &last);\n printf(\"%s\\n\", token);\n }\n" }, { "answer_id": 35493995, "author": "fnisi", "author_id": 1884351, "author_profile": "https://Stackoverflow.com/users/1884351", "pm_score": 0, "selected": false, "text": "strtok() strtok() char *zstring_strtok(char *str, const char *delim) {\n static char *static_str=0; /* var to store last address */\n int index=0, strlength=0; /* integers for indexes */\n int found = 0; /* check if delim is found */\n\n /* delimiter cannot be NULL\n * if no more char left, return NULL as well\n */\n if (delim==0 || (str == 0 && static_str == 0))\n return 0;\n\n if (str == 0)\n str = static_str;\n\n /* get length of string */\n while(str[strlength])\n strlength++;\n\n /* find the first occurance of delim */\n for (index=0;index<strlength;index++)\n if (str[index]==delim[0]) {\n found=1;\n break;\n }\n\n /* if delim is not contained in str, return str */\n if (!found) {\n static_str = 0;\n return str;\n }\n\n /* check for consecutive delimiters\n *if first char is delim, return delim\n */\n if (str[0]==delim[0]) {\n static_str = (str + 1);\n return (char *)delim;\n }\n\n /* terminate the string\n * this assignmetn requires char[], so str has to\n * be char[] rather than *char\n */\n str[index] = '\\0';\n\n /* save the rest of the string */\n if ((str + index + 1)!=0)\n static_str = (str + index + 1);\n else\n static_str = 0;\n\n return str;\n}\n strtok() static *char" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/382480/" ]
266,364
<p>I've got a DB table where we store a lot of MD5 hashes (and yes I know that they aren't 100% unique...) where we have a lot of comparison queries against those strings. This table can become quite large with over 5M rows.</p> <p>My question is this: Is it wise to keep the data as hexadecimal strings or should I convert the hex to binary or decimals for better querying?</p>
[ { "answer_id": 266405, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 6, "selected": false, "text": "char s[256];\nstrcpy(s, \"one two three\");\nchar* token = strtok(s, \" \");\nwhile (token) {\n printf(\"token: %s\\n\", token);\n token = strtok(NULL, \" \");\n}\n strtok const char*" }, { "answer_id": 266407, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": false, "text": "strtok strtok char *p = strtok(str, \" \");\nwhile(p != NULL) {\n printf(\"%s\\n\", p);\n p = strtok(NULL, \" \");\n}\n NULL strtok" }, { "answer_id": 266425, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "#include <string.h>\n#include <stdio.h>\n\nint main()\n{\n char str[100], *s = str, *t = NULL;\n\n strcpy(str, \"a space delimited string\");\n while ((t = strtok(s, \" \")) != NULL) {\n s = NULL;\n printf(\":%s:\\n\", t);\n }\n return 0;\n}\n" }, { "answer_id": 266478, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 3, "selected": false, "text": "char strprint[256];\nchar text[256];\nstrcpy(text, \"My string to test\");\nwhile ( sscanf( text, \"%s %s\", strprint, text) > 0 ) {\n printf(\"token: %s\\n\", strprint);\n}\n" }, { "answer_id": 18580007, "author": "Fernando", "author_id": 2740941, "author_profile": "https://Stackoverflow.com/users/2740941", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <string.h>\n\nchar POSTREQ[255] = \"pwd=123456&apply=Apply&d1=88&d2=100&pwr=1&mpx=Internal&stmo=Stereo&proc=Processor&cmp=Compressor&ip1=192&ip2=168&ip3=10&ip4=131&gw1=192&gw2=168&gw3=10&gw4=192&pt=80&lic=&A=A\";\n\nint findchar(char *string, int Start, char C) {\n while((string[Start] != 0)) { Start++; if(string[Start] == C) return Start; }\n return -1;\n}\n\nint findcharn(char *string, int Times, char C) {\n int i = 0, pos = 0, fnd = 0;\n\n while(i < Times) {\n fnd = findchar(string, pos, C);\n if(fnd < 0) return -1;\n if(fnd > 0) pos = fnd;\n i++;\n }\n return fnd;\n}\n\nvoid mid(char *in, char *out, int start, int end) {\n int i = 0;\n int size = end - start;\n\n for(i = 0; i < size; i++){\n out[i] = in[start + i + 1];\n }\n out[size] = 0;\n}\n\nvoid getvalue(char *out, int index) {\n mid(POSTREQ, out, findcharn(POSTREQ, index, '='), (findcharn(POSTREQ, index, '&') - 1));\n}\n\nvoid main() {\n char n_pwd[7];\n char n_d1[7];\n\n getvalue(n_d1, 1);\n\n printf(\"Value: %s\\n\", n_d1);\n} \n" }, { "answer_id": 19721184, "author": "jitsceait", "author_id": 2671935, "author_profile": "https://Stackoverflow.com/users/2671935", "pm_score": -1, "selected": false, "text": "int not_in_delimiter(char c, char *delim){\n\n while(*delim != '\\0'){\n if(c == *delim) return 0;\n delim++;\n }\n return 1;\n}\n\nchar *token_separater(char *source, char *delimiter, char **last){\n\nchar *begin, *next_token;\nchar *sbegin;\n\n/*Get the start of the token */\nif(source)\n begin = source;\nelse\n begin = *last;\n\nsbegin = begin;\n\n/*Scan through the string till we find character in delimiter. */\nwhile(*begin != '\\0' && not_in_delimiter(*begin, delimiter)){\n begin++;\n}\n\n/* Check if we have reached at of the string */\nif(*begin == '\\0') {\n/* We dont need to come further, hence return NULL*/\n *last = NULL;\n return sbegin;\n}\n/* Scan the string till we find a character which is not in delimiter */\n next_token = begin;\n while(next_token != '\\0' && !not_in_delimiter(*next_token, delimiter)) {\n next_token++;\n }\n /* If we have not reached at the end of the string */\n if(*next_token != '\\0'){\n *last = next_token--;\n *next_token = '\\0';\n return sbegin;\n}\n}\n\n void main(){\n\n char string[10] = \"abcb_dccc\";\n char delim[10] = \"_\";\n char *token = NULL;\n char *last = \"\" ;\n token = token_separater(string, delim, &last);\n printf(\"%s\\n\", token);\n while(last){\n token = token_separater(NULL, delim, &last);\n printf(\"%s\\n\", token);\n }\n" }, { "answer_id": 35493995, "author": "fnisi", "author_id": 1884351, "author_profile": "https://Stackoverflow.com/users/1884351", "pm_score": 0, "selected": false, "text": "strtok() strtok() char *zstring_strtok(char *str, const char *delim) {\n static char *static_str=0; /* var to store last address */\n int index=0, strlength=0; /* integers for indexes */\n int found = 0; /* check if delim is found */\n\n /* delimiter cannot be NULL\n * if no more char left, return NULL as well\n */\n if (delim==0 || (str == 0 && static_str == 0))\n return 0;\n\n if (str == 0)\n str = static_str;\n\n /* get length of string */\n while(str[strlength])\n strlength++;\n\n /* find the first occurance of delim */\n for (index=0;index<strlength;index++)\n if (str[index]==delim[0]) {\n found=1;\n break;\n }\n\n /* if delim is not contained in str, return str */\n if (!found) {\n static_str = 0;\n return str;\n }\n\n /* check for consecutive delimiters\n *if first char is delim, return delim\n */\n if (str[0]==delim[0]) {\n static_str = (str + 1);\n return (char *)delim;\n }\n\n /* terminate the string\n * this assignmetn requires char[], so str has to\n * be char[] rather than *char\n */\n str[index] = '\\0';\n\n /* save the rest of the string */\n if ((str + index + 1)!=0)\n static_str = (str + index + 1);\n else\n static_str = 0;\n\n return str;\n}\n strtok() static *char" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
266,370
<p>I'd like to write some unit tests for some code that connects to a database, runs one or more queries, and then processes the results. (Without actually using a database)</p> <p>Another developer here wrote our own DataSource, Connection, Statement, PreparedStatement, and ResultSet implementation that will return the corresponding objects based on an xml configuration file. (we could use the bogus datasource and just run tests against the result sets it returns).</p> <p>Are we reinventing the wheel here? Does something like this exist already for unit testing? Are there other / better ways to test jdbc code?</p>
[ { "answer_id": 274752, "author": "P Arrayah", "author_id": 33459, "author_profile": "https://Stackoverflow.com/users/33459", "pm_score": 1, "selected": false, "text": "DBUtils.getMetadataFor(String tablename)" }, { "answer_id": 20901399, "author": "Paweł Prażak", "author_id": 539481, "author_profile": "https://Stackoverflow.com/users/539481", "pm_score": 2, "selected": false, "text": "public class JDBCLowLevelTest {\n\n private TestedClass tested;\n private Connection connection;\n private static Driver driver;\n\n @BeforeClass\n public static void setUpClass() throws Exception {\n // (Optional) Print DriverManager logs to system out\n DriverManager.setLogWriter(new PrintWriter((System.out)));\n\n // (Optional) Sometimes you need to get rid of a driver (e.g JDBC-ODBC Bridge)\n Driver configuredDriver = DriverManager.getDriver(\"jdbc:odbc:url\");\n\n System.out.println(\"De-registering the configured driver: \" + configuredDriver);\n DriverManager.deregisterDriver(configuredDriver);\n\n // Register the mocked driver\n driver = mock(Driver.class);\n System.out.println(\"Registering the mock driver: \" + driver);\n DriverManager.registerDriver(driver);\n }\n\n @AfterClass\n public static void tearDown() throws Exception {\n // Let's cleanup the global state\n System.out.println(\"De-registering the mock driver: \" + driver);\n DriverManager.deregisterDriver(driver);\n }\n\n @Before\n public void setUp() throws Exception {\n // given\n tested = new TestedClass();\n\n connection = mock(Connection.class);\n\n given(driver.acceptsURL(anyString())).willReturn(true);\n given(driver.connect(anyString(), Matchers.<Properties>any()))\n .willReturn(connection);\n\n given(connection.prepareCall(anyString())).willReturn(statement); \n }\n}\n @Test\npublic void shouldHandleDoubleException() throws Exception {\n // given\n SomeData someData = new SomeData();\n\n given(connection.prepareCall(anyString()))\n .willThrow(new SQLException(\"Prepare call\"));\n willThrow(new SQLException(\"Close exception\")).given(connection).close();\n\n // when\n SomeResponse response = testClass.someMethod(someData);\n\n // then\n assertThat(response, is(SOME_ERROR));\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
266,371
<p>In VIM in command line mode a "%" denotes the current file, "cword" denotes the current word under the cursor. I want to create a shortcut where I need the current line number. What is the symbol which denotes this?</p>
[ { "answer_id": 266386, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 4, "selected": false, "text": ":1,.s/foo/bar/g foo bar :!echo . % # :he cmdline-special" }, { "answer_id": 267827, "author": "Oli", "author_id": 22035, "author_profile": "https://Stackoverflow.com/users/22035", "pm_score": 1, "selected": false, "text": ":s/foo/bar/g\n" }, { "answer_id": 267870, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": ":.= \n" }, { "answer_id": 273678, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 5, "selected": true, "text": ":exe \"!echo \" . line(\".\")\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29653/" ]
266,372
<p>For a rigorous marker of the source database state, I'd like to capture the @@DBTS of an external database in a sproc. Yeah, I think I could issue </p> <blockquote> <code> <br/>USE ExternalDB <br/>GO <br/> <br/>SELECT @myVarbinary8 = @@DBTS <br/>GO <br/> <br/>USE OriginalDB <br/>GO </code> </blockquote> <p>but, even if I could, it seems ugly.</p> <p>For now, I've embedded a scalar-valued function in the source database to invoke the </p> <p>SET @Result = SELECT @@DBTS</p> <p>which worked fine until I forgot to ask the DBA to grant the appropriate rights for a new user, which crashed a process.</p> <p>Something akin to</p> <blockquote><code>SELECT ExternalServer.dbo.@@DBTS </code> <br/><br/>(I know that doesn't work).</blockquote> <p><br/> <br/>See &nbsp; <a href="http://msdn.microsoft.com/en-us/library/ms187366(SQL.90).aspx" rel="nofollow noreferrer">MSDN @@DBTS documentation</a></p> <blockquote>@@DBTS (Transact-SQL) <br/>Returns the value of the current timestamp data type for the current database. <br/>This timestamp is guaranteed to be unique in the database. </blockquote>
[ { "answer_id": 267396, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 0, "selected": false, "text": "\nDECLARE @sourceDbName nvarchar(128)\nSET     @sourceDbName = N'sbaportia1'\n\nDECLARE @strQuery nvarchar(max)\nDECLARE @parmDefn nvarchar(max)\nDECLARE @DbtsCapture varbinary(8)\nSET    @strQuery =\n    '\n           N' ' + N'USE' + N' ' + @sourceDbName + N' '\n         + N' ' + N'SELECT @dbtsCapture = min_active_rowversion()'\n    '\n\nSET @parmDefn =\n    N'\n         @dbName varchar(128),\n         @dbtsCapture varbinary(8) OUTPUT\n    '\n\nEXEC sp_executesql  @strQuery\n                    ,@parmDefn\n                    ,@dbName = 'autobahn'\n                    ,@dbtsCapture = @dbtsCapture OUTPUT\n\nSELECT @dbtsCapture\n" }, { "answer_id": 268213, "author": "Mladen Prajdic", "author_id": 31345, "author_profile": "https://Stackoverflow.com/users/31345", "pm_score": 1, "selected": false, "text": "CREATE PROCEDURE dbo.GetDatabaseTimestamp AS\n SET NOCOUNT ON;\n SELECT @@DBTS AS CurrentRowversion, MIN_ACTIVE_ROWVERSION() AS ActiveRowversion\n EXECUTE ExternalDB.dbo.GetDatabaseTimestamp;\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23422/" ]
266,373
<p>If something is making a single-thread program take, say, 10 times as long as it should, you could run a profiler on it. You could also just halt it with a "pause" button, and you'll see exactly what it's doing. </p> <p>Even if it's only 10% slower than it should be, if you halt it more times, before long you'll see it repeatedly doing the unnecessary thing. Usually the problem is a function call somewhere in the middle of the stack that isn't really needed. This doesn't measure the problem, but it sure does find it.</p> <p>Edit: The objections mostly assume that you only take 1 sample. If you're serious, take 10. Any line of code causing some percentage of wastage, like 40%, will appear on the stack on that fraction of samples, on average. Bottlenecks (in single-thread code) can't hide from it.</p> <p>EDIT: To show what I mean, many objections are of the form "there aren't enough samples, so what you see could be entirely spurious" - vague ideas about chance. But if something of <em>any recognizable description</em>, not just being in a routine or the routine being active, is in effect for 30% of the time, then the probability of seeing it on any given sample is 30%. </p> <p>Then suppose only 10 samples are taken. The number of times the problem will be seen in 10 samples follows a <a href="http://en.wikipedia.org/wiki/Binomial_distribution" rel="noreferrer">binomial distribution</a>, and the probability of seeing it 0 times is .028. The probability of seeing it 1 time is .121. For 2 times, the probability is .233, and for 3 times it is .267, after which it falls off. Since the probability of seeing it less than two times is .028 + .121 = .139, that means the probability of seeing it two or more times is 1 - .139 = .861. The general rule is if you see something you could fix on two or more samples, it is worth fixing. </p> <p>In this case, the chance of seeing it in 10 samples is 86%. If you're in the 14% who don't see it, just take more samples until you do. (If the number of samples is increased to 20, the chance of seeing it two or more times increases to more than 99%.) So it hasn't been precisely measured, but it has been precisely found, and it's important to understand that it could easily be something that a profiler could not actually find, such as something involving the state of the data, not the program counter.</p>
[ { "answer_id": 8290367, "author": "Crashworks", "author_id": 53543, "author_profile": "https://Stackoverflow.com/users/53543", "pm_score": 4, "selected": false, "text": "malloc stricmp" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23771/" ]
266,389
<p>What's the easiest programmatic way to restart a service on a remote Windows system? Language or method doesn't matter as long as it doesn't require human interaction.</p>
[ { "answer_id": 266423, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 8, "selected": true, "text": "sc.exe psservice.exe" }, { "answer_id": 266434, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 4, "selected": false, "text": " The option <server> has the form \"\\\\ServerName\"\n Further help on commands can be obtained by typing: \"sc [command]\"\n Commands:\n query-----------Queries the status for a service, or\n enumerates the status for types of services.\n queryex---------Queries the extended status for a service, or\n enumerates the status for types of services.\n start-----------Starts a service.\n pause-----------Sends a PAUSE control request to a service.\n interrogate-----Sends an INTERROGATE control request to a service.\n continue--------Sends a CONTINUE control request to a service.\n stop------------Sends a STOP request to a service.\n config----------Changes the configuration of a service (persistant).\n description-----Changes the description of a service.\n failure---------Changes the actions taken by a service upon failure.\n qc--------------Queries the configuration information for a service.\n qdescription----Queries the description for a service.\n qfailure--------Queries the actions taken by a service upon failure.\n delete----------Deletes a service (from the registry).\n create----------Creates a service. (adds it to the registry).\n control---------Sends a control to a service.\n sdshow----------Displays a service's security descriptor.\n sdset-----------Sets a service's security descriptor.\n GetDisplayName--Gets the DisplayName for a service.\n GetKeyName------Gets the ServiceKeyName for a service.\n EnumDepend------Enumerates Service Dependencies.\n\n The following commands don't require a service name:\n sc <server> <command> <option>\n boot------------(ok | bad) Indicates whether the last boot should\n be saved as the last-known-good boot configuration\n Lock------------Locks the Service Database\n QueryLock-------Queries the LockStatus for the SCManager Database\n" }, { "answer_id": 266463, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "function ServiceStart(sMachine, sService : string) : boolean; //start service, return TRUE if successful\nvar schm, schs : SC_Handle;\n ss : TServiceStatus;\n psTemp : PChar;\n dwChkP : DWord;\nbegin\n ss.dwCurrentState := 0;\n schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT); //connect to the service control manager\n\n if(schm > 0)then begin // if successful...\n schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS); // open service handle, start and query status\n if(schs > 0)then begin // if successful...\n psTemp := nil;\n if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then\n while(SERVICE_RUNNING <> ss.dwCurrentState)do begin\n dwChkP := ss.dwCheckPoint; //dwCheckPoint contains a value incremented periodically to report progress of a long operation. Store it.\n Sleep(ss.dwWaitHint); //Sleep for recommended time before checking status again\n if(not QueryServiceStatus(schs,ss))then\n break; //couldn't check status\n if(ss.dwCheckPoint < dwChkP)then\n Break; //if QueryServiceStatus didn't work for some reason, avoid infinite loop\n end; //while not running\n CloseServiceHandle(schs);\n end; //if able to get service handle\n CloseServiceHandle(schm);\n end; //if able to get svc mgr handle\n Result := SERVICE_RUNNING = ss.dwCurrentState; //if we were able to start it, return true\nend;\n\nfunction ServiceStop(sMachine, sService : string) : boolean; //stop service, return TRUE if successful\nvar schm, schs : SC_Handle;\n ss : TServiceStatus;\n dwChkP : DWord;\nbegin\n schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);\n\n if(schm > 0)then begin\n schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);\n if(schs > 0)then begin\n if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then\n while(SERVICE_STOPPED <> ss.dwCurrentState) do begin\n dwChkP := ss.dwCheckPoint;\n Sleep(ss.dwWaitHint);\n if(not QueryServiceStatus(schs,ss))then\n Break;\n\n if(ss.dwCheckPoint < dwChkP)then\n Break;\n end; //while\n CloseServiceHandle(schs);\n end; //if able to get svc handle\n CloseServiceHandle(schm);\n end; //if able to get svc mgr handle\n Result := SERVICE_STOPPED = ss.dwCurrentState;\nend;\n" }, { "answer_id": 266471, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 2, "selected": false, "text": "net stop \"DNS Client\"\nnet start \"DNS client\"\n" }, { "answer_id": 30847542, "author": "ambassallo", "author_id": 2616446, "author_profile": "https://Stackoverflow.com/users/2616446", "pm_score": 2, "selected": false, "text": "taskkill /F /IM processname.exe\ntimeout 20\nsc start servicename\n" }, { "answer_id": 32522511, "author": "ShaneC", "author_id": 2191599, "author_profile": "https://Stackoverflow.com/users/2191599", "pm_score": 2, "selected": false, "text": "$session = New-PSsession -Computername \"YourServerName\"\nInvoke-Command -Session $Session -ScriptBlock {Restart-Service \"YourServiceName\"}\nRemove-PSSession $Session\n" }, { "answer_id": 38340439, "author": "Medos", "author_id": 675440, "author_profile": "https://Stackoverflow.com/users/675440", "pm_score": 0, "selected": false, "text": "Restart-Service \"servicename\"\n" }, { "answer_id": 59226500, "author": "Kishore Kumar", "author_id": 823369, "author_profile": "https://Stackoverflow.com/users/823369", "pm_score": 0, "selected": false, "text": "runas /noprofile /user:DOMAIN\\USERNAME cmd\n sc \\\\SERVERNAME query Tomcat8\nsc \\\\SERVERNAME stop Tomcat8\nsc \\\\SERVERNAME start Tomcat8\n" }, { "answer_id": 64269737, "author": "David Rogers", "author_id": 2912011, "author_profile": "https://Stackoverflow.com/users/2912011", "pm_score": 0, "selected": false, "text": "#Configuration\n$servername = \"ABC\",\n$serviceAccountUsername = \"XYZ\",\n$serviceAccountPassword = \"XXX\"\n\n#Establish connection\ntry {\n if (-not ([System.IO.Directory]::Exists('\\\\' + $servername))) {\n net use \\\\$servername /user:$serviceAccountUsername $serviceAccountPassword\n }\n}\ncatch {\n #May already exists, if so just continue\n Write-Output $_.Exception.Message\n}\n\n#Restart Service\nsc.exe \\\\$servername stop \"ServiceNameHere\"\nsc.exe \\\\$servername start \"ServiceNameHere\"\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
266,395
<p>I have a git repository which tracks an svn repository. I cloned it using <code>--stdlayout</code>.</p> <p>I created a new local branch via <code>git checkout -b foobar</code></p> <p>Now I want this branch to end up in <code>…/branches/foobar</code> in the svn repository.</p> <p>How do I go about that?</p> <p>(snipped lots of investigative text. see question history if you care)</p>
[ { "answer_id": 266561, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 7, "selected": true, "text": "git svn branch" }, { "answer_id": 1911069, "author": "Jesper Rønn-Jensen", "author_id": 109305, "author_profile": "https://Stackoverflow.com/users/109305", "pm_score": 8, "selected": false, "text": "git svn branch -n git svn branch -n -m \"Branch for authentication bug\" auth_bug\n -n git checkout -b local/auth_bug auth_bug\n auth_bug auth_bug dcommit --dry-run -n git svn dcommit -n\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
266,409
<p>I've got a WAR file that I need to add two files to. Currently, I'm doing this:</p> <pre><code>File war = new File(DIRECTORY, "server.war"); JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war))); //Add file 1 File file = new File(DIRECTORY, "file1.jar"); InputStream is = new BufferedInputStream(new FileInputStream(file)); ZipEntry e = new ZipEntry("file1.jar"); zos.putNextEntry(e); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf, 0, buf.length)) != -1) { zos.write(buf, 0, len); } is.close(); zos.closeEntry(); //repeat for file 2 zos.close(); </code></pre> <p>The result is that the previous contents get clobbered: the WAR has only the 2 files I just added in it. Is there some sort of append mode that I'm not using or what?</p>
[ { "answer_id": 266469, "author": "hark", "author_id": 34826, "author_profile": "https://Stackoverflow.com/users/34826", "pm_score": 3, "selected": false, "text": "JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war, True)));\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
266,417
<p>We are in a Windows environment and looking to automate this process for non-company machines. If a vendor comes on site, we'd like to be able to have him/her hit a website that can perform a quick scan of the workstation to determine if they have the proper MS KB patches and if their virus scanner dats are up to date.</p> <p>I can scan for the KB updates relatively easy, what I'm having a hard time finding is a way to check the virus dat status and since there are so many different engines out there, it seemed to make sense to use the (built into XP at least) proprietary MS security center stuff.</p> <p>Eventually we'd like to have our routers redirect non-company machines to a website that will force validation, but until that point it will be a manual process.</p> <p>Any thoughts?</p>
[ { "answer_id": 392605, "author": "Hernán", "author_id": 48026, "author_profile": "https://Stackoverflow.com/users/48026", "pm_score": 3, "selected": true, "text": " Set oWMI = GetObject\n(\"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\SecurityCenter\") \n Set colItems = oWMI.ExecQuery(\"Select * from AntiVirusProduct\") \n\n For Each objAntiVirusProduct In colItems \n msg = msg & \"companyName: \" & objAntiVirusProduct.companyName & vbCrLf \n msg = msg & \"displayName: \" & objAntiVirusProduct.displayName & vbCrLf \n msg = msg & \"instanceGuid: \" & objAntiVirusProduct.instanceGuid & vbCrLf \n msg = msg & \"onAccessScanningEnabled: \"\n & objAntiVirusProduct.onAccessScanningEnabled & vbCrLf \n msg = msg & \"productUptoDate: \" & objAntiVirusProduct.productUptoDate & vbCrLf \n msg = msg & \"versionNumber: \" & objAntiVirusProduct.versionNumber & vbCrLf \n msg = msg & vbCrLf \n\n Next\n\n WScript.Echo msg\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11130/" ]
266,431
<p>I used to use the standard mysql_connect(), mysql_query(), etc statements for doing MySQL stuff from PHP. Lately I've been switching over to using the wonderful MDB2 class. Along with it, I'm using prepared statements, so I don't have to worry about escaping my input and SQL injection attacks.</p> <p>However, there's one problem I'm running into. I have a table with a few VARCHAR columns, that are specified as not-null (that is, do not allow NULL values). Using the old MySQL PHP commands, I could do things like this without any problem:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO mytable SET somevarchar = ''; </code></pre> <p>Now, however, if I have a query like:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO mytable SET somevarchar = ?; </code></pre> <p>And then in PHP I have:</p> <pre><code>$value = ""; $prepared = $db-&gt;prepare($query, array('text')); $result = $prepared-&gt;execute($value); </code></pre> <p>This will throw the error "<code>null value violates not-null constraint</code>"</p> <p>As a temporary workaround, I check if <code>$value</code> is empty, and change it to <code>" "</code> (a single space), but that's a horrible hack and might cause other issues.</p> <p>How am I supposed to insert empty strings with prepared statements, without it trying to instead insert a NULL?</p> <p><strong>EDIT:</strong> It's too big of a project to go through my entire codebase, find everywhere that uses an empty string "" and change it to use NULL instead. What I need to know is why standard MySQL queries treat "" and NULL as two separate things (as I think is correct), but prepared statements converts "" into NULL. </p> <p>Note that "" and NULL are <strong>not</strong> the same thing. For Example, <code>SELECT NULL = "";</code> returns <code>NULL</code> instead of <code>1</code> as you'd expect. </p>
[ { "answer_id": 266464, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "\"\"" }, { "answer_id": 266512, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": -1, "selected": false, "text": "$query = \"INSERT INTO mytable SET somevarchar = ?\";\n$value = \"\";\n$prepared = $db->prepare($query);\n$prepared->bind_param(\"s\", $value);\n$result = $prepared->execute();\n" }, { "answer_id": 266518, "author": "hark", "author_id": 34826, "author_profile": "https://Stackoverflow.com/users/34826", "pm_score": 5, "selected": true, "text": "mysql> CREATE TABLE tbl( row CHAR(128) NOT NULL );\nQuery OK, 0 rows affected (0.05 sec)\n\nmysql> INSERT INTO tbl VALUES( 'not empty' ), ( '' );\nQuery OK, 2 rows affected (0.02 sec)\nRecords: 2 Duplicates: 0 Warnings: 0\n\nmysql> SELECT row, row IS NULL FROM tbl;\n+-----------+-------------+\n| row | row IS NULL |\n+-----------+-------------+\n| not empty | 0 | \n| | 0 | \n+-----------+-------------+\n2 rows in set (0.00 sec)\n\nmysql> INSERT INTO tbl VALUES( NULL );\nERROR 1048 (23000): Column 'row' cannot be null\n SET @EMPTY_STRING = \"\";\nUPDATE tbl SET row=@EMPTY_STRING;\n" }, { "answer_id": 2294611, "author": "ahhon", "author_id": 276755, "author_profile": "https://Stackoverflow.com/users/276755", "pm_score": 1, "selected": false, "text": "$options = array(\n 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL\n);\n$res= & MDB2::connect(\"mysql://user:password@server/dbase\", $options);\n" }, { "answer_id": 6193501, "author": "Lisa Simpson", "author_id": 673748, "author_profile": "https://Stackoverflow.com/users/673748", "pm_score": 1, "selected": false, "text": "SELECT * from table where mything IS NULL" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
266,433
<p>So... I used to think that when you accessed a file but specified the name without a path (CAISLog.csv in my case) that .NET would expect the file to reside at the same path as the running .exe. </p> <p>This works when I'm stepping through a solution (C# .NET2.* VS2K5) but when I run the app in normal mode (Started by a Websphere MQ Trigger monitor &amp; running in the background as a network service) instead of accessing the file at the path where the .exe is it's being looked for at C:\WINDOWS\system32. If it matters The parent task's .exe is in almost the same folder structure/path as my app</p> <p>I get a matching error: "<em>System.UnauthorizedAccessException: Access to the path 'C:\WINDOWS\system32\CAISLog.csv' is denied.</em>"</p> <p>My workaround is to just fully qualify the location of my file. What I want to understand, however is <strong>"What is the .NET rule that governs how a path is resolved when only the file name is specified during IO?"</strong> I feel I'm missing some basic concept and it's bugging me bad.</p> <p>edit - I'm not sure it's a.NET rule per se but Schmuli seems to be explaining the concept a little clearer. I will definitely try Rob Prouse's suggestions in the future so +1 on that too.</p> <p>If anyone has some re-wording suggestions that emphasize I don't <em>really</em> care about finding the path to my .exe - rather just didn't understand what was going on with relative path resolution (and I may still have my terminlogy screwed up)...</p>
[ { "answer_id": 266473, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "Assembly ass = Assembly.GetEntryAssembly();\nstring dir = Path.GetDirectoryName(ass.Location);\nstring filename = Path.Combine( dir, \"CAISLog.csv\" );\n Assembly ass = Assembly.GetAssembly( typeof( AClassInYourAssembly ) );\n" }, { "answer_id": 266871, "author": "Schmuli", "author_id": 8363, "author_profile": "https://Stackoverflow.com/users/8363", "pm_score": 5, "selected": true, "text": "Environment.CurrentDirectory OpenFileDialog SaveFileDialog System.IO Environment.CurrentDirectory Assembly.GetEntryAssembly() Assembly.GetExecutingAssembly() Location CodeBase `System.IO.Directory.SetCurrentDirectory( System.AppDomain.CurrentDomain.BaseDirectory );`\n OnStart" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30901/" ]
266,448
<p>How would I format the standard RSS pubDate string as something closer to ASP.NET's DateTime?</p> <p>So, from this:</p> <p>Wed, 29 Oct 2008 14:14:48 +0000</p> <p>to this:</p> <p>10/29/2008 2:14 PM</p>
[ { "answer_id": 266470, "author": "AaronS", "author_id": 26932, "author_profile": "https://Stackoverflow.com/users/26932", "pm_score": 3, "selected": true, "text": "string orig = \"Wed, 29 Oct 2008 14:14:48 +0000\";\nstring newstring = String.Format(\"{0:MM/dd/yyyy hh:mm tt}\", DateTime.Parse(orig.Remove(orig.IndexOf(\" +\"))));\n" }, { "answer_id": 266508, "author": "Moose", "author_id": 19032, "author_profile": "https://Stackoverflow.com/users/19032", "pm_score": 2, "selected": false, "text": "string d = \"Wed, 29 Oct 2008 14:14:48 +0000\";\n\nstring RFC822 = \"ddd, dd MMM yyyy HH:mm:ss zzz\";\nDateTime dt = DateTime.ParseExact( d, RFC822,\n DateTimeFormatInfo.InvariantInfo,\n DateTimeStyles.None);\n" }, { "answer_id": 285550, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 4, "selected": false, "text": "/// <summary>\n/// Provides methods for converting <see cref=\"DateTime\"/> structures \n/// to and from the equivalent <a href=\"http://www.w3.org/Protocols/rfc822/#z28\">RFC 822</a> \n/// string representation.\n/// </summary>\npublic class Rfc822DateTime\n{\n //============================================================\n // Private members\n //============================================================\n #region Private Members\n /// <summary>\n /// Private member to hold array of formats that RFC 822 date-time representations conform to.\n /// </summary>\n private static string[] formats = new string[0];\n /// <summary>\n /// Private member to hold the DateTime format string for representing a DateTime in the RFC 822 format.\n /// </summary>\n private const string format = \"ddd, dd MMM yyyy HH:mm:ss K\";\n #endregion\n\n //============================================================\n // Public Properties\n //============================================================\n #region Rfc822DateTimeFormat\n /// <summary>\n /// Gets the custom format specifier that may be used to represent a <see cref=\"DateTime\"/> in the RFC 822 format.\n /// </summary>\n /// <value>A <i>DateTime format string</i> that may be used to represent a <see cref=\"DateTime\"/> in the RFC 822 format.</value>\n /// <remarks>\n /// <para>\n /// This method returns a string representation of a <see cref=\"DateTime\"/> that utilizes the time zone \n /// offset (local differential) to represent the offset from Greenwich mean time in hours and minutes. \n /// The <see cref=\"Rfc822DateTimeFormat\"/> is a valid date-time format string for use \n /// in the <see cref=\"DateTime.ToString(String, IFormatProvider)\"/> method.\n /// </para>\n /// <para>\n /// The <a href=\"http://www.w3.org/Protocols/rfc822/#z28\">RFC 822</a> Date and Time specification \n /// specifies that the year will be represented as a two-digit value, but the \n /// <a href=\"http://www.rssboard.org/rss-profile#data-types-datetime\">RSS Profile</a> recommends that \n /// all date-time values should use a four-digit year. The <see cref=\"Rfc822DateTime\"/> class \n /// follows the RSS Profile recommendation when converting a <see cref=\"DateTime\"/> to the equivalent \n /// RFC 822 string representation.\n /// </para>\n /// </remarks>\n public static string Rfc822DateTimeFormat\n {\n get\n {\n return format;\n }\n }\n #endregion\n\n #region Rfc822DateTimePatterns\n /// <summary>\n /// Gets an array of the expected formats for RFC 822 date-time string representations.\n /// </summary>\n /// <value>\n /// An array of the expected formats for RFC 822 date-time string representations \n /// that may used in the <see cref=\"DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)\"/> method.\n /// </value>\n /// <remarks>\n /// The array of the expected formats that is returned assumes that the RFC 822 time zone \n /// is represented as or converted to a local differential representation.\n /// </remarks>\n /// <seealso cref=\"ConvertZoneToLocalDifferential(String)\"/>\n public static string[] Rfc822DateTimePatterns\n {\n get\n {\n if (formats.Length > 0)\n {\n return formats;\n }\n else\n {\n formats = new string[35];\n\n // two-digit day, four-digit year patterns\n formats[0] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fffffff zzzz\";\n formats[1] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ffffff zzzz\";\n formats[2] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fffff zzzz\";\n formats[3] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ffff zzzz\";\n formats[4] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fff zzzz\";\n formats[5] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ff zzzz\";\n formats[6] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'f zzzz\";\n formats[7] = \"ddd',' dd MMM yyyy HH':'mm':'ss zzzz\";\n\n // two-digit day, two-digit year patterns\n formats[8] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fffffff zzzz\";\n formats[9] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ffffff zzzz\";\n formats[10] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fffff zzzz\";\n formats[11] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ffff zzzz\";\n formats[12] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fff zzzz\";\n formats[13] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ff zzzz\";\n formats[14] = \"ddd',' dd MMM yy HH':'mm':'ss'.'f zzzz\";\n formats[15] = \"ddd',' dd MMM yy HH':'mm':'ss zzzz\";\n\n // one-digit day, four-digit year patterns\n formats[16] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fffffff zzzz\";\n formats[17] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ffffff zzzz\";\n formats[18] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fffff zzzz\";\n formats[19] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ffff zzzz\";\n formats[20] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fff zzzz\";\n formats[21] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ff zzzz\";\n formats[22] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'f zzzz\";\n formats[23] = \"ddd',' d MMM yyyy HH':'mm':'ss zzzz\";\n\n // two-digit day, two-digit year patterns\n formats[24] = \"ddd',' d MMM yy HH':'mm':'ss'.'fffffff zzzz\";\n formats[25] = \"ddd',' d MMM yy HH':'mm':'ss'.'ffffff zzzz\";\n formats[26] = \"ddd',' d MMM yy HH':'mm':'ss'.'fffff zzzz\";\n formats[27] = \"ddd',' d MMM yy HH':'mm':'ss'.'ffff zzzz\";\n formats[28] = \"ddd',' d MMM yy HH':'mm':'ss'.'fff zzzz\";\n formats[29] = \"ddd',' d MMM yy HH':'mm':'ss'.'ff zzzz\";\n formats[30] = \"ddd',' d MMM yy HH':'mm':'ss'.'f zzzz\";\n formats[31] = \"ddd',' d MMM yy HH':'mm':'ss zzzz\";\n\n // Fall back patterns\n formats[32] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK\"; // RoundtripDateTimePattern\n formats[33] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;\n formats[34] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;\n\n return formats;\n }\n }\n }\n #endregion\n\n //============================================================\n // Public Methods\n //============================================================\n #region Parse(string s)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <returns>\n /// A <see cref=\"DateTime\"/> equivalent to the date and time contained in <paramref name=\"s\"/>, \n /// expressed as <i>Coordinated Universal Time (UTC)</i>.\n /// </returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object.\n /// </remarks>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is an empty string.</exception>\n /// <exception cref=\"FormatException\"><paramref name=\"s\"/> does not contain a valid RFC 822 string representation of a date and time.</exception>\n public static DateTime Parse(string s)\n {\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n Guard.ArgumentNotNullOrEmptyString(s, \"s\");\n\n DateTime result;\n if (Rfc822DateTime.TryParse(s, out result))\n {\n return result;\n }\n else\n {\n throw new FormatException(String.Format(null, \"{0} is not a valid RFC 822 string representation of a date and time.\", s));\n }\n }\n #endregion\n\n #region ConvertZoneToLocalDifferential(string s)\n /// <summary>\n /// Converts the time zone component of an RFC 822 date and time string representation to its local differential (time zone offset).\n /// </summary>\n /// <param name=\"s\">A string containing an RFC 822 date and time to convert.</param>\n /// <returns>A date and time string that uses local differential to describe the time zone equivalent to the date and time contained in <paramref name=\"s\"/>.</returns>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is an empty string.</exception>\n public static string ConvertZoneToLocalDifferential(string s)\n {\n string zoneRepresentedAsLocalDifferential = String.Empty;\n\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n Guard.ArgumentNotNullOrEmptyString(s, \"s\");\n\n if(s.EndsWith(\" UT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" UT\") + 1) ), \"+00:00\");\n }\n else if (s.EndsWith(\" GMT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" GMT\") + 1 ) ), \"+00:00\");\n }\n else if (s.EndsWith(\" EST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" EST\") + 1)), \"-05:00\");\n }\n else if (s.EndsWith(\" EDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" EDT\") + 1)), \"-04:00\");\n }\n else if (s.EndsWith(\" CST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" CST\") + 1)), \"-06:00\");\n }\n else if (s.EndsWith(\" CDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" CDT\") + 1)), \"-05:00\");\n }\n else if (s.EndsWith(\" MST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" MST\") + 1)), \"-07:00\");\n }\n else if (s.EndsWith(\" MDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" MDT\") + 1)), \"-06:00\");\n }\n else if (s.EndsWith(\" PST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" PST\") + 1)), \"-08:00\");\n }\n else if (s.EndsWith(\" PDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" PDT\") + 1)), \"-07:00\");\n }\n else if (s.EndsWith(\" Z\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" Z\") + 1)), \"+00:00\");\n }\n else if (s.EndsWith(\" A\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" A\") + 1)), \"-01:00\");\n }\n else if (s.EndsWith(\" M\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" M\") + 1)), \"-12:00\");\n }\n else if (s.EndsWith(\" N\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" N\") + 1)), \"+01:00\");\n }\n else if (s.EndsWith(\" Y\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" Y\") + 1)), \"+12:00\");\n }\n else\n {\n zoneRepresentedAsLocalDifferential = s;\n }\n\n return zoneRepresentedAsLocalDifferential;\n }\n #endregion\n\n #region ToString(DateTime utcDateTime)\n /// <summary>\n /// Converts the value of the specified <see cref=\"DateTime\"/> object to its equivalent string representation.\n /// </summary>\n /// <param name=\"utcDateTime\">The Coordinated Universal Time (UTC) <see cref=\"DateTime\"/> to convert.</param>\n /// <returns>A RFC 822 string representation of the value of the <paramref name=\"utcDateTime\"/>.</returns>\n /// <exception cref=\"ArgumentException\">The specified <paramref name=\"utcDateTime\"/> object does not represent a <see cref=\"DateTimeKind.Utc\">Coordinated Universal Time (UTC)</see> value.</exception>\n public static string ToString(DateTime utcDateTime)\n {\n if (utcDateTime.Kind != DateTimeKind.Utc)\n {\n throw new ArgumentException(\"utcDateTime\");\n }\n\n return utcDateTime.ToString(Rfc822DateTime.Rfc822DateTimeFormat, DateTimeFormatInfo.InvariantInfo);\n }\n #endregion\n\n #region TryParse(string s, out DateTime result)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <param name=\"result\">\n /// When this method returns, contains the <see cref=\"DateTime\"/> value equivalent to the date and time \n /// contained in <paramref name=\"s\"/>, expressed as <i>Coordinated Universal Time (UTC)</i>, \n /// if the conversion succeeded, or <see cref=\"DateTime.MinValue\">MinValue</see> if the conversion failed. \n /// The conversion fails if the s parameter is a <b>null</b> reference (Nothing in Visual Basic), \n /// or does not contain a valid string representation of a date and time. \n /// This parameter is passed uninitialized.\n /// </param>\n /// <returns><b>true</b> if the <paramref name=\"s\"/> parameter was converted successfully; otherwise, <b>false</b>.</returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object. \n /// </remarks>\n public static bool TryParse(string s, out DateTime result)\n {\n //------------------------------------------------------------\n // Attempt to convert string representation\n //------------------------------------------------------------\n bool wasConverted = false;\n result = DateTime.MinValue;\n\n if (!String.IsNullOrEmpty(s))\n {\n DateTime parseResult;\n if (DateTime.TryParseExact(Rfc822DateTime.ConvertZoneToLocalDifferential(s), Rfc822DateTime.Rfc822DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))\n {\n result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);\n wasConverted = true;\n }\n }\n\n return wasConverted;\n }\n #endregion \n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4241/" ]
266,457
<p>I have a linq query and I am trying to put that in to a serializable object for a distributed caching (Velocity) but its failing due to a LINQ-to-SQL lazy list</p> <p>like so</p> <pre><code> return from b in _datacontext.MemberBlogs let cats = GetBlogCategories(b.MemberBlogID) select new MemberBlogs { MemberBlogID = b.MemberBlogID, MemberID = b.MemberID, BlogTitle = b.BlogTitle, BlogURL = b.BlogURL, BlogUsername = b.BlogUsername, BlogPassword = b.BlogPassword, Categories = new LazyList&lt;MemberBlogCategories&gt;(cats) }; </code></pre> <p>LazyList is the same class Rob Conery uses in his MVC storefront...</p> <p>all three classes are marked serializable (MemberBlogs,MemberBlogCategories,LazyList... any ideas?</p>
[ { "answer_id": 266541, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 4, "selected": true, "text": "(from x select new MemberBlogs).ToList()\n" }, { "answer_id": 266547, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 2, "selected": false, "text": "[OnSerializing]\nprivate void ExecuteLinqQuery(StreamingContext context)\n{\n if (!SomethingThatIndicatesThisLinqQueryHasNotBeenExecuted)\n LinqVariable.ToList()\n}\n" }, { "answer_id": 19234021, "author": "Jonathan", "author_id": 62686, "author_profile": "https://Stackoverflow.com/users/62686", "pm_score": 0, "selected": false, "text": " public class LazyList<T> : IList<T>, ISerializable\n{\n\n public LazyList()\n {\n this.query = new List<T>().AsQueryable();\n }\n\n public LazyList(SerializationInfo info, StreamingContext context)\n {\n try {\n this.inner = (List<T>)info.GetValue(\"InnerList\", typeof(List<T>));\n }\n catch (Exception ex)\n {\n this.inner = null;\n }\n }\n\n public void GetObjectData(SerializationInfo info, StreamingContext context)\n {\n if (this.inner != null)\n info.AddValue(\"InnerList\", this.inner.ToList());\n }\n\n public LazyList(IQueryable<T> query)\n {\n this.query = query;\n }\n\n public LazyList(List<T> l)\n {\n inner = l;\n }\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22093/" ]
266,486
<p>I am trying to write out a png file from a java.awt.image.BufferedImage. Everything works fine but the resulting png is a 32-bit file.</p> <p>Is there a way to make the png file be 8-bit? The image is grayscale, but I do need transparency as this is an overlay image. I am using java 6, and I would prefer to return an OutputStream so that I can have the calling class deal with writing out the file to disk/db.</p> <p>Here is the relevant portion of the code:</p> <pre><code> public static ByteArrayOutputStream createImage(InputStream originalStream) throws IOException { ByteArrayOutputStream oStream = null; java.awt.Image newImg = javax.imageio.ImageIO.read(originalStream); int imgWidth = newImg.getWidth(null); int imgHeight = newImg.getHeight(null); java.awt.image.BufferedImage bim = new java.awt.image.BufferedImage(imgWidth, imgHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB); Color bckgrndColor = new Color(0x80, 0x80, 0x80); Graphics2D gf = (Graphics2D)bim.getGraphics(); // set transparency for fill image gf.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f)); gf.setColor(bckgrndColor); gf.fillRect(0, 0, imgWidth, imgHeight); oStream = new ByteArrayOutputStream(); javax.imageio.ImageIO.write(bim, "png", oStream); oStream.close(); return oStream; } </code></pre>
[ { "answer_id": 267316, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "public class ImageUtil\n{\n public static int ALPHA_BIT_MASK = 0xFF000000;\n\n public static BufferedImage imageToBufferedImage(Image image, int width, int height)\n {\n return imageToBufferedImage(image, width, height, BufferedImage.TYPE_INT_ARGB);\n }\n\n public static BufferedImage imageToBufferedImage(Image image, int width, int height, int type)\n {\n BufferedImage dest = new BufferedImage(width, height, type);\n Graphics2D g2 = dest.createGraphics();\n g2.drawImage(image, 0, 0, null);\n g2.dispose();\n return dest;\n }\n\n public static BufferedImage convertRGBAToIndexed(BufferedImage srcImage)\n {\n // Create a non-transparent palletized image\n Image flattenedImage = transformTransparencyToMagenta(srcImage);\n BufferedImage flatImage = imageToBufferedImage(flattenedImage,\n srcImage.getWidth(), srcImage.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);\n BufferedImage destImage = makeColorTransparent(flatImage, 0, 0);\n return destImage;\n }\n\n private static Image transformTransparencyToMagenta(BufferedImage image)\n {\n ImageFilter filter = new RGBImageFilter()\n {\n @Override\n public final int filterRGB(int x, int y, int rgb)\n {\n int pixelValue = 0;\n int opacity = (rgb & ALPHA_BIT_MASK) >>> 24;\n if (opacity < 128)\n {\n // Quite transparent: replace color with transparent magenta\n // (traditional color for binary transparency)\n pixelValue = 0x00FF00FF;\n }\n else\n {\n // Quite opaque: get pure color\n pixelValue = (rgb & 0xFFFFFF) | ALPHA_BIT_MASK;\n }\n return pixelValue;\n }\n };\n\n ImageProducer ip = new FilteredImageSource(image.getSource(), filter);\n return Toolkit.getDefaultToolkit().createImage(ip);\n }\n\n public static BufferedImage makeColorTransparent(BufferedImage image, int x, int y)\n {\n ColorModel cm = image.getColorModel();\n if (!(cm instanceof IndexColorModel))\n return image; // No transparency added as we don't have an indexed image\n\n IndexColorModel originalICM = (IndexColorModel) cm;\n WritableRaster raster = image.getRaster();\n int colorIndex = raster.getSample(x, y, 0); // colorIndex is an offset in the palette of the ICM'\n // Number of indexed colors\n int size = originalICM.getMapSize();\n byte[] reds = new byte[size];\n byte[] greens = new byte[size];\n byte[] blues = new byte[size];\n originalICM.getReds(reds);\n originalICM.getGreens(greens);\n originalICM.getBlues(blues);\n IndexColorModel newICM = new IndexColorModel(8, size, reds, greens, blues, colorIndex);\n return new BufferedImage(newICM, raster, image.isAlphaPremultiplied(), null);\n }\n}\n" }, { "answer_id": 270075, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "TYPE_BYTE_INDEXED" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
266,491
<p>I have a lot of buttons and by clicking on different button, different image and text would appear. I can achieve what I want, but the code is just so long and it seems very repetitive. For example:</p> <pre><code> var aaClick = false; $("aa").observe('click', function() { unclick(); $('characterPic').writeAttribute('src',"aa.jpg"); $('characterBio').update("aatext"); $('aa').setStyle({ color: '#FFFFFF' }); aaClick = true; }); $("aa").observe('mouseover', function() { if (!aaClick) $('aa').setStyle({ color: '#FFFFFF' }); }); $("aa").observe('mouseout', function() { if (!aaClick) $('aa').setStyle({ color: '#666666' }); }); function unclick() { aaClick = false; $('aa').setStyle({ color: '#666666' }); } </code></pre> <p>same thing with bb, cc, etc. and every time I add a new button, I need to add it to unclick function as well. This is pretty annoying and I tried to google it, and I only found observe click on all listed items, so I still couldn't figure out since what I want involves button up when other buttons are clicked. </p> <p>Is there any way to just have a generic function that takes different id but do the exact same thing? Because from what I can see, if I can just replace aa with other id, I can reduce a lot of code. Thanks!!!</p>
[ { "answer_id": 266515, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "$(container).childElements().each(function(element) {\n $(element).observe('click', function () { … });\n …\n});\n [\"aa\", \"bb\", \"cc\"].each(function(element) { … same code … });\n" }, { "answer_id": 266533, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 3, "selected": true, "text": "var clicks = []\nfunction regEvents(divName) {\n $(divName).observe('click', function() {\n unclick(divName);\n $('characterPic').writeAttribute('src',divName+\".jpg\");\n $('characterBio').update(divName\"text\");\n $(divName).setStyle({ color: '#FFFFFF' });\n clicks[divName] = true\n\n });\n\n $(divName).observe('mouseover', function() {\n if (!clicks[divName]) $(divName).setStyle({ color: '#FFFFFF' });\n });\n\n $(divName).observe('mouseout', function() {\n if (!clicks[divName]) $(divName).setStyle({ color: '#666666' });\n });\n}\nfunction unclick(divName) {\n clicks[divName] = false;\n $(clicks[divName]).setStyle({ color: '#666666' });\n}\n" }, { "answer_id": 266550, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "var clickedHandler = function(element) { \n $(element).addClass(\"selected\");\n};\n$(\"aa\").observe('click', clickedHandler);\n$(\"bb\").observe('click', clickedHandler);\n" }, { "answer_id": 266558, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 1, "selected": false, "text": "yourButtonClass var clicks = [];\n$$('.yourButtonClass').each(function(button) {\n clicks.push(button.id);\n});\n$(document).observe('click', function(e) {\n // If your click registered on an element contained by the button, this comes in handy...\n var clicked = e.element().up('.yourButtonClass') || e.element();\n\n if(clicked.hasClassName('.yourButtonClass')) {\n unclick();\n $('characterPic').writeAttribute('src', clicked.id + '.jpg');\n $('characterBio').update(clicked.id + 'text');\n $(clicked).setStyle({ color: '#FFFFFF' });\n clicks[clicked.id] = true;\n }\n});\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34797/" ]
266,501
<p>Is there a way to define a macro that contains a <code>#include</code> directive in its body?</p> <p>If I just put the "<code>#include</code>", it gives the error</p> <pre><code>C2162: "expected macro formal parameter" </code></pre> <p>since here I am not using <code>#</code> to concatenate strings.<br> If I use "<code>\# include</code>", then I receive the following two errors:</p> <pre><code>error C2017: illegal escape sequence error C2121: '#' : invalid character : possibly the result of a macro expansion </code></pre> <p>Any help?</p>
[ { "answer_id": 266580, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": -1, "selected": false, "text": "#include \"standardAppDefs.h\"\n#myStandardIncludeMacro\n #define myStandardIncludeMacro #include <foo.h>\n #include \"standardAppDefs.h\"\n #include <foo.h>\n" }, { "answer_id": 266647, "author": "Bing Jian", "author_id": 34829, "author_profile": "https://Stackoverflow.com/users/34829", "pm_score": 2, "selected": false, "text": "void foo(AbstractClass object)\n{\n switch (object.data_type())\n {\n case AbstractClass::TYPE_UCHAR :\n {\n typedef unsigned char PixelType;\n #include \"snippets/foo.cpp\"\n }\n break;\n case AbstractClass::TYPE_UINT:\n {\n typedef unsigned int PixelType;\n #include \"snippets/foo.cpp\"\n }\n break;\n default:\n break;\n }\n}\n void bar(AbstractClass object)\n #include \"snippets/bar.cpp\"\n" }, { "answer_id": 266679, "author": "Dan Hewett", "author_id": 17975, "author_profile": "https://Stackoverflow.com/users/17975", "pm_score": 4, "selected": false, "text": "#include FT_FREETYPE_H\n" }, { "answer_id": 3613287, "author": "Lutorm", "author_id": 307175, "author_profile": "https://Stackoverflow.com/users/307175", "pm_score": 2, "selected": false, "text": "extern \"C\" {\n#include \"blah.h\"\n}\n __cplusplus #include <mpi.h>\n #ifdef __cplusplus\n#undef __cplusplus\n#include <mpi.h>\n#define __cplusplus\n#else\n#include <mpi.h>\n#endif\n INCLUDE_AS_C" }, { "answer_id": 27830271, "author": "Ben Farmer", "author_id": 1447953, "author_profile": "https://Stackoverflow.com/users/1447953", "pm_score": 5, "selected": false, "text": "/* tools.hpp */\n\n#ifndef __TOOLS_HPP__\n#def __TOOLS_HPP__\n\n// Macro for adding quotes\n#define STRINGIFY(X) STRINGIFY2(X) \n#define STRINGIFY2(X) #X\n\n// Macros for concatenating tokens\n#define CAT(X,Y) CAT2(X,Y)\n#define CAT2(X,Y) X##Y\n#define CAT_2 CAT\n#define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z))\n#define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z))\n// etc...\n\n#endif\n /* pseudomacro.hpp */\n\n#include \"tools.hpp\"\n// NO INCLUDE GUARD ON PURPOSE\n// Note especially FOO, which we can #define before #include-ing this file,\n// in order to alter which files it will in turn #include.\n// FOO fulfils the role of \"parameter\" in this pseudo-macro.\n\n#define INCLUDE_FILE(HEAD,TAIL) STRINGIFY( CAT_3(HEAD,FOO,TAIL) )\n\n#include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp\n#include INCLUDE_FILE(head2,tail2.hpp)\n#include INCLUDE_FILE(head3,tail3.hpp)\n#include INCLUDE_FILE(head4,tail4.hpp)\n// etc..\n\n#undef INCLUDE_FILE\n /* mainfile.cpp */\n\n// Here we automate the including of groups of similarly named files\n\n#define FOO _groupA_\n#include \"pseudomacro.hpp\"\n// \"expands\" to: \n// #include \"head1_groupA_tail1.hpp\"\n// #include \"head2_groupA_tail2.hpp\"\n// #include \"head3_groupA_tail3.hpp\"\n// #include \"head4_groupA_tail4.hpp\"\n#undef FOO\n\n#define FOO _groupB_\n#include \"pseudomacro.hpp\"\n// \"expands\" to: \n// #include \"head1_groupB_tail1.hpp\"\n// #include \"head2_groupB_tail2.hpp\"\n// #include \"head3_groupB_tail3.hpp\"\n// #include \"head4_groupB_tail4.hpp\"\n#undef FOO\n\n#define FOO _groupC_\n#include \"pseudomacro.hpp\"\n#undef FOO\n\n// etc.\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34829/" ]
266,506
<p>Using a standard ASP.NET ListView with a LinqDataSource and pagination enabled (with a DataPager), what would be the best way to default to displaying the last page of results?</p>
[ { "answer_id": 266580, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": -1, "selected": false, "text": "#include \"standardAppDefs.h\"\n#myStandardIncludeMacro\n #define myStandardIncludeMacro #include <foo.h>\n #include \"standardAppDefs.h\"\n #include <foo.h>\n" }, { "answer_id": 266647, "author": "Bing Jian", "author_id": 34829, "author_profile": "https://Stackoverflow.com/users/34829", "pm_score": 2, "selected": false, "text": "void foo(AbstractClass object)\n{\n switch (object.data_type())\n {\n case AbstractClass::TYPE_UCHAR :\n {\n typedef unsigned char PixelType;\n #include \"snippets/foo.cpp\"\n }\n break;\n case AbstractClass::TYPE_UINT:\n {\n typedef unsigned int PixelType;\n #include \"snippets/foo.cpp\"\n }\n break;\n default:\n break;\n }\n}\n void bar(AbstractClass object)\n #include \"snippets/bar.cpp\"\n" }, { "answer_id": 266679, "author": "Dan Hewett", "author_id": 17975, "author_profile": "https://Stackoverflow.com/users/17975", "pm_score": 4, "selected": false, "text": "#include FT_FREETYPE_H\n" }, { "answer_id": 3613287, "author": "Lutorm", "author_id": 307175, "author_profile": "https://Stackoverflow.com/users/307175", "pm_score": 2, "selected": false, "text": "extern \"C\" {\n#include \"blah.h\"\n}\n __cplusplus #include <mpi.h>\n #ifdef __cplusplus\n#undef __cplusplus\n#include <mpi.h>\n#define __cplusplus\n#else\n#include <mpi.h>\n#endif\n INCLUDE_AS_C" }, { "answer_id": 27830271, "author": "Ben Farmer", "author_id": 1447953, "author_profile": "https://Stackoverflow.com/users/1447953", "pm_score": 5, "selected": false, "text": "/* tools.hpp */\n\n#ifndef __TOOLS_HPP__\n#def __TOOLS_HPP__\n\n// Macro for adding quotes\n#define STRINGIFY(X) STRINGIFY2(X) \n#define STRINGIFY2(X) #X\n\n// Macros for concatenating tokens\n#define CAT(X,Y) CAT2(X,Y)\n#define CAT2(X,Y) X##Y\n#define CAT_2 CAT\n#define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z))\n#define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z))\n// etc...\n\n#endif\n /* pseudomacro.hpp */\n\n#include \"tools.hpp\"\n// NO INCLUDE GUARD ON PURPOSE\n// Note especially FOO, which we can #define before #include-ing this file,\n// in order to alter which files it will in turn #include.\n// FOO fulfils the role of \"parameter\" in this pseudo-macro.\n\n#define INCLUDE_FILE(HEAD,TAIL) STRINGIFY( CAT_3(HEAD,FOO,TAIL) )\n\n#include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp\n#include INCLUDE_FILE(head2,tail2.hpp)\n#include INCLUDE_FILE(head3,tail3.hpp)\n#include INCLUDE_FILE(head4,tail4.hpp)\n// etc..\n\n#undef INCLUDE_FILE\n /* mainfile.cpp */\n\n// Here we automate the including of groups of similarly named files\n\n#define FOO _groupA_\n#include \"pseudomacro.hpp\"\n// \"expands\" to: \n// #include \"head1_groupA_tail1.hpp\"\n// #include \"head2_groupA_tail2.hpp\"\n// #include \"head3_groupA_tail3.hpp\"\n// #include \"head4_groupA_tail4.hpp\"\n#undef FOO\n\n#define FOO _groupB_\n#include \"pseudomacro.hpp\"\n// \"expands\" to: \n// #include \"head1_groupB_tail1.hpp\"\n// #include \"head2_groupB_tail2.hpp\"\n// #include \"head3_groupB_tail3.hpp\"\n// #include \"head4_groupB_tail4.hpp\"\n#undef FOO\n\n#define FOO _groupC_\n#include \"pseudomacro.hpp\"\n#undef FOO\n\n// etc.\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9433/" ]
266,507
<p>I'm using linq to pull back an object (i.e. customer) that might have a collection of other objects(customer.orders). I would be nice if I can pass this list of customers to the ultragrid and a hierarchical view of customers and thier orders displayed on databind. When I try this, I just get customers. Anyone know how to get this to work with non dataset objects?</p>
[ { "answer_id": 272436, "author": "Bless Yahu", "author_id": 32120, "author_profile": "https://Stackoverflow.com/users/32120", "pm_score": 4, "selected": true, "text": "IList<T> DisplayLayout.ViewStyle = ViewStyle.MultiBand" }, { "answer_id": 3055563, "author": "KTN", "author_id": 368490, "author_profile": "https://Stackoverflow.com/users/368490", "pm_score": 1, "selected": false, "text": "DisplayLayout.ViewStyle = ViewStyle.MultiBand\n List IList" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32120/" ]
266,523
<p>Are there any drawbacks to using the STL or templates. Are there any situations for which they are inappropriate.</p>
[ { "answer_id": 267412, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 1, "selected": false, "text": "hash_map tr1/unordered_map" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
266,549
<p>Using MEF I want to do the following.</p> <p>I have a WPF Shell. To the shell I want to Import from another DLL a UserControl that is also a View of my MVP triad. The way the MVP triad works, is that in presenter I have a constructor that takes both IModel and IView and wires them up. So, in order for this to work, I need MEF to do the following:</p> <ol> <li>Create IView implementation</li> <li>Create IModel implementation</li> <li>Create Presenter and pass IModel and IView to its constructor</li> <li>Import IView implementation into my shell when it gets displayed</li> </ol> <p>Instead what it does, is it only creates the type Exporting IView and passes it to the shell, basically skipping steps 2 and 3. Its pretty logical, when you think about it, but how can I tell MEF to also create the whole triad when I ask for a IView. I don't need to reference Presenter nor model anywhere else in my Shell .dll so puting it as an Import as well is not an option (and it would be quite ugly anyway :).</p> <p>I'm using the latest drop of MEF (Preview 2 Refresh). Anyone?</p> <p><strong>==Update==</strong></p> <p>I have found a solution and I blogged about it here:<br> <a href="http://kozmic.pl/archive/2008/11/06/creating-tree-of-dependencies-with-mef/" rel="nofollow noreferrer" title="here">Krzysztof Koźmic's blog - Creating tree of dependencies with MEF</a></p> <p>However, I'd be more than happy if someone came up with a better solution.**</p>
[ { "answer_id": 285744, "author": "Glenn Block", "author_id": 18419, "author_profile": "https://Stackoverflow.com/users/18419", "pm_score": 3, "selected": true, "text": " 1: using System.ComponentModel.Composition;\n 2: using System.Reflection;\n 3: using Microsoft.VisualStudio.TestTools.UnitTesting;\n 4: \n 5: namespace MVPwithMEF\n 6: {\n 7: /// <summary>\n 8: /// Summary description for MVPTriadFixture\n 9: /// </summary>\n 10: [TestClass]\n 11: public class MVPTriadFixture\n 12: {\n 13: [TestMethod]\n 14: public void MVPTriadShouldBeProperlyBuilt()\n 15: {\n 16: var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());\n 17: var container = new CompositionContainer(catalog.CreateResolver());\n 18: var shell = container.GetExportedObject<Shell>();\n 19: Assert.IsNotNull(shell);\n 20: Assert.IsNotNull(shell.Presenter);\n 21: Assert.IsNotNull(shell.Presenter.View);\n 22: Assert.IsNotNull(shell.Presenter.Model);\n 23: }\n 24: }\n 25: \n 26: [Export]\n 27: public class Shell\n 28: {\n 29: private IPresenter _presenter = null;\n 30: \n 31: public IPresenter Presenter\n 32: {\n 33: get { return _presenter; }\n 34: }\n 35: \n 36: [ImportingConstructor]\n 37: public Shell(IPresenter presenter)\n 38: {\n 39: _presenter = presenter;\n 40: }\n 41: }\n 42: \n 43: public interface IModel\n 44: {\n 45: }\n 46: \n 47: [Export(typeof(IModel))]\n 48: public class Model : IModel\n 49: {\n 50: \n 51: }\n 52: \n 53: public interface IView\n 54: {\n 55: }\n 56: \n 57: [Export(typeof(IView))]\n 58: public class View : IView\n 59: {\n 60: }\n 61: \n 62: public interface IPresenter\n 63: {\n 64: IView View { get;}\n 65: IModel Model { get; }\n 66: }\n 67: \n 68: [Export(typeof(IPresenter))]\n 69: public class Presenter : IPresenter\n 70: {\n 71: \n 72: private IView _view;\n 73: private IModel _model;\n 74: \n 75: [ImportingConstructor]\n 76: public Presenter(IView view, IModel model)\n 77: {\n 78: _view = view;\n 79: _model = model;\n 80: }\n 81: \n 82: public IView View\n 83: {\n 84: get { return _view; }\n 85: }\n 86: \n 87: public IModel Model\n 88: {\n 89: get { return _model; }\n 90: }\n 91: \n 92: }\n 93: }\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13163/" ]
266,570
<p>Is there any performance difference between the for loops on a primitive array? </p> <p>Assume:</p> <pre><code>double[] doubleArray = new double[300000]; for (double var: doubleArray) someComplexCalculation(var); </code></pre> <p>or :</p> <pre><code>for ( int i = 0, y = doubleArray.length; i &lt; y; i++) someComplexCalculation(doubleArray[i]); </code></pre> <p><strong>Test result</strong></p> <p>I actually profiled it:</p> <pre><code>Total timeused for modern loop= 13269ms Total timeused for old loop = 15370ms </code></pre> <p>So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5. </p>
[ { "answer_id": 266727, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "1: double[] tmp = doubleArray;\n2: for (int i = 0, y = tmp.length; i < y; i++) {\n3: double var = tmp[i];\n4: someComplexCalculation(var);\n5: }\n doubleArray tmp var" }, { "answer_id": 269296, "author": "Paulo Guedes", "author_id": 33857, "author_profile": "https://Stackoverflow.com/users/33857", "pm_score": 1, "selected": false, "text": "public class TestEnhancedFor {\n\n public static void main(String args[]){\n new TestEnhancedFor();\n }\n\n public TestEnhancedFor(){\n int numberOfItems = 100000;\n double[] items = getArrayOfItems(numberOfItems);\n int repetitions = 0;\n long start, end;\n\n do {\n start = System.currentTimeMillis();\n doNormalFor(items);\n end = System.currentTimeMillis();\n System.out.printf(\"Normal For. Repetition %d: %d\\n\", \n repetitions, end-start);\n\n start = System.currentTimeMillis();\n doEnhancedFor(items);\n end = System.currentTimeMillis();\n System.out.printf(\"Enhanced For. Repetition %d: %d\\n\\n\", \n repetitions, end-start);\n\n } while (++repetitions < 5);\n }\n\n private double[] getArrayOfItems(int numberOfItems){\n double[] items = new double[numberOfItems];\n for (int i=0; i < numberOfItems; i++)\n items[i] = i;\n return items;\n }\n\n private void doSomeComplexCalculation(double item){\n // check if item is prime number\n for (int i = 3; i < item / 2; i+=2){\n if ((item / i) == (int) (item / i)) break;\n }\n }\n\n private void doNormalFor(double[] items){\n for (int i = 0; i < items.length; i++)\n doSomeComplexCalculation(items[i]);\n }\n\n private void doEnhancedFor(double[] items){\n for (double item : items)\n doSomeComplexCalculation(item);\n }\n\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9774/" ]
266,578
<p>I really like the Flex framework, however I routinely deal with SWF files that are ~ 500KB. </p> <p>I don't know at what point a file considered to be "too big" to be served on the internet, but I would assume that a 500KB download just to use a web application would certainly annoy some users.</p> <p>Are there any tips or techniques on reducing the size of compiled SWFS? </p> <p>As a side note, the 500KB SWF file really isn't that big of application...</p>
[ { "answer_id": 266613, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 1, "selected": false, "text": "URLRequest" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
266,586
<p>I am coding in ColdFusion, but trying to stay in cfscript, so I have a function that allows me to pass in a query to run it with <code> &lt;cfquery blah > #query# &lt;/cfquery> </code></p> <p>Somehow though, when I construct my queries with <code>sql = "SELECT * FROM a WHERE b='#c#'"</code> and pass it in, ColdFusion has replaced the single quotes with 2 single quotes. so it becomes <code> WHERE b=''c''</code> in the final query.</p> <p>I have tried creating the strings a lot of different ways, but I cannot get it to leave just one quote. Even doing a string replace has no effect. </p> <p>Any idea why this is happening? It is ruining my hopes of living in cfscript for the duration of this project</p>
[ { "answer_id": 266680, "author": "ale", "author_id": 21960, "author_profile": "https://Stackoverflow.com/users/21960", "pm_score": 4, "selected": false, "text": "<cfquery> PreserveSingleQuotes() <cfquery ...>#PreserveSingleQuotes(query)#</cfquery>\n <cfqueryparam> <cfqueryparam>" }, { "answer_id": 266787, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<cfquery> SELECT * FROM TABLE WHERE Foo='#Foo#'\n #Foo# #PreserveSingleQuotes(Foo)# SELECT * FROM TABLE WHERE Foo='#LCase(Foo)#' /* Single quotes are retained! */\n PreserveSingleQuotes()" }, { "answer_id": 267093, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 3, "selected": false, "text": "preserveSingleQuotes(...) cfqueryparam" }, { "answer_id": 411959, "author": "Isaac Dealey", "author_id": 50355, "author_profile": "https://Stackoverflow.com/users/50355", "pm_score": 0, "selected": false, "text": "qry = datasource.select_avg_price_as_avgprice_from_products(); //(requires CF8)\n\nqry = datasource.select(\"avg(price) as avgprice\",\"products\"); \n\nqry = datasource.getSelect(\"avg(price) as avgprice\",\"products\").filter(\"categoryid\",url.categoryid).execute();\n\nqry = datasource.getSelect(table=\"products\",orderby=\"productname\").filter(\"categoryid\",url.categoryid).execute();\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
266,601
<p>My spring-context file is shown below.</p> <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"&gt; &lt;bean id="cfaBeanFactory" class="org.springframework.context.support.ClassPathXmlApplicationContext"&gt; &lt;constructor-arg value="classpath:cfa-spring-core.xml" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>When I try to run my application, I get the following error:</p> <pre><code>Caused by: org.springframework.beans.factory.access.BootstrapException: Unable to initialize group definition. Group resource name [classpath*:cfa-spring-context.xml], factory key [cfaBeanFactory]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Line 16 in XML document from URL [file:/C:/.../cfa-spring-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:389) ... 56 more Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Line 16 in XML document from URL [file:/C:/.../cfa-spring-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:169) ... 59 more Caused by: org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) </code></pre> <p>Can someone tell me what I'm doing wrong?</p>
[ { "answer_id": 266627, "author": "Mike Pone", "author_id": 16404, "author_profile": "https://Stackoverflow.com/users/16404", "pm_score": 0, "selected": false, "text": "<beans> </beans>" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
266,606
<p>I'm running an application (web service) in tomcat with TLS enabled (with certificates both for the client and the server).</p> <p>I want that my application will be able to send audit message (logging) when TLS handshake fails. For example I want to log when:</p> <ul> <li>the client certificate is expired,</li> <li>the client certificate is unknown (not in the server trust store)</li> <li>any other handshake failure</li> </ul> <p>Is there any event that I can catch and handle in order to do that?</p> <p>My application is web service based and is running in tomcat. Tomcat is handling all network and the TLS layers, and the application does not aware of that.</p> <p>As I don't open any socket myself, where should I catch this Exception?</p>
[ { "answer_id": 266650, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "javax.net.ssl.SSLHandshakeException" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20065/" ]
266,621
<p>I'm consuming an axis 1.4 web service that returns soap responses that I want to unmarshal into my domain objects using jaxb annotations. My initial tests worked very well until some of the returned messages had multiRef elements. Objects that were marshalled using multiRef were showing up as null in my client side annotated model objects. </p> <p>My question is does JAXB support unmarshalling soap responses with multiRef elements? If so, how? and if not, does anybody know of a better way to unmarshal axis 1.4 soap responses into my domain model in java?</p>
[ { "answer_id": 444582, "author": "martsraits", "author_id": 55036, "author_profile": "https://Stackoverflow.com/users/55036", "pm_score": 0, "selected": false, "text": "org.apache.axis.AxisEngine.PROP_DOMULTIREFS" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32825/" ]
266,639
<p>What is the best tool / practice to enable browser history for Flash (or AJAX) websites? I guess the established practice is to set and read a hash-addition to the URL like</p> <pre><code>http://example.com/#id=1 </code></pre> <p>I am aware of the Flex History Manager, but was wondering if there are any good alternatives to consider. Would also be interested in a general AJAX solution or best practice.</p>
[ { "answer_id": 405704, "author": "nakajima", "author_id": 39589, "author_profile": "https://Stackoverflow.com/users/39589", "pm_score": 0, "selected": false, "text": "(function() {\n var oldHash, newHash;\n\n function checkHash() {\n // Grab the hash\n newHash = document.location.hash;\n\n // Check to see if it changed\n if (oldHash != newHash) {\n\n // Trigger a custom event if it changed,\n // passing the old and new values as\n // metadata on the event.\n $(document).trigger('hash.changed', {\n old: oldHash,\n new: newHash\n });\n\n // Update the oldHash for the next check\n oldHash = newHash;\n }\n }\n\n // Poll the hash every 10 milliseconds.\n // You might need to alter this time based\n // on performance\n window.setInterval(checkHash, 10);\n\n})(jQuery);\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23069/" ]
266,648
<p>How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?</p> <p>This is how far I got by now:</p> <p>Script receives image via HTML Form Post and is processed by the following code</p> <pre><code>... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... </code></pre> <p>I found mimetypes.guess_type, but it does not work for me.</p>
[ { "answer_id": 266731, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": true, "text": "Start Marker | JFIF Marker | Header Length | Identifier\n0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | \"JFIF\\0\"\n def is_jpg(filename):\n data = open(filename,'rb').read(11)\n if data[:4] != '\\xff\\xd8\\xff\\xe0': return False\n if data[6:] != 'JFIF\\0': return False\n return True\n from PIL import Image\ndef is_jpg(filename):\n try:\n i=Image.open(filename)\n return i.format =='JPEG'\n except IOError:\n return False\n" }, { "answer_id": 266774, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": ">>> import Image\n>>> im = Image.open(\"lena.ppm\")\n>>> print im.format, im.size, im.mode\n" }, { "answer_id": 1040027, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "import imghdr\n\nimage_type = imghdr.what(filename)\nif not image_type:\n print \"error\"\nelse:\n print image_type\n image_type = imghdr.what(filename, incomming_image)\n ${h.form(h.url_for(action=\"save_image\"), multipart=True)}\nUpload file: ${h.file(\"upload_file\")} <br />\n${h.submit(\"Submit\", \"Submit\")}\n${h.end_form()}\n def save_image(self):\n upload_file = request.POST[\"upload_file\"]\n image_type = imghdr.what(upload_file.filename, upload_file.value)\n if not image_type:\n return \"error\"\n else:\n return image_type\n" }, { "answer_id": 5717194, "author": "Jabba", "author_id": 232485, "author_profile": "https://Stackoverflow.com/users/232485", "pm_score": 1, "selected": false, "text": "import magic\n\nms = magic.open(magic.MAGIC_NONE)\nms.load()\ntype = ms.file(\"/path/to/some/file\")\nprint type\n\nf = file(\"/path/to/some/file\", \"r\")\nbuffer = f.read(4096)\nf.close()\n\ntype = ms.buffer(buffer)\nprint type\n\nms.close()\n" }, { "answer_id": 28907255, "author": "Christian Papathanasiou", "author_id": 4642505, "author_profile": "https://Stackoverflow.com/users/4642505", "pm_score": 0, "selected": false, "text": "def is_jpg(filename):\n data = open(\"uploads/\" + filename,'rb').read(11)\n if (data[:3] == \"\\xff\\xd8\\xff\"):\n return True\n elif (data[6:] == 'JFIF\\0'): \n return True\n else:\n return False\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26763/" ]
266,652
<p>We are trying to build a Crystal Report that sends control characters directly to the printer, without going through the (buggy) Windows driver for that printer. Does anyone know a way to do this from within a Crystal Report? </p> <p>The specific control character we are trying to send is CHR(2). However when we put that in a Crystal Report, and print to a Generic Text Only printer, it is converting the character to a period on output. The character appears as a box in Crystal's preview, so I suspect it is the Windows driver, rather than Crystal, that is the problem.</p> <p>The device is a Datamax printer. We do have drivers for it, but are encountering various problems - the infrastructure group knows more about the problems than I do, I don't feel I have enough information to try and ask about the specific problem. It is some combination of the interplay of Crystal Reports, Citrix, our market-specific ERP package, and automatically selecting label printers for the appropriate label size based on user at the time the report is run.</p>
[ { "answer_id": 266731, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": true, "text": "Start Marker | JFIF Marker | Header Length | Identifier\n0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | \"JFIF\\0\"\n def is_jpg(filename):\n data = open(filename,'rb').read(11)\n if data[:4] != '\\xff\\xd8\\xff\\xe0': return False\n if data[6:] != 'JFIF\\0': return False\n return True\n from PIL import Image\ndef is_jpg(filename):\n try:\n i=Image.open(filename)\n return i.format =='JPEG'\n except IOError:\n return False\n" }, { "answer_id": 266774, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": ">>> import Image\n>>> im = Image.open(\"lena.ppm\")\n>>> print im.format, im.size, im.mode\n" }, { "answer_id": 1040027, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "import imghdr\n\nimage_type = imghdr.what(filename)\nif not image_type:\n print \"error\"\nelse:\n print image_type\n image_type = imghdr.what(filename, incomming_image)\n ${h.form(h.url_for(action=\"save_image\"), multipart=True)}\nUpload file: ${h.file(\"upload_file\")} <br />\n${h.submit(\"Submit\", \"Submit\")}\n${h.end_form()}\n def save_image(self):\n upload_file = request.POST[\"upload_file\"]\n image_type = imghdr.what(upload_file.filename, upload_file.value)\n if not image_type:\n return \"error\"\n else:\n return image_type\n" }, { "answer_id": 5717194, "author": "Jabba", "author_id": 232485, "author_profile": "https://Stackoverflow.com/users/232485", "pm_score": 1, "selected": false, "text": "import magic\n\nms = magic.open(magic.MAGIC_NONE)\nms.load()\ntype = ms.file(\"/path/to/some/file\")\nprint type\n\nf = file(\"/path/to/some/file\", \"r\")\nbuffer = f.read(4096)\nf.close()\n\ntype = ms.buffer(buffer)\nprint type\n\nms.close()\n" }, { "answer_id": 28907255, "author": "Christian Papathanasiou", "author_id": 4642505, "author_profile": "https://Stackoverflow.com/users/4642505", "pm_score": 0, "selected": false, "text": "def is_jpg(filename):\n data = open(\"uploads/\" + filename,'rb').read(11)\n if (data[:3] == \"\\xff\\xd8\\xff\"):\n return True\n elif (data[6:] == 'JFIF\\0'): \n return True\n else:\n return False\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20068/" ]
266,665
<p>I'm learning C++ and writing little programs as I go along. The following is one such program:</p> <pre><code>// This program is intended to take any integer and convert to the // corresponding signed char. #include &lt;iostream&gt; int main() { signed char sch = 0; int n = 0; while(true){ std::cin &gt;&gt; n; sch = n; std::cout &lt;&lt; n &lt;&lt; " --&gt; " &lt;&lt; sch &lt;&lt; std::endl; } } </code></pre> <p>When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:</p> <pre><code>#: ./int2ch 10 10 --&gt; 10000000000 10 --&gt; 10 --&gt; 10 --&gt; 10 --&gt; </code></pre> <p>The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.</p> <p>What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)</p>
[ { "answer_id": 266703, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": true, "text": "cin #include <iostream>\n\nint main()\n{\n signed char sch = 0;\n int n = 0;\n while(std::cin >> n){\n sch = n;\n std::cout << n << \" --> \" << sch << std::endl;\n }\n}\n cin >> n cin while(std::cin >> n) #include <iostream>\n#include <climits>\n\nint main() {\n signed char sch = 0;\n int n = 0;\n while(true) {\n if(std::cin >> n) {\n sch = n;\n std::cout << n << \" --> \" << sch << std::endl;\n } else {\n std::cin.clear(); // clear error state\n std::cin.ignore(INT_MAX, '\\n'); // ignore this line we couldn't read it\n }\n }\n}\n" }, { "answer_id": 266711, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "char int int" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32944/" ]
266,681
<p>I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best?</p> <p>1)</p> <pre><code>void example() { lock (mutex) { //... } return myData; } </code></pre> <p>2)</p> <pre><code>void example() { lock (mutex) { //... return myData; } } </code></pre> <p>Which one should I use?</p>
[ { "answer_id": 266685, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 5, "selected": false, "text": "T myData;\nMonitor.Enter(mutex)\ntry\n{\n myData= // something\n}\nfinally\n{\n Monitor.Exit(mutex);\n}\n\nreturn myData;\n" }, { "answer_id": 266706, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "return f(...)\n" }, { "answer_id": 266718, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 9, "selected": true, "text": "static class Program\n{\n static void Main() { }\n\n static readonly object sync = new object();\n\n static int GetValue() { return 5; }\n\n static int ReturnInside()\n {\n lock (sync)\n {\n return GetValue();\n }\n }\n\n static int ReturnOutside()\n {\n int val;\n lock (sync)\n {\n val = GetValue();\n }\n return val;\n }\n}\n ReturnInside .method private hidebysig static int32 ReturnInside() cil managed\n{\n .maxstack 2\n .locals init (\n [0] int32 CS$1$0000,\n [1] object CS$2$0001)\n L_0000: ldsfld object Program::sync\n L_0005: dup \n L_0006: stloc.1 \n L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)\n L_000c: call int32 Program::GetValue()\n L_0011: stloc.0 \n L_0012: leave.s L_001b\n L_0014: ldloc.1 \n L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)\n L_001a: endfinally \n L_001b: ldloc.0 \n L_001c: ret \n .try L_000c to L_0014 finally handler L_0014 to L_001b\n} \n\nmethod private hidebysig static int32 ReturnOutside() cil managed\n{\n .maxstack 2\n .locals init (\n [0] int32 val,\n [1] object CS$2$0000)\n L_0000: ldsfld object Program::sync\n L_0005: dup \n L_0006: stloc.1 \n L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)\n L_000c: call int32 Program::GetValue()\n L_0011: stloc.0 \n L_0012: leave.s L_001b\n L_0014: ldloc.1 \n L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)\n L_001a: endfinally \n L_001b: ldloc.0 \n L_001c: ret \n .try L_000c to L_0014 finally handler L_0014 to L_001b\n}\n ReturnInside" }, { "answer_id": 266766, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 3, "selected": false, "text": "void example() { \n int myData;\n lock (foo) { \n myData = ...;\n }\n return myData\n}\n void example() { \n lock (foo) {\n return ...;\n }\n}\n" }, { "answer_id": 47995372, "author": "mshakurov", "author_id": 3787814, "author_profile": "https://Stackoverflow.com/users/3787814", "pm_score": 0, "selected": false, "text": "lock() return <expression> <expression> lock() return" }, { "answer_id": 62028761, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": -1, "selected": false, "text": "return return lock return lock return return return try catch using if while for lock" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
266,688
<p>As many do I have a config.php file in the root of a web app that I want to include in almost every other php file. So most of them have a line like:</p> <pre><code>require_once("config.php"); </code></pre> <p>or sometimes</p> <pre><code>require_once("../config.php"); </code></pre> <p>or even</p> <pre><code>require_once("../../config.php"); </code></pre> <p>But I never get it right the first time. I can't figure out what php is going to consider to be the current working directory when reading one of these files. It is apparently not the directory where the file containing the require_once() call is made because I can have two files in the same directory that have different paths for the config.php.</p> <p>How I have a situation where one path is correct for refreshing the page but an ajax can that updates part of the page requires a different path to the config.php in the require_once() statement;</p> <p>What's the secret? From where is that path evaluated?</p> <p>Shoot, I was afraid this wouldn't be a common problem - This is occurring under apache 2.2.8 and PHP 5.2.6 running on windows.</p>
[ { "answer_id": 266730, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 4, "selected": false, "text": "require_once(dirname(__FILE__).\"/../_include/header.inc\");\n" }, { "answer_id": 266749, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "dirname(__FILE__) __FILE__ define(\"ROOT\",dirname(__FILE__).'/' ); \n require(ROOT . \"/lib/tool/error.php\"); \n cd foo\n php bar/baz.php \n -> some error saying it cant find the file\n cd bar \n php baz.php \n -> suddenly working.\n" }, { "answer_id": 266768, "author": "Ferdinand Beyer", "author_id": 34855, "author_profile": "https://Stackoverflow.com/users/34855", "pm_score": 1, "selected": false, "text": "include_path $includeDir = realpath(dirname(__FILE__) . '/include'); \nini_set('include_path', $includeDir . PATH_SEPARATOR . ini_get('include_path'));\n require_once '../init.php'; // The init-script\nrequire_once 'MyFile.php'; // Includes /include/MyFile.php\n" }, { "answer_id": 266775, "author": "Seamus", "author_id": 30443, "author_profile": "https://Stackoverflow.com/users/30443", "pm_score": 6, "selected": true, "text": "/A\n foo.php\n tar.php\n B/\n bar.php\n <?php\nrequire_once( 'B/bar.php' );\n?>\n <?php\nrequire_once( 'tar.php');\n?>\n require_once( realpath( dirname( __FILE__ ) ).'/../../path/to/file.php' );\n // config file\ndefine( \"APP_ROOT\", realpath( dirname( __FILE__ ) ).'/' );\n require_once( APP_ROOT.'../../path/to/file.php' );\n" }, { "answer_id": 267037, "author": "Steve Massing", "author_id": 34889, "author_profile": "https://Stackoverflow.com/users/34889", "pm_score": 2, "selected": false, "text": "//get basic page variables\n$self=$_SERVER['PHP_SELF']; \n$thispath=dirname($_SERVER['PHP_SELF']);\n$sitebasepath=$_SERVER['DOCUMENT_ROOT'];\n\n//include the global settings, variables and includes\n\ninclude_once(\"$sitebasepath/globals/global.include.php\");\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28565/" ]
266,693
<p>I'd like to remove all "unchecked" warnings from this general utility method (part of a larger class with a number of similar methods). In a pinch, I can use @SuppressWarnings("unchecked") but I'm wondering if I can use generics properly to avoid the warning.</p> <p>The method is intended to be allow callers to compare two objects by passing through to compareTo, with the exception that if the object is a strings it does it in a case insensitive manner.</p> <pre><code>public static int compareObject(Comparable o1, Comparable o2) { if ((o1 instanceof String) &amp;&amp; (o2 instanceof String)) return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase()); else return o1.compareTo(o2); } </code></pre> <p>This was my first (incorrect) attempt at a solution. The parameters work fine, but the line o1.compareTo(o2) has a compile error "The method compareTo(capture#15-of ?) in the type Comparable is not applicable for the arguments (Comparable".</p> <pre><code>public static int compareObject(Comparable&lt;?&gt; o1, Comparable&lt;?&gt; o2) { if ((o1 instanceof String) &amp;&amp; (o2 instanceof String)) return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase()); else return o1.compareTo(o2); } </code></pre> <p>Any suggestions?</p>
[ { "answer_id": 266741, "author": "jfpoilpret", "author_id": 1440720, "author_profile": "https://Stackoverflow.com/users/1440720", "pm_score": -1, "selected": false, "text": "public static <T> int compareObject(Comparable<T> o1, Comparable<T> o2)\n{\n if ((o1 instanceof String) && (o2 instanceof String))\n return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n" }, { "answer_id": 266786, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 3, "selected": true, "text": "public static <T extends Comparable> int compareObject(T o1, T o2) {\n if ((o1 instanceof String) && (o2 instanceof String))\n return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n public static <T extends Comparable<T>> int compareObject(T o1, T o2) {\n public static <T extends Comparable<T>> int compareObject(T o1, T o2) {\n if (((Object) o1 instanceof String) && ((Object) o2 instanceof String))\n return ((String) (Object)o1).toUpperCase().compareTo(((String) (Object)o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n Object" }, { "answer_id": 266789, "author": "Frederic Morin", "author_id": 4064, "author_profile": "https://Stackoverflow.com/users/4064", "pm_score": 1, "selected": false, "text": "public static <T extends Comparable<T>> int compareObject(T o1, T o2) {\n if ((o1 instanceof String) && (o2 instanceof String))\n return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n" }, { "answer_id": 267913, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 1, "selected": false, "text": "public static <T extends Comparable<T>> int compareObject(T o1, T o2)\n public static int compareObject2(Comparable<Object> o1, Comparable<Object> o2) {\n if (((Object) o1 instanceof String) && ((Object) o2 instanceof String))\n return ((String) (Object)o1).toUpperCase().compareTo(((String) (Object)o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n @SuppressWarnings(\"unchecked\")" }, { "answer_id": 666938, "author": "Bartosz Klimek", "author_id": 79920, "author_profile": "https://Stackoverflow.com/users/79920", "pm_score": 0, "selected": false, "text": " public static <T extends Comparable<T>> int compareObjects(T o1, T o2)\n {\n return o1.compareTo(o2);\n }\n\n public static int compareObjects(String o1, String o2)\n {\n return o1.compareToIgnoreCase(o2);\n }\n compareObjects()" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32978/" ]
266,697
<p>I have a stored procedure that has a optional parameter, <code>@UserID VARCHAR(50)</code>. The thing is, there are two ways to work with it:</p> <ol> <li>Give it a default value of <code>NULL</code>, the have an <code>IF...ELSE</code> clause, that performs two different <code>SELECT</code> queries, one with <code>'WHERE UserID = @UserID'</code> and without the where.</li> <li>Give it a default value of <code>'%'</code> and then just have the where clause use <code>'WHERE UserID LIKE @UserID'</code>. In the calling code, the '%' wont be used, so only exact matches will be found.</li> </ol> <p>The question is: Which option is faster? Which option provides better performance as the table grows? Be aware that the <code>UserID</code> column is a foreign key and is not indexed. </p> <p><b>EDIT:</b> Something I want to add, based on some answers: The <code>@UserID</code> parameter is not (necessarily) the only <b>optional</b> parameter being passed. In some cases there are as many as 4 or 5 optional parameters.</p>
[ { "answer_id": 266717, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 3, "selected": false, "text": "WHERE ( @UserID IS NULL OR UserID = @UserID )\n" }, { "answer_id": 266728, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 2, "selected": false, "text": "WHERE (@UserID IS NULL OR UserId = @UserId)\n" }, { "answer_id": 266729, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 2, "selected": false, "text": "where @UserID is null or UserID=@UserID \n" }, { "answer_id": 266767, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "UserID UserID LIKE @UserID @UserID UserID WHERE UserID = @UserID NULL IF" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8363/" ]
266,704
<p>Is there any way in JavaScript to create a &quot;weak reference&quot; to another object? <a href="http://en.wikipedia.org/wiki/Weak_reference" rel="nofollow noreferrer">Here is the wiki page describing what a weak reference is.</a> <a href="https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references" rel="nofollow noreferrer">Here is another article that describes them in Java.</a> Can anyone think of a way to implement this behavior in JavaScript?</p>
[ { "answer_id": 266892, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 6, "selected": true, "text": "WeakRef" }, { "answer_id": 42119578, "author": "Markus", "author_id": 1826075, "author_profile": "https://Stackoverflow.com/users/1826075", "pm_score": 2, "selected": false, "text": "this.val = {};\nthis.ref = new WeakReference(this.val);\n...\nthis.ref.get(); // always returns val\n...\nthis.val = null; // no more references\n...\nthis.ref.get(); // may still return val, depending on already gc'd or not\n this.val = {};\nthis.key = cache.put(this.val);\n...\ncache.get(this.key); // returns val, until evicted by other cache puts\n...\nthis.val = null; // no more references\n...\ncache.get(this.key); // returns val, until evicted by other cache puts\n" }, { "answer_id": 65552300, "author": "Peter Moore", "author_id": 4467670, "author_profile": "https://Stackoverflow.com/users/4467670", "pm_score": 2, "selected": false, "text": "WeakRef" }, { "answer_id": 74131509, "author": "Sheldon Oliveira", "author_id": 7050878, "author_profile": "https://Stackoverflow.com/users/7050878", "pm_score": 0, "selected": false, "text": "export class IterableWeakMap<T extends Object, V> {\n weakMap = new WeakMap();\n\n refSet = new Set<WeakRef<T>>();\n\n finalizationGroup = new FinalizationRegistry(IterableWeakMap.cleanup);\n\n static cleanup({ set, ref }: { set: Set<WeakRef<Object>>; ref: WeakRef<Object> }) {\n set.delete(ref);\n }\n\n constructor(iterable?: Iterable<[T, V]>) {\n if (!iterable) return;\n for (const [key, value] of iterable) {\n this.set(key, value);\n }\n }\n\n set(key: T, value: V) {\n const ref = new WeakRef<T>(key);\n\n this.weakMap.set(key, { value, ref });\n this.refSet.add(ref);\n this.finalizationGroup.register(key, { set: this.refSet, ref }, ref);\n }\n\n get(key: T) {\n const entry = this.weakMap.get(key);\n return entry && entry.value;\n }\n\n delete(key: T) {\n const entry = this.weakMap.get(key);\n if (!entry) {\n return false;\n }\n\n this.weakMap.delete(key);\n this.refSet.delete(entry.ref);\n this.finalizationGroup.unregister(entry.ref);\n return true;\n }\n\n *[Symbol.iterator]() {\n for (const ref of this.refSet) {\n const key = ref.deref();\n if (!key) continue;\n const { value } = this.weakMap.get(key);\n yield [key, value];\n }\n }\n\n entries() {\n return this[Symbol.iterator]();\n }\n\n *keys() {\n for (const [key] of this) {\n yield key;\n }\n }\n\n *values() {\n for (const [, value] of this) {\n yield value;\n }\n }\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21317/" ]
266,716
<p>Is there a way to select which TestMethods you want to execute in Visual Studio 2008 Unit Test project while debugging? I want to debug one particular test without having my other TestMethods execute during each debug session.</p>
[ { "answer_id": 1999464, "author": "peSHIr", "author_id": 50846, "author_profile": "https://Stackoverflow.com/users/50846", "pm_score": 0, "selected": false, "text": "Test Windows Test List Editor" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
266,719
<p>I've seen a lot of discussion on URL Routing, and LOTS of great suggestions... but in the real world, one thing I haven't seen discussed are: </p> <ol> <li>Creating Friendly URLs <strong>with Spaces and illegal characters</strong> </li> <li>Querying the DB</li> </ol> <p>Say you're building a Medical site, which has <strong>Articles</strong> with a <strong>Category</strong> and optional <strong>Subcategory</strong>. (1 to many). ( <strong>Could've used any example, but the medical field has lots of long words</strong>)</p> <hr> <h2><strong>Example Categories/Sub/Article Structure:</strong></h2> <ol> <li><strong>Your General Health (Category)</strong> <ul> <li><em>Natural Health <strong>(Subcategory)</em></strong> <ol> <li>Your body's immune system and why it needs help. <strong>(Article)</strong></li> <li>Are plants and herbs really the solution?</li> <li>Should I eat fortified foods?</li> </ol></li> <li>Homeopathic Medicine <ol> <li>What's homeopathic medicine?</li> </ol></li> <li><em>Healthy Eating</em> <ol> <li>Should you drink 10 cups of coffee per day?</li> <li>Are Organic Vegetables worth it?</li> <li>Is Burger King&reg; evil?</li> <li>Is "French café" or American coffee healthier?</li> </ol></li> </ul></li> <li><strong>Diseases &amp; Conditions (Category)</strong> <ul> <li><em>Auto-Immune Disorders <strong>(Subcategory)</em></strong> <ol> <li>The #1 killer of people is some disease</li> <li>How to get help </li> </ol></li> <li><em>Genetic Conditions</em> <ol> <li>Preventing Spina Bifida before pregnancy.</li> <li>Are you predisposed to live a long time?</li> </ol></li> </ul></li> <li><strong>Dr. FooBar's personal suggestions (Category)</strong> <ol> <li>My thoughts on Herbal medicine &amp; natural remedies <strong>(Article - no subcategory)</strong></li> <li>Why should you care about your health?</li> <li>It IS possible to eat right and have a good diet.</li> <li>Has bloodless surgery come of age?</li> </ol></li> </ol> <hr> <p>In a structure like this, you're going to have some <strong>LOOONG URLs</strong> if you go: /{Category}/{subcategory}/{Article Title}</p> <p>In addition, there are numerous <strong>illegal characters</strong>, like # ! ? ' é " etc.</p> <h2><strong>SO, the QUESTION(S) ARE:</strong></h2> <ol> <li>How would you handle illegal characters and Spaces? (Pros and Cons?)</li> <li>Would you handle getting this from the Database <ul> <li>In other words, would you <strong>trust the DB to find</strong> the Item, passing the title, <strong>or pull all the titles</strong> and find the key in code to get the key to pass to the Database (two calls to the database)?</li> </ul></li> </ol> <p><em>note: I always see nice pretty examples like /products/beverages/Short-Product-Name/ how about handling some ugly examples ^_^</em></p>
[ { "answer_id": 266834, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "http://www.example.com/x/category-name/subcat-name/article-name/348254863\n" }, { "answer_id": 266898, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": true, "text": "_ /article/1/Some_Article_Title_Here\n/article/1/Section/5/Section_Title_Here\n/section/19023/Section_Title_here ( == above link ) \n" }, { "answer_id": 271568, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 1, "selected": false, "text": "Route r = new Route(\"{country}/{lang}/Article/{id}/{title}/\", new NFRouteHandler(\"OneArticle\"));\nRoute r2 = new Route(\"{country}/{lang}/Section/{id}-{subid}/{title}/\", new NFRouteHandler(\"ArticlesInSubcategory\"));\nRoute r3 = new Route(\"{country}/{lang}/Section/{id}/{title}/\", new NFRouteHandler(\"ArticlesByCategory\"));\n" }, { "answer_id": 273767, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 1, "selected": false, "text": "private static string anglicized(this string urlpart) {\n string before = \"àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ\";\n string after = \"aAaAaAaAeEeEeEeEiIiIiIoOoOoOuUuUuUcC'n\";\n\n string cleaned = urlpart;\n\n for (int i = 0; i < avantConversion.Length; i++ ) {\n\n cleaned = Regex.Replace(urlpart, before[i].ToString(), after[i].ToString());\n }\n\n return cleaned;\n\n // Here's some for Spanish : ÁÉÍÑÓÚÜ¡¿áéíñóúü\"\n\n}\n string articleTitle = \"My Article about café and the letters àâäá\";\nstring cleaned = articleTitle.anglicized();\n\n// replace spaces with dashes\ncleaned = Regex.Replace( cleaned, \"[^A-Za-z0-9- ]\", \"\");\n\n// strip all illegal characters like punctuation\ncleaned = Regex.Replace( cleaned, \" +\", \"-\").ToLower();\n\n// returns \"my-article-about-cafe-and-the-letters-aaaa\"\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26931/" ]
266,761
<p>I'm pivoting data in MS SQL stored procedure. Columns which are pivoted are dynamically created using stored procedure parameter (for exampe: "location1,location2,location3,") so number of columns which will be generated is not known. Output should look like (where locations are taken from stored procedure parameter):</p> <blockquote> <p>OrderTime | Location1 | Location2 | Location3</p> </blockquote> <p>Any chance that this can be used in LINQ to SQL? When I dragged this procedure to dbml file it shows that this procedure returns int type.</p> <p>Columns I use from <code>log_sales</code> table are:</p> <ul> <li>Location (various location which I'm pivoting),</li> <li>Charge (amount of money)</li> <li>OrderTime</li> </ul> <p>Stored procedure:</p> <pre><code>CREATE PROCEDURE [dbo].[proc_StatsDay] @columns NVARCHAR(64) AS DECLARE @SQL_PVT1 NVARCHAR(512), @SQL_PVT2 NVARCHAR(512), @SQL_FULL NVARCHAR(4000); SET @SQL_PVT1 = 'SELECT OrderTime, ' + LEFT(@columns,LEN(@columns)-1) +' FROM (SELECT ES.Location, CONVERT(varchar(10), ES.OrderTime, 120),ES.Charge FROM dbo.log_sales ES ) AS D (Location,OrderTime,Charge) PIVOT (SUM (D.Charge) FOR D.Location IN ('; SET @SQL_PVT2 = ') )AS PVT ORDER BY OrderTime DESC'; SET @SQL_FULL = @SQL_PVT1 + LEFT(@columns,LEN(@columns)-1) + @SQL_PVT2; EXEC sp_executesql @SQL_FULL, N'@columns NVARCHAR(64)',@columns = @columns </code></pre> <p>In dbml <code>designer.cs</code> file my stored procedure part of code:</p> <pre><code>[Function(Name="dbo.proc_StatsDay")] public int proc_EasyDay([Parameter(DbType="NVarChar(64)")] string columns) { IExecuteResult result = this.ExecuteMethodCall(this,((MethodInfo)MethodInfo.GetCurrentMethod())), columns); return ((int)(result.ReturnValue)); } </code></pre>
[ { "answer_id": 266860, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "SELECT ES.Location, DateAdd(dd, DateDiff(dd, 0, ES.OrderTime), 0),ES.Charge\nFROM dbo.log_sales ES\n public class LogSale\n{\n public string Location {get;set;}\n public DateTime OrderDate {get;set;}\n public decimal Charge {get;set;}\n}\n List<LogSale> source = LoadData();\nvar pivot = source\n .GroupBy(ls => ls.OrderDate)\n .OrderBy(g => g.Key)\n .Select(g => new {\n Date = g.Key,\n Details = g\n .GroupBy(ls => ls.Location)\n .Select(loc => new {\n Location = loc.Key,\n Amount = loc.Sum(ls => ls.Charge)\n })\n });\n var pivot = source\n .GroupBy(ls => ls.OrderDate)\n .OrderBy(g => g.Key)\n .Select(g => new XElement(\"Date\",\n new XAttribute(\"Value\", g.key),\n g.GroupBy(ls => ls.Location)\n .Select(loc => new XElement(\"Detail\",\n new XAttribute(\"Location\", loc.Key),\n new XAttribute(\"Amount\", loc.Sum(ls => ls.Charge))\n ))\n ));\n" }, { "answer_id": 266928, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "public class DynamicResult\n{\n public DateTime OrderDate {get;set;}\n public decimal? Location1 {get;set;}\n public decimal? Location2 {get;set;}\n//..\n public decimal? Location100 {get;set;}\n}\n IEnumerable<DynamicResult> result =\n myDataContext.ExecuteQuery<DynamicResult>(commandString, param1);\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23280/" ]
266,771
<p>I'm trying to figure out a way to detect files that are not opened for editing but have nevertheless been modified locally. <code>p4 fstat</code> returns a value <code>headModTime</code> for any given file, but this is the change time in the depot, which should not be equal to the filesystem's <code>stat</code> last modified time.</p> <p>I'm hoping that there exists a more lightweight operation than backing up the original file, forcing a sync of the file, and then running a diff. Ideas?</p>
[ { "answer_id": 266813, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 6, "selected": true, "text": "p4 diff -se //myclient/... | p4 -x - edit\n" }, { "answer_id": 1013591, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 5, "selected": false, "text": ".ignore" }, { "answer_id": 13127491, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 2, "selected": false, "text": "p4 status p4 reconcile p4 status" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
266,776
<p>We have some methods that call File.Copy, File.Delete, File.Exists, etc. How can we test these methods without actually hitting the file system?</p> <p>I consider myself a unit testing n00b, so any advice is appreciated.</p>
[ { "answer_id": 266804, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 6, "selected": true, "text": "public interface IFile {\n void Copy(string source, string dest);\n void Delete(string fn);\n bool Exists(string fn);\n}\n\npublic class FileImpl : IFile {\n public virtual void Copy(string source, string dest) { File.Copy(source, dest); }\n public virtual void Delete(string fn) { File.Delete(fn); }\n public virtual bool Exists(string fn) { return File.Exists(fn); }\n}\n\n[Test]\npublic void TestMySystemCalls() {\n var filesystem = new Moq.Mock<IFile>();\n var obj = new ClassUnderTest(filesystem);\n filesystem.Expect(fs => fs.Exists(\"MyFile.txt\")).Return(true);\n obj.CheckIfFileExists(); // doesn't hit the underlying filesystem!!!\n}\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
266,777
<p>As a web developer, a number of the projects I work on fall under government umbrellas and hence are subject to <a href="http://www.section508.gov/" rel="noreferrer">508 Accessibility</a> laws, and sometimes <a href="http://www.w3.org/TR/WCAG/" rel="noreferrer">W3C accessibility</a> guidelines. To what extent can JavaScript be used while still meeting these requirements?</p> <p>Along these lines, to what extent is JavaScript, specifically AJAX and using packages like jQuery to do things such as display modal dialogues, popups, etc. supported by modern accessibility software such as JAWS, Orca, etc? In the past, the rule went something like "If it won't work in Lynx, it won't work for a screen reader." Is this still true, or has there been more progress in these areas?</p> <p>EDIT: The consensus seems to be that javascript is fine as long as there are non-javascript fallbacks, however it still seems uncertain about the support for AJAX in screen reader software. If anyone has specific experience with this, that would be most helpful.</p>
[ { "answer_id": 266833, "author": "danpickett", "author_id": 21788, "author_profile": "https://Stackoverflow.com/users/21788", "pm_score": 2, "selected": false, "text": "<script>\n $(\"#hello\").click(function(){\n alert(\"Hi\");\n });\n</script>\n<a href=\"/say_hello.htm\" id=\"hello\">Say Hello</a>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20770/" ]
266,794
<p>I'm trying to submit a form with javascript. Firefox works fine but IE complains that "Object doesn't support this property or method" on the submit line of this function:</p> <pre><code>function submitPGV(formName, action) { var gvString = ""; pgVisibilities.each(function(pair) { gvString += pair.key + ":" + pair.value + ","; }); $('pgv_input').value = gvString; var form = $(formName); form.action = action; form.submit(); } </code></pre> <p>Called here:</p> <pre><code>&lt;a href="javascript:submitPGV('ProductGroupVisibility','config/productgroupvis/save')"&gt; </code></pre> <p>Here's the form:</p> <pre><code>&lt;form id="ProductGroupVisibility" action="save" method="post"&gt; &lt;input type="hidden" name="ows_gv..PGV" id="pgv_input" value=""/&gt; &lt;/form&gt; </code></pre> <p>Any ideas?</p>
[ { "answer_id": 266822, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "alert($('ProductGroupVisibility').id)\n" }, { "answer_id": 266866, "author": "Brian", "author_id": 13264, "author_profile": "https://Stackoverflow.com/users/13264", "pm_score": 4, "selected": true, "text": "// For getting element with id you must use # \nalert( typeof( $( '#ProductGroupVisibility' )));\n" }, { "answer_id": 266889, "author": "Lance McNearney", "author_id": 25549, "author_profile": "https://Stackoverflow.com/users/25549", "pm_score": 1, "selected": false, "text": "$('#ProductGroupVisibility').submit();\n" }, { "answer_id": 266920, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "name <input type=\"submit\"> form.submit() form.foo" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34859/" ]
266,800
<p>I have a C# class the returns a List, using System.Collections.Generic Lists not F# List</p> <p>I want to iterate though the list to find a object or not find it. Here is how I would do it in C#. How would I accomplish the similar thing in F#</p> <pre><code>foreach (AperioCaseObj caseObj in CaseList) { if (caseObj.CaseId == "") { } else { } } </code></pre>
[ { "answer_id": 267047, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": true, "text": "#light\nopen System.Collections.Generic\n\nlet genList = new List<int>()\n\ngenList.Add(1)\ngenList.Add(2)\ngenList.Add(3)\n\n\nfor x in genList do\n printf \"%d\" x\n" }, { "answer_id": 267431, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 2, "selected": false, "text": "for elt in list do for caseObj in CaseList do\n if caseObj.CaseId = \"\" then\n ...\n else\n ...\n" }, { "answer_id": 267448, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 3, "selected": false, "text": "match Seq.tryfind ((=) \"\") caseList with\n None -> print_string \"didn't find it\"\n | Some s -> printfn \"found it: %s\" s\n" }, { "answer_id": 268310, "author": "simonuk", "author_id": 28136, "author_profile": "https://Stackoverflow.com/users/28136", "pm_score": 0, "selected": false, "text": "type foo = {\n id : int;\n value : string;\n}\n\nlet foos = [{id=1; value=\"one\"}; {id=2; value=\"two\"}; {id=3; value=\"three\"} ]\n\n// This will return Some foo\nList.tryfind (fun f -> f.id = 2) foos\n\n// This will return None\nList.tryfind (fun f -> f.id = 4) foos\n" }, { "answer_id": 271256, "author": "user20155", "author_id": 20155, "author_profile": "https://Stackoverflow.com/users/20155", "pm_score": 2, "selected": false, "text": "let foo() = \n match CaseList |> ResizeArray.tryfind (fun x -> x.caseObj = \"imlookingforyou\") with\n |None -> print-string \"\"notfound\n |Some(case ) -> printfn \"found %s\" case \n let foo()\n try\n let case = ResizeArray.find (fun x -> x.caseObj = \"imlookingforyou\") \n printfn \"found %s\" case \n\n with\n | _ -> print_string \"not found\"\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72123/" ]