qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
31,790
<p>How many ServiceContracts can a WCF service have?</p> <p>Specifically, since a ServiceContract is an attribute to an interface, how many interfaces can I code into one WCF web service? Is it a one-to-one?</p> <p>Does it make sense to separate the contracts across multiple web services?</p>
[ { "answer_id": 31809, "author": "Ubiguchi", "author_id": 2562, "author_profile": "https://Stackoverflow.com/users/2562", "pm_score": 4, "selected": false, "text": "[ServiceBehavior(Namespace = \"DemoService\")]\npublic class DemoService : IDemoService, IDoNothingService\n <service name=\"DemoService\" behaviorConfiguration=\"Debugging\">\n <host>\n <baseAddresses>\n <add baseAddress = \"http://localhost/DemoService.svc\" />\n </baseAddresses>\n </host>\n <endpoint \n address =\"\"\n binding=\"customBinding\"\n bindingConfiguration=\"InsecureCustom\"\n bindingNamespace=\"http://schemas.com/Demo\" contract=\"IDemoService\"/>\n <endpoint \n address =\"\"\n binding=\"customBinding\"\n bindingConfiguration=\"InsecureCustom\"\n bindingNamespace=\"http://schemas.com/Demo\" contract=\"IDoNothingService\"/>\n</service> \n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831/" ]
31,794
<p>In .net frameworks 1.1, I use </p> <pre><code>System.Configuration.ConfigurationSettings.AppSettings["name"]; </code></pre> <p>for application settings. But in .Net 2.0, it says ConfigurationSettings is obsolete and to use ConfigurationManager instead. So I swapped it out with this:</p> <pre><code>System.Configuration.ConfigurationManager.AppSettings["name"]; </code></pre> <p>The problem is, ConfigurationManager was not found in the System.Configuration namespace. I've been banging my head against the wall trying to figure out what I'm doing wrong. Anybody got any ideas?</p>
[ { "answer_id": 31838, "author": "Joda", "author_id": 1090, "author_profile": "https://Stackoverflow.com/users/1090", "pm_score": 1, "selected": false, "text": "ConfigurationSettings.AppSettings[\"name\"];\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2121/" ]
31,799
<p><strong>NOTE: <em>XMLIgnore</em> is NOT the answer!</strong></p> <p>OK, so following on from my question on <a href="https://stackoverflow.com/questions/20084/xml-serialization-and-inherited-types">XML Serialization and Inherited Types</a>, I began integrating that code into my application I am working on, stupidly thinking all will go well..</p> <p>I ran into problems with a couple of classes I have that implement <em>IEnumerable</em> and <em>ICollection&lt;T&gt;</em></p> <p>The problem with these is that when the XMLSerializer comes to serialize these, it views them as an external property, and instead of using the property we would like it to (i.e. the one with our <em>AbstractXmlSerializer</em> ) it comes here and falls over (due to the type mismatch), pretty much putting us back to square one. You cannot decorate these methods with the <strong>XmlIgnore</strong> attribute either, so we cannot stop it that way.</p> <p>My current solution is to remove the interface implementation (in this current application, its no real big deal, just made the code prettier).</p> <p><strong>Do I need to swallow my pride on this one and accept it cant be done?</strong> I know I have kinda pushed and got more out of the XmlSerializer than what was expected of it :)</p> <hr /> <h3>Edit</h3> <p>I should also add, I am currently working in framework 2.</p> <hr /> <h3>Update</h3> <p>I have accepted <a href="https://stackoverflow.com/questions/31799/preventing-xml-serialization-of-ienumerable-and-icollectiont-inherited-types#31810">lomaxx's answer</a>. In my scenario I cannot actually do this, but I do know it will work. Since their have been no other suggestions, I ended up removing the interface implementation from the code.</p>
[ { "answer_id": 31824, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 1, "selected": false, "text": " [XmlArray(\"ProviderPatientLists\")]\n [XmlArrayItem(\"File\")]\n public ProviderPatientList Files\n {\n get { return _ProviderPatientLists; }\n set\n {\n _ProviderPatientLists = value;\n }\n }\n List<PatientList>" }, { "answer_id": 1048455, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "class Target : IEnumerable<Anything>, IXmlSerializable\n{\n//...\n\npublic void ReadXml(System.Xml.XmlReader reader)\n{\n reader.ReadStartElement();\n TargetXmlAdapter toRead = (TargetXmlAdapter)new XmlSerializer(typeof(TargetXmlAdapter)).Deserialize(reader);\n reader.Read();\n\n // here: install state from TargetXmlAdapter\n}\n\npublic void WriteXml(System.Xml.XmlWriter writer)\n{\n // NOTE: TargetXmlAdapter(Target) is supposed to store this' state being subject to serialization\n new XmlSerializer(typeof(TargetXmlAdapter)).Serialize(writer, new TargetXmlAdapter(this));\n}\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
31,818
<p>How can I find out which Service Pack is installed on my copy of SQL Server?</p>
[ { "answer_id": 31820, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 5, "selected": true, "text": "-- SQL Server 2000/2005\nSELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')\n\n-- SQL Server 6.5/7.0\nSELECT @@VERSION\n" }, { "answer_id": 9741878, "author": "Amarnath", "author_id": 967638, "author_profile": "https://Stackoverflow.com/users/967638", "pm_score": 3, "selected": false, "text": "Select @@Version\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3353/" ]
31,849
<p>It seems that it is impossible to capture the keyboard event normally used for copy when running a Flex application in the browser or as an AIR app, presumably because the browser or OS is intercepting it first.</p> <p>Is there a way to tell the browser or OS to let the event through?</p> <p>For example, on an AdvancedDataGrid I have set the keyUp event to handleCaseListKeyUp(event), which calls the following function:</p> <pre><code> private function handleCaseListKeyUp(event:KeyboardEvent):void { var char:String = String.fromCharCode(event.charCode).toUpperCase(); if (event.ctrlKey &amp;&amp; char == "C") { trace("Ctrl-C"); copyCasesToClipboard(); return; } if (!event.ctrlKey &amp;&amp; char == "C") { trace("C"); copyCasesToClipboard(); return; } // Didn't match event to capture, just drop out. trace("charCode: " + event.charCode); trace("char: " + char); trace("keyCode: " + event.keyCode); trace("ctrlKey: " + event.ctrlKey); trace("altKey: " + event.altKey); trace("shiftKey: " + event.shiftKey); } </code></pre> <p>When run, I can never get the release of the "C" key while also pressing the command key (which shows up as KeyboardEvent.ctrlKey). I get the following trace results:</p> <pre><code>charCode: 0 char: keyCode: 17 ctrlKey: false altKey: false shiftKey: false </code></pre> <p>As you can see, the only event I can capture is the release of the command key, the release of the "C" key while holding the command key isn't even sent.</p> <p>Has anyone successfully implemented standard copy and paste keyboard handling?</p> <p>Am I destined to just use the "C" key on it's own (as shown in the code example) or make a copy button available?</p> <p>Or do I need to create the listener manually at a higher level and pass the event down into my modular application's guts?</p>
[ { "answer_id": 48427, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 0, "selected": false, "text": "event.ctrlKey && event.keyCode = Keyboard.C event.charCode == 67 charCode keyCode 3 charCode 3 keyCode" }, { "answer_id": 426982, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " private var _ctrlHoldFlag:Boolean = false; \n\n // Do something if CTRL was held down and C was pressed\n // Otherwise release the ctrl flag if it was pressed\n public function onKey_Up(event:KeyboardEvent):void { \n var keycode_c:uint = 67;\n\n if (_ctrlHoldFlag && event.keyCode == keycode_c)\n {\n //do whatever you need on CTRL-C\n }\n\n if (event.ctrlKey)\n {\n _ctrlHoldFlag = false;\n }\n }\n\n // Track ctrl key down press \n public function onKey_Down(event:KeyboardEvent):void\n {\n if (event.ctrlKey)\n {\n _ctrlHoldFlag = true;\n }\n }\n" }, { "answer_id": 5759982, "author": "Pedro Andrade", "author_id": 715451, "author_profile": "https://Stackoverflow.com/users/715451", "pm_score": 0, "selected": false, "text": " protected var lastKeys:Array;\n this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler, false, 0, true);\n this.stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler, false, 0, true);\n\n private function getCmdKey(ev:KeyboardEvent):Boolean {\n this.lastKeys.push(ev);\n this.lastKeys = this.lastKeys.splice(Math.max(0, this.lastKeys.length-3), 3);\n\n if (this.lastKeys.length < 3) return false;\n\n if (ev.keyCode != 15 && ev.type == KeyboardEvent.KEY_UP) {\n var firstKey:KeyboardEvent = this.lastKeys[0] as KeyboardEvent;\n var secondKey:KeyboardEvent = this.lastKeys[1] as KeyboardEvent;\n\n if (firstKey.keyCode == 15 && firstKey.type == KeyboardEvent.KEY_DOWN &&\n secondKey.keyCode == 15 && secondKey.type == KeyboardEvent.KEY_UP) {\n return true;\n }\n }\n\n return false;\n }\n\n private function keyHandler(ev:KeyboardEvent):void {\n var cmdKey:Boolean = this.getCmdKey(ev.clone() as KeyboardEvent);\n var ctrlKey:Boolean = ev.ctrlKey || cmdKey;\n\n if (ctrlKey) {\n if (ev.keyCode == 65) { \n // ctrl + \"a\"-- select all!\n }\n }\n }\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3023/" ]
31,865
<p>I know this might be a no-brainer, but please read on.</p> <p>I also know it's generally not considered a good idea, maybe the worst, to let a browser run and interact with local apps, even in an intranet context.</p> <p>We use Citrix for home-office, and people really like it. Now, they would like the same kind of environment at work, a nice page where every important application/document/folder is nicely arranged and classified in an orderly fashion. These folks are not particularly tech savvy; I don't even consider thinking that they could understand the difference between remote delivered applications and local ones.</p> <p>So, I've been asked if it's possible. Of course, it is, with IE's good ol' ActiveX controls. And I even made a working prototype (that's where it hurts).</p> <p>But now, I doubt. Isn't it madness to allow such 'dangerous' ActiveX controls, even in the '<em>local intranet</em>' zone? People will use the same browser to surf the web, can I fully trust IE? Isn't there a risk that Microsoft would just disable those controls in future updates/versions? What if a website, or any kind of malware, just put another site on the trust list? With that extent of control, you could as well uninstall every protection and just run amok 'till you got hanged by the IT dept.</p> <p>I'm about to confront my superiors with the fact that, even if they saw it is doable, it would be a very bad thing. So I'm desperately in need of good and strong arguments, because "<em>let's don't</em>" won't do it.</p> <p>Of course, if there is nothing to be scared of, that'll be nice too. But I strongly doubt that.</p>
[ { "answer_id": 33689, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "<a href=\"dial#1800-234-567\">Call John Smith</a>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2452/" ]
31,867
<p>While I've seen rare cases where <em>private</em> inheritance was needed, I've never encountered a case where <em>protected</em> inheritance is needed. Does someone have an example?</p>
[ { "answer_id": 82215, "author": "Antti Kissaniemi", "author_id": 2948, "author_profile": "https://Stackoverflow.com/users/2948", "pm_score": 1, "selected": false, "text": "derivedFunction() class SomeImplementationClass\n{\nprotected:\n void service() {\n derivedFunction();\n }\n\n virtual void derivedFunction() = 0; \n\n // virtual destructor etc\n};\n\nclass Derived : private SomeImplementationClass\n{\n void someFunction() {\n service();\n }\n\n virtual void derivedFunction() {\n // ...\n }\n\n // ...\n};\n Base::service() Derived::someFunction() Base" }, { "answer_id": 280453, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "struct base { \n virtual ~base() {} \n virtual base & getBase() = 0;\n}; \n\nstruct d1 : private /* protected */ base { \n virtual base & getBase() { \n return this; \n } \n}; \n\nstruct d2 : private /* protected */ d1 {\n virtual d1 & getBase () { \n return this; \n } \n}; \n d2 d2 d1 base covariance std::ostream getStream std::ostream& std::ostream& d2::getStream() {\n this->width(10);\n return *this;\n}\n\nlogger.getStream() << \"we are padded\";\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2638/" ]
31,868
<p>What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes?</p> <p><strong>Following the two initial answers...</strong></p> <ul> <li><p>We definitely need to use the Web Service layer as we will be making these calls from remote client applications.</p></li> <li><p>The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method.</p></li> </ul> <p><Blockquote> There is additionally a web service to upload files, painful but works all the time. </Blockquote></p> <p>Are you referring to the “Copy” service? We have been successful with this service’s <code>CopyIntoItems</code> method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API?</p> <p>I have posted our code as a suggested answer.</p>
[ { "answer_id": 34274, "author": "Andy McCluggage", "author_id": 3362, "author_profile": "https://Stackoverflow.com/users/3362", "pm_score": 5, "selected": true, "text": "public static void UploadFile2007(string destinationUrl, byte[] fileData)\n{\n // List of desination Urls, Just one in this example.\n string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) };\n\n // Empty Field Information. This can be populated but not for this example.\n SharePoint2007CopyService.FieldInformation information = new \n SharePoint2007CopyService.FieldInformation();\n SharePoint2007CopyService.FieldInformation[] info = { information };\n\n // To receive the result Xml.\n SharePoint2007CopyService.CopyResult[] result;\n\n // Create the Copy web service instance configured from the web.config file.\n SharePoint2007CopyService.CopySoapClient\n CopyService2007 = new CopySoapClient(\"CopySoap\");\n CopyService2007.ClientCredentials.Windows.ClientCredential = \n CredentialCache.DefaultNetworkCredentials;\n CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel = \n System.Security.Principal.TokenImpersonationLevel.Delegation;\n\n CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result);\n\n if (result[0].ErrorCode != SharePoint2007CopyService.CopyErrorCode.Success)\n {\n // ...\n }\n}\n" }, { "answer_id": 44915, "author": "Jim Harte", "author_id": 4544, "author_profile": "https://Stackoverflow.com/users/4544", "pm_score": 3, "selected": false, "text": "WebClient webclient = new WebClient();\nwebclient.Credentials = new NetworkCredential(_userName, _password, _domain);\nwebclient.UploadFile(remoteFileURL, \"PUT\", FilePath);\nwebclient.Dispose();\n" }, { "answer_id": 3763626, "author": "Luke Hutton", "author_id": 368552, "author_profile": "https://Stackoverflow.com/users/368552", "pm_score": 3, "selected": false, "text": "public static void UploadFile(byte[] fileData) {\n var copy = new Copy {\n Url = \"http://servername/sitename/_vti_bin/copy.asmx\", \n UseDefaultCredentials = true\n };\n\n string destinationUrl = \"http://servername/sitename/doclibrary/filename\";\n string[] destinationUrls = {destinationUrl};\n\n var info1 = new FieldInformation\n {\n DisplayName = \"Title\", \n InternalName = \"Title\", \n Type = FieldType.Text, \n Value = \"New Title\"\n };\n\n FieldInformation[] info = {info1};\n var copyResult = new CopyResult();\n CopyResult[] copyResults = {copyResult};\n\n copy.CopyIntoItems(\n destinationUrl, destinationUrls, info, fileData, out copyResults);\n}\n CopyIntoItems Path.GetFileName(destinationUrl)" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
31,870
<p>What is the best way to include an html entity in XSLT?</p> <pre><code>&lt;xsl:template match="/a/node"&gt; &lt;xsl:value-of select="."/&gt; &lt;xsl:text&gt;&amp;nbsp;&lt;/xsl:text&gt; &lt;/xsl:template&gt; </code></pre> <p>this one returns a <strong>XsltParseError</strong></p>
[ { "answer_id": 31873, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 8, "selected": true, "text": "<xsl:text disable-output-escaping=\"yes\"><![CDATA[&nbsp;]]></xsl:text>\n <!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp \"&#160;\"> ]>\n &#160; &nbsp;" }, { "answer_id": 31878, "author": "Tom Lokhorst", "author_id": 2597, "author_profile": "https://Stackoverflow.com/users/2597", "pm_score": 3, "selected": false, "text": "&nbsp; &nbsp; &#160;" }, { "answer_id": 31886, "author": "Pierre Spring", "author_id": 1532, "author_profile": "https://Stackoverflow.com/users/1532", "pm_score": 4, "selected": false, "text": "<xsl:text disable-output-escaping=\"yes\">&amp;nbsp;</xsl:text>\n" }, { "answer_id": 31894, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 3, "selected": false, "text": "lt gt apos quot amp" }, { "answer_id": 32161, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 3, "selected": false, "text": "&#160" }, { "answer_id": 7613975, "author": "Sergey Ushakov", "author_id": 972463, "author_profile": "https://Stackoverflow.com/users/972463", "pm_score": 5, "selected": false, "text": "<!DOCTYPE stylesheet [\n <!ENTITY % w3centities-f PUBLIC \"-//W3C//ENTITIES Combined Set//EN//XML\"\n \"http://www.w3.org/2003/entities/2007/w3centities-f.ent\">\n %w3centities-f;\n]>\n...\n<xsl:text>&nbsp;&minus;30&deg;</xsl:text>\n <xsl:text disable-output-escaping=\"yes\"> &nbsp; <xsl:output method=\"text\"> <!DOCTYPE ... <!ENTITY ... xsl:output" }, { "answer_id": 8993297, "author": "SixOThree", "author_id": 99774, "author_profile": "https://Stackoverflow.com/users/99774", "pm_score": 1, "selected": false, "text": "<xsl:text> </xsl:text> <xsl:text>#x20;</xsl:text>" }, { "answer_id": 14543587, "author": "Dave", "author_id": 463960, "author_profile": "https://Stackoverflow.com/users/463960", "pm_score": 0, "selected": false, "text": " <xsl:text disable-output-escaping=\"yes\">&amp;#160;</xsl:text>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1532/" ]
31,871
<p>Ok, I have a strange exception thrown from my code that's been bothering me for ages.</p> <pre><code>System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() </code></pre> <p>MSDN isn't terribly helpful on this : <a href="http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx</a> and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. </p> <p>I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it.</p> <p>The code runs in a separate background thread, the method starts :</p> <pre><code>public virtual void Startup() { TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port)); serverSocket.Start(); </code></pre> <p>then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically:</p> <pre><code> while (( socket = serverSocket.AcceptTcpClient()) !=null) //Funny exception here { connectionHandler = new ConnectionHandler(socket, mappingStrategy); pool.AddJob(connectionHandler); } } </code></pre> <p>From there, the <code>pool</code> has it's own threads that take care of each job in it's own thread, separately.</p> <p>My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? </p> <hr> <p>Well, I do think some other thread is closing the socket, but it's certainly not from my code. What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. </p> <p>Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods?</p>
[ { "answer_id": 261393, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "serverSocket.Stop() Dispose try\n{\n //...\n}\ncatch (SocketException socketEx)\n{ \n if (_disposed)\n ar.SetAsCompleted(null, false); //exception because listener stopped (disposed), ignore exception\n else\n ar.SetAsCompleted(socketEx, false);\n}\n _disposed" }, { "answer_id": 8397129, "author": "Nikolaus Very Permana", "author_id": 961567, "author_profile": "https://Stackoverflow.com/users/961567", "pm_score": 3, "selected": false, "text": "private void closinginvoker(string dummy)\n {\n if (InvokeRequired)\n {\n this.Invoke(new Action<string>(closinginvoker), new object[] { dummy });\n return;\n }\n t_listen.Abort();\n client_flag = true;\n c_idle.Close();\n listener1.Stop();\n }\n" }, { "answer_id": 51034620, "author": "SimonNZ", "author_id": 7186618, "author_profile": "https://Stackoverflow.com/users/7186618", "pm_score": 0, "selected": false, "text": "string path = \"Reasonably large file.dat\";\nint bufferSize = 1024;\nbyte[] buffer = new byte[bufferSize];\nSystem.Net.HttpWebRequest req = (HttpWebRequest)System.Net.HttpWebRequest.Create(\"Some URL\");\nreq.Method = \"PUT\";\nreq.Timeout = 3000; //3 seconds, small timeout to demonstrate\nlong length = new System.IO.FileInfo(path).Length;\nusing (FileStream input = File.OpenRead(path))\n{\n using (Stream output = req.GetRequestStream())\n {\n long remaining = length;\n int bytesRead = 0;\n while ((bytesRead = input.Read(buffer, 0, (int)Math.Min(remaining, (decimal)bufferSize))) > 0)\n {\n output.Write(buffer, 0, bytesRead);\n remaining -= bytesRead;\n }\n output.Close();\n }\ninput.Close();\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
31,875
<p>There seem to be many ways to define <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singletons</a> in Python. Is there a consensus opinion on Stack&nbsp;Overflow?</p>
[ { "answer_id": 31884, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 2, "selected": false, "text": "class Singleton:\n __single = None\n def __init__( self ):\n if Singleton.__single:\n raise Singleton.__single\n Singleton.__single = self\n" }, { "answer_id": 32487, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 7, "selected": false, "text": "class Borg:\n __shared_state = {}\n def __init__(self):\n self.__dict__ = self.__shared_state\n" }, { "answer_id": 33201, "author": "Acuminate", "author_id": 2482, "author_profile": "https://Stackoverflow.com/users/2482", "pm_score": 6, "selected": false, "text": "class Singleton(type):\n def __init__(cls, name, bases, dict):\n super(Singleton, cls).__init__(name, bases, dict)\n cls.instance = None \n\n def __call__(cls,*args,**kw):\n if cls.instance is None:\n cls.instance = super(Singleton, cls).__call__(*args, **kw)\n return cls.instance\n\nclass MyClass(object):\n __metaclass__ = Singleton\n" }, { "answer_id": 35080, "author": "David Locke", "author_id": 1447, "author_profile": "https://Stackoverflow.com/users/1447", "pm_score": 4, "selected": false, "text": "class Foo:\n x = 1\n \n @classmethod\n def increment(cls, y=1):\n cls.x += y\n" }, { "answer_id": 1314783, "author": "u0b34a0f6ae", "author_id": 137317, "author_profile": "https://Stackoverflow.com/users/137317", "pm_score": 5, "selected": false, "text": "DataController _data_controller = None\ndef GetDataController():\n global _data_controller\n if _data_controller is None:\n _data_controller = DataController()\n return _data_controller\n" }, { "answer_id": 1810367, "author": "jojo", "author_id": 287210, "author_profile": "https://Stackoverflow.com/users/287210", "pm_score": 8, "selected": false, "text": "__new__ class Singleton(object):\n _instance = None\n def __new__(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = super(Singleton, cls).__new__(\n cls, *args, **kwargs)\n return cls._instance\n\n\nif __name__ == '__main__':\n s1 = Singleton()\n s2 = Singleton()\n if (id(s1) == id(s2)):\n print \"Same\"\n else:\n print \"Different\"\n" }, { "answer_id": 1922376, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "class Singleton(object[,...]):\n\n staticVar1 = None\n staticVar2 = None\n\n def __init__(self):\n if self.__class__.staticVar1==None :\n # create class instance variable for instantiation of class\n # assign class instance variable values to class static variables\n else:\n # assign class static variable values to class instance variables\n" }, { "answer_id": 2752280, "author": "Wei", "author_id": 330650, "author_profile": "https://Stackoverflow.com/users/330650", "pm_score": 6, "selected": false, "text": "def singleton(cls):\n instances = {}\n def getinstance():\n if cls not in instances:\n instances[cls] = cls()\n return instances[cls]\n return getinstance\n\n@singleton\nclass MyClass:\n ...\n" }, { "answer_id": 6843917, "author": "Mark Evans", "author_id": 228670, "author_profile": "https://Stackoverflow.com/users/228670", "pm_score": 3, "selected": false, "text": "class NothingSpecial:\n pass\n\n_the_one_and_only = None\n\ndef TheOneAndOnly():\n global _the_one_and_only\n if not _the_one_and_only:\n _the_one_and_only = NothingSpecial()\n return _the_one_and_only\n class NothingSpecial:\n pass\n\nTHE_ONE_AND_ONLY = NothingSpecial()\n" }, { "answer_id": 7346105, "author": "Paul Manta", "author_id": 627005, "author_profile": "https://Stackoverflow.com/users/627005", "pm_score": 9, "selected": false, "text": "Instance @Singleton\nclass Foo:\n def __init__(self):\n print 'Foo created'\n\nf = Foo() # Error, this isn't how you get the instance of a singleton\n\nf = Foo.instance() # Good. Being explicit is in line with the Python Zen\ng = Foo.instance() # Returns already created instance\n\nprint f is g # True\n class Singleton:\n \"\"\"\n A non-thread-safe helper class to ease implementing singletons.\n This should be used as a decorator -- not a metaclass -- to the\n class that should be a singleton.\n\n The decorated class can define one `__init__` function that\n takes only the `self` argument. Also, the decorated class cannot be\n inherited from. Other than that, there are no restrictions that apply\n to the decorated class.\n\n To get the singleton instance, use the `instance` method. Trying\n to use `__call__` will result in a `TypeError` being raised.\n\n \"\"\"\n\n def __init__(self, decorated):\n self._decorated = decorated\n\n def instance(self):\n \"\"\"\n Returns the singleton instance. Upon its first call, it creates a\n new instance of the decorated class and calls its `__init__` method.\n On all subsequent calls, the already created instance is returned.\n\n \"\"\"\n try:\n return self._instance\n except AttributeError:\n self._instance = self._decorated()\n return self._instance\n\n def __call__(self):\n raise TypeError('Singletons must be accessed through `instance()`.')\n\n def __instancecheck__(self, inst):\n return isinstance(inst, self._decorated)\n" }, { "answer_id": 7927702, "author": "mkm", "author_id": 246621, "author_profile": "https://Stackoverflow.com/users/246621", "pm_score": 0, "selected": false, "text": "class singleton(object):\n \"\"\"Singleton decorator.\"\"\"\n\n def __init__(self, cls):\n self.__dict__['cls'] = cls\n\n instances = {}\n\n def __call__(self):\n if self.cls not in self.instances:\n self.instances[self.cls] = self.cls()\n return self.instances[self.cls]\n\n def __getattr__(self, attr):\n return getattr(self.__dict__['cls'], attr)\n\n def __setattr__(self, attr, value):\n return setattr(self.__dict__['cls'], attr, value)\n" }, { "answer_id": 8296319, "author": "Tiezhen", "author_id": 1052083, "author_profile": "https://Stackoverflow.com/users/1052083", "pm_score": 2, "selected": false, "text": "def getSystemContext(contextObjList=[]):\n if len( contextObjList ) == 0:\n contextObjList.append( Context() )\n pass\n return contextObjList[0]\n\nclass Context(object):\n # Anything you want here\n" }, { "answer_id": 9403992, "author": "Matt Alcock", "author_id": 200983, "author_profile": "https://Stackoverflow.com/users/200983", "pm_score": 4, "selected": false, "text": "def singleton(cls):\n instances = {}\n def getinstance():\n if cls not in instances:\n instances[cls] = cls()\n return instances[cls]\n return getinstance\n\n@singleton\nclass MyClass:\n ...\n" }, { "answer_id": 9489387, "author": "Mychot sad", "author_id": 1126139, "author_profile": "https://Stackoverflow.com/users/1126139", "pm_score": 2, "selected": false, "text": "# Peppelinux's cached singleton\nclass Singleton_group(object):\n __instances_args_dict = {}\n def __new__(cls, *args, **kwargs):\n if not cls.__instances_args_dict.get((cls.__name__, args, str(kwargs))):\n cls.__instances_args_dict[(cls.__name__, args, str(kwargs))] = super(Singleton_group, cls).__new__(cls, *args, **kwargs)\n return cls.__instances_args_dict.get((cls.__name__, args, str(kwargs)))\n\n\n# It's a dummy real world use example:\nclass test(Singleton_group):\n def __init__(self, salute):\n self.salute = salute\n\na = test('bye')\nb = test('hi')\nc = test('bye')\nd = test('hi')\ne = test('goodbye')\nf = test('goodbye')\n\nid(a)\n3070148780L\n\nid(b)\n3070148908L\n\nid(c)\n3070148780L\n\nb == d\nTrue\n\n\nb._Singleton_group__instances_args_dict\n\n{('test', ('bye',), '{}'): <__main__.test object at 0xb6fec0ac>,\n ('test', ('goodbye',), '{}'): <__main__.test object at 0xb6fec32c>,\n ('test', ('hi',), '{}'): <__main__.test object at 0xb6fec12c>}\n" }, { "answer_id": 11517201, "author": "Brian Bruggeman", "author_id": 631199, "author_profile": "https://Stackoverflow.com/users/631199", "pm_score": 5, "selected": false, "text": "class Singleton(object):\n def __new__(cls, *args, **kwds):\n it = cls.__dict__.get(\"__it__\")\n if it is not None:\n return it\n cls.__it__ = it = object.__new__(cls)\n it.init(*args, **kwds)\n return it\n def init(self, *args, **kwds):\n pass\n class Singleton(object):\n \"\"\"Use to create a singleton\"\"\"\n def __new__(cls, *args, **kwds):\n \"\"\"\n >>> s = Singleton()\n >>> p = Singleton()\n >>> id(s) == id(p)\n True\n \"\"\"\n it_id = \"__it__\"\n # getattr will dip into base classes, so __dict__ must be used\n it = cls.__dict__.get(it_id, None)\n if it is not None:\n return it\n it = object.__new__(cls)\n setattr(cls, it_id, it)\n it.init(*args, **kwds)\n return it\n\n def init(self, *args, **kwds):\n pass\n\n\nclass A(Singleton):\n pass\n\n\nclass B(Singleton):\n pass\n\n\nclass C(A):\n pass\n\n\nassert A() is A()\nassert B() is B()\nassert C() is C()\nassert A() is not B()\nassert C() is not B()\nassert C() is not A()\n class Bus(Singleton):\n def init(self, label=None, *args, **kwds):\n self.label = label\n self.channels = [Channel(\"system\"), Channel(\"app\")]\n ...\n" }, { "answer_id": 11965327, "author": "Volodymyr Pavlenko", "author_id": 655500, "author_profile": "https://Stackoverflow.com/users/655500", "pm_score": 2, "selected": false, "text": "class Singeltone(type):\n instances = dict()\n\n def __call__(cls, *args, **kwargs):\n if cls.__name__ not in Singeltone.instances: \n Singeltone.instances[cls.__name__] = type.__call__(cls, *args, **kwargs)\n return Singeltone.instances[cls.__name__]\n\n\nclass Test(object):\n __metaclass__ = Singeltone\n\n\ninst0 = Test()\ninst1 = Test()\nprint(id(inst1) == id(inst0))\n" }, { "answer_id": 12850496, "author": "Lambda Fairy", "author_id": 617159, "author_profile": "https://Stackoverflow.com/users/617159", "pm_score": 5, "selected": false, "text": "def singleton(cls):\n obj = cls()\n # Always return the same object\n cls.__new__ = staticmethod(lambda cls: obj)\n # Disable __init__\n try:\n del cls.__init__\n except AttributeError:\n pass\n return cls\n __new__ @singleton\nclass Duck(object):\n pass\n\nif Duck() is Duck():\n print \"It works!\"\nelse:\n print \"It doesn't work!\"\n object" }, { "answer_id": 14280940, "author": "neu-rah", "author_id": 1329075, "author_profile": "https://Stackoverflow.com/users/1329075", "pm_score": 2, "selected": false, "text": "class void:pass\na = void();\na.__class__ = Singleton\n a class Singleton:\n def __new__(cls): raise AssertionError # Singletons can't have instances\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3363/" ]
31,913
<p>I'm sorry if my question is so long and technical but I think it's so important other people will be interested about it</p> <p>I was looking for a way to separate clearly some softwares internals from their representation in c++</p> <p>I have a generic parameter class (to be later stored in a container) that can contain any kind of value with the the boost::any class</p> <p>I have a base class (roughly) of this kind (of course there is more stuff)</p> <pre><code>class Parameter { public: Parameter() template typename&lt;T&gt; T GetValue() const { return any_cast&lt;T&gt;( _value ); } template typename&lt;T&gt; void SetValue(const T&amp; value) { _value = value; } string GetValueAsString() const = 0; void SetValueFromString(const string&amp; str) const = 0; private: boost::any _value; } </code></pre> <p>There are two levels of derived classes: The first level defines the type and the conversion to/from string (for example ParameterInt or ParameterString) The second level defines the behaviour and the real creators (for example deriving ParameterAnyInt and ParameterLimitedInt from ParameterInt or ParameterFilename from GenericString)</p> <p>Depending on the real type I would like to add external function or classes that operates depending on the specific parameter type without adding virtual methods to the base class and without doing strange casts</p> <p>For example I would like to create the proper gui controls depending on parameter types:</p> <pre><code>Widget* CreateWidget(const Parameter&amp; p) </code></pre> <p>Of course I cannot understand real Parameter type from this unless I use RTTI or implement it my self (with enum and switch case), but this is not the right OOP design solution, you know.</p> <p>The classical solution is the Visitor design pattern <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Visitor_pattern</a></p> <p>The problem with this pattern is that I have to know in advance which derived types will be implemented, so (putting together what is written in wikipedia and my code) we'll have sort of: </p> <pre><code>struct Visitor { virtual void visit(ParameterLimitedInt&amp; wheel) = 0; virtual void visit(ParameterAnyInt&amp; engine) = 0; virtual void visit(ParameterFilename&amp; body) = 0; }; </code></pre> <p>Is there any solution to obtain this behaviour in any other way without need to know in advance all the concrete types and without deriving the original visitor?</p> <hr> <p><strong>Edit:</strong> <a href="https://stackoverflow.com/q/31913">Dr. Pizza's solution seems the closest to what I was thinking</a>, but the problem is still the same and the method is actually relying on dynamic_cast, that I was trying to avoid as a kind of (even if weak) RTTI method</p> <p>Maybe it is better to think to some solution without even citing the visitor Pattern and clean our mind. The purpose is just having the function such:</p> <pre><code>Widget* CreateWidget(const Parameter&amp; p) </code></pre> <p>behave differently for each "concrete" parameter without losing info on its type </p>
[ { "answer_id": 33452, "author": "genix", "author_id": 2714, "author_profile": "https://Stackoverflow.com/users/2714", "pm_score": 0, "selected": false, "text": "class Visitor\n{\npublic:\n template< class T > void visit( const T& param ) const\n {\n assert( false && \"this parameter type not specialised in the visitor\" );\n }\n void visit( const ParameterLimitedInt& ) const; // specialised implementations...\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3373/" ]
31,919
<p>I'm comparing it Java where you can start your application server in debug mode, then attach your IDE to the server. And you can change your code "on the fly" without restarting the server. As long as your changes don't affect any method signatures or fields you can just hit recompile for a class and the application server (servlet container) will reload the class.</p> <p>I suppose this is impossible in ASP.NET since all classes are packed into assemblies and you cannot unload/reload assemblies, can you ?</p> <p>So when you have an .aspx page and an assembly deployed to GAC and your codebehind changes you have to redeploy the assembly and reset IIS. I'm talking about Sharepoint applications in particular and I'm not sure whether you have to do iisreset for private assemblies but I guess you have too.</p> <p>So the best way to debug aspx pages with code behind I guess would be to get rid of the codebehind for the time of active debugging and move into the page, then when it is more or less working move it back to codebehind. (This would be applicable only for application pages in Sharepoint, site pages don't allow inline code )</p> <p>How do you approach debugging of your ASP.NET applications to make it less time consuming?</p>
[ { "answer_id": 31984, "author": "Artem Tikhomirov", "author_id": 2313, "author_profile": "https://Stackoverflow.com/users/2313", "pm_score": 2, "selected": false, "text": "<system.web>\n ...\n <trust level=\"WSS_Medium\" originUrl=\"\" />\n ...\n</system.web>\n" }, { "answer_id": 40373, "author": "Matt Bishop", "author_id": 4301, "author_profile": "https://Stackoverflow.com/users/4301", "pm_score": 2, "selected": false, "text": "iisapp.vbs /a \"App Pool Name\" /r iisreset" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
31,931
<p>I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.</p> <p>It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way. </p> <p>What's the simplest way of doing this?</p> <p>[Edit: Just to avoid confusion in an answer below, this is a <strong>JavaScript</strong> question, not a Java one.]</p>
[ { "answer_id": 31938, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": 3, "selected": false, "text": "var today = new Date();\nvar yesterday = new Date().setDate(today.getDate() -1);\n" }, { "answer_id": 31939, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 6, "selected": true, "text": "var d = new Date();\nd.setDate(d.getDate() - 1);\n\nconsole.log(d);" }, { "answer_id": 31943, "author": "Philip Reynolds", "author_id": 1087, "author_profile": "https://Stackoverflow.com/users/1087", "pm_score": 2, "selected": false, "text": "getDate()-1 var day = new Date( \"January 1 2008\" );\nday.setDate(day.getDate() -1);\nalert(day);\n" }, { "answer_id": 357000, "author": "John Griffiths", "author_id": 24765, "author_profile": "https://Stackoverflow.com/users/24765", "pm_score": 1, "selected": false, "text": "setDate(dayValue) dayValue" }, { "answer_id": 20407757, "author": "adrian7", "author_id": 319150, "author_profile": "https://Stackoverflow.com/users/319150", "pm_score": 2, "selected": false, "text": "origDate = new Date();\ndecrementedDate = new Date(origDate.getTime() - (86400 * 1000));\n\nconsole.log(decrementedDate);\n" }, { "answer_id": 25114400, "author": "Sunil B N", "author_id": 1641714, "author_profile": "https://Stackoverflow.com/users/1641714", "pm_score": 3, "selected": false, "text": " day.setDate(day.getDate() -1); //will be wrong\n var d = new Date(2014,9,19);\nd.setDate(d.getDate()-1);// will return Oct 17\n var n = day.getTime();\nn -= 86400000;\nday = new Date(n); //works fine for everything\n" }, { "answer_id": 49706911, "author": "Aliaksandr Sushkevich", "author_id": 7600492, "author_profile": "https://Stackoverflow.com/users/7600492", "pm_score": 1, "selected": false, "text": "const date = moment().subtract(1, 'day')\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/916/" ]
31,935
<p>I'm sure this is easy but I can't figure it out:</p> <p>I have an ASP.NET page with some UpdatePanels on it. I want the page to <em>completely</em> load with some 'Please wait' text in the UpdatePanels. Then once the page is <em>completely loaded</em> I want to call a code-behind function to update the UpdatePanel.</p> <p>Any ideas as to what combination of Javascript and code-behind I need to implement this idea?</p> <p>SAL</p> <p>PS: I've tried putting my function call in the Page_Load but then code is run <em>before</em> the page is delivered and, as the function I want to run takes some time, the page simply takes too long to load up.</p>
[ { "answer_id": 33161, "author": "SAL", "author_id": 3099, "author_profile": "https://Stackoverflow.com/users/3099", "pm_score": 3, "selected": false, "text": " <%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"AJAXPostLoadCall._Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n<head runat=\"server\">\n <title>Untitled Page</title>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <h2>And now for a magic trick...</h2>\n <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnablePartialRendering=\"True\">\n </asp:ScriptManager>\n <div>\n <asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\">\n <ContentTemplate>\n <asp:Timer ID=\"Timer1\" runat=\"server\" Interval=\"2000\" ontick=\"Timer1_Tick\" />\n <asp:Label ID=\"Label1\" runat=\"server\">Something magic is about to happen...</asp:Label>\n </ContentTemplate>\n </asp:UpdatePanel>\n\n </div>\n </form>\n</body>\n</html>\n using System;\nusing System.Collections;\nusing System.Configuration;\nusing System.Data;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.HtmlControls;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\nusing System.Xml.Linq;\n\nnamespace AJAXPostLoadCall\n{\n public partial class _Default : System.Web.UI.Page\n {\n\n protected void Page_Load(object sender, EventArgs e)\n {\n }\n\n public void DoMagic()\n {\n Label1.Text = \"Abracadabra\";\n }\n\n protected void Timer1_Tick(object sender, EventArgs e)\n {\n // Do the magic, then disable the timer\n DoMagic();\n Timer1.Enabled = false;\n }\n\n }\n}\n" }, { "answer_id": 1079187, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<asp:UpdateProgress AssociatedUpdatePanelID=\"UpdatePanel1\" ID=\"UpdateProgress1\" runat=\"server\">\n <ProgressTemplate>\n <div class=\"mystyleclass\">\n Please Wait...\n </div>\n </ProgressTemplate>\n</asp:UpdateProgress>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/31935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3099/" ]
32,000
<p>I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace. </p> <p>I'm using <code>SqlConnection</code> for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.</p>
[ { "answer_id": 32005, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "using (var conn = new SqlConnection(yourConnectionString))\n{\n var cmd = new SqlCommand(\"insert into Foo values (@bar)\", conn);\n cmd.Parameters.AddWithValue(\"@bar\", 17);\n conn.Open();\n cmd.ExecuteNonQuery();\n}\n" }, { "answer_id": 32006, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "using (SqlConnection myConnection new SqlConnection(\"Your connection string\")) \n{ \n SqlCommand myCommand = new SqlCommand(\"INSERT INTO ... VALUES ...\", myConnection); \n myConnection.Open(); \n myCommand.ExecuteNonQuery(); \n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344/" ]
32,001
<p>I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal. </p> <p>If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds. E.g. the timer should be able to do something like:</p> <pre><code>Timer timer = new Timer(); timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X) //At some point between 0 and 5000 ms... setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y). </code></pre> <p>I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again.</p> <p>The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: </p> <pre><code>timer.stop(); timer = new Timer(8000, ActionListener); timer.start(); </code></pre> <p>Is there an easier way??</p>
[ { "answer_id": 32047, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 1, "selected": false, "text": "Timer/TimerTask java.util.concurrent.ScheduledThreadPoolExecutor" }, { "answer_id": 32057, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 7, "selected": true, "text": "Timer ScheduledThreadPoolExecutor Executors .newSingleThreadScheduledExecutor() Timer schedule() ScheduledFuture Timer ScheduledThreadPoolExecutor java.util.concurrent ScheduledThreadPoolExecutor Timer TimerTask TimerTask Runnable ScheduledThreadPoolExecutor Timer" }, { "answer_id": 32073, "author": "David Sykes", "author_id": 3154, "author_profile": "https://Stackoverflow.com/users/3154", "pm_score": 4, "selected": false, "text": "Timer import java.util.Timer;\nimport java.util.TimerTask;\n\npublic class ReschedulableTimer extends Timer\n{\n private Runnable task;\n private TimerTask timerTask;\n\n public void schedule(Runnable runnable, long delay)\n {\n task = runnable;\n timerTask = new TimerTask()\n {\n @Override\n public void run()\n {\n task.run();\n }\n };\n this.schedule(timerTask, delay);\n }\n\n public void reschedule(long delay)\n {\n timerTask.cancel();\n timerTask = new TimerTask()\n {\n @Override\n public void run()\n {\n task.run();\n }\n };\n this.schedule(timerTask, delay);\n }\n}\n ScheduledThreadPoolExecutor" }, { "answer_id": 13583445, "author": "Shaik Khader", "author_id": 1021549, "author_profile": "https://Stackoverflow.com/users/1021549", "pm_score": 2, "selected": false, "text": "{\n\n Runnable r = new ScheduleTask();\n ReschedulableTimer rescheduleTimer = new ReschedulableTimer();\n rescheduleTimer.schedule(r, 10*1000);\n\n\n public class ScheduleTask implements Runnable {\n public void run() {\n //Do schecule task\n\n }\n }\n\n\nclass ReschedulableTimer extends Timer {\n private Runnable task;\n private TimerTask timerTask;\n\n public void schedule(Runnable runnable, long delay) {\n task = runnable;\n timerTask = new TimerTask() { \n public void run() { \n task.run(); \n }\n };\n\n timer.schedule(timerTask, delay); \n }\n\n public void reschedule(long delay) {\n System.out.println(\"rescheduling after seconds \"+delay);\n timerTask.cancel();\n timerTask = new TimerTask() { \n public void run() { \n task.run(); \n }\n };\n timer.schedule(timerTask, delay); \n }\n }\n\n\n}\n" }, { "answer_id": 13720407, "author": "Human Being", "author_id": 1835198, "author_profile": "https://Stackoverflow.com/users/1835198", "pm_score": 0, "selected": false, "text": "package com.tps.ProjectTasks.TimeThread;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\n/**\n * Simple demo that uses java.util.Timer to schedule a task to execute\n * every 5 seconds and have a delay if you give any input in console.\n */\n\npublic class DateThreadSheduler extends Thread { \n Timer timer;\n BufferedReader br ;\n String data = null;\n Date dNow ;\n SimpleDateFormat ft;\n\n public DateThreadSheduler() {\n\n timer = new Timer();\n timer.schedule(new RemindTask(), 0, 5*1000); \n br = new BufferedReader(new InputStreamReader(System.in));\n start();\n }\n\n public void run(){\n\n while(true){\n try {\n data =br.readLine();\n if(data != null && !data.trim().equals(\"\") ){\n timer.cancel();\n timer = new Timer();\n dNow = new Date( );\n ft = new SimpleDateFormat (\"E yyyy.MM.dd 'at' hh:mm:ss a zzz\");\n System.out.println(\"Modified Current Date ------> \" + ft.format(dNow));\n timer.schedule(new RemindTask(), 5*1000 , 5*1000);\n }\n\n }catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n public static void main(String args[]) {\n System.out.format(\"Printint the time and date was started...\\n\");\n new DateThreadSheduler();\n }\n}\n\nclass RemindTask extends TimerTask {\n Date dNow ;\n SimpleDateFormat ft;\n\n public void run() {\n\n dNow = new Date();\n ft = new SimpleDateFormat (\"E yyyy.MM.dd 'at' hh:mm:ss a zzz\");\n System.out.println(\"Current Date: \" + ft.format(dNow));\n }\n}\n" }, { "answer_id": 51446933, "author": "luke8800gts", "author_id": 5392548, "author_profile": "https://Stackoverflow.com/users/5392548", "pm_score": 0, "selected": false, "text": "public class ReschedulableTimer extends Timer {\n private Runnable mTask;\n private TimerTask mTimerTask;\n\n public ReschedulableTimer(Runnable runnable) {\n this.mTask = runnable;\n }\n\n public void schedule(long delay) {\n if (mTimerTask != null)\n mTimerTask.cancel();\n\n mTimerTask = new TimerTask() {\n @Override\n public void run() {\n mTask.run();\n }\n };\n this.schedule(mTimerTask, delay);\n }\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/142/" ]
32,003
<p>Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like:</p> <pre><code>C:\&gt; go home D:\profiles\user\home\&gt; go svn-project1 D:\projects\project1\svn\branch\src\&gt; </code></pre> <p>I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is <a href="http://www.skamphausen.de/software/cdargs/" rel="noreferrer">cdargs</a> or <a href="http://kore-nordmann.de/blog/shell_bookmarks.html" rel="noreferrer">shell bookmarks</a> but I haven't found something on windows.</p> <hr> <p>Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution.</p>
[ { "answer_id": 32007, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "$vids=\"C:\\Users\\mabster\\Videos\"\n cd $vids\n" }, { "answer_id": 32012, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "C:\\>set DOOMED=c:\\windows\nC:\\>cd %DOOMED%\nC:\\WINDOWS>\n" }, { "answer_id": 32014, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 0, "selected": false, "text": "set home=D:\\profiles\\user\\home\nset svn-project1=D:\\projects\\project1\\svn\\branch\\src\n\ncd %home%\n" }, { "answer_id": 32019, "author": "Andrew", "author_id": 1948, "author_profile": "https://Stackoverflow.com/users/1948", "pm_score": 6, "selected": true, "text": "doskey mcd=mkdir \"$*\"$Tpushd \"$*\"\n mcd foo/bar \n mkdir \"foo/bar\"&pushd \"foo/bar\"\n" }, { "answer_id": 32026, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 2, "selected": false, "text": "@echo off\nset BookMarkFolder=c:\\data\\cline\\bookmarks\\\nif exist %BookMarkFolder%%1.lnk start %BookMarkFolder%%1.lnk\nif exist %BookMarkFolder%%1.bat start %BookMarkFolder%%1.bat\nif exist %BookMarkFolder%%1.vbs start %BookMarkFolder%%1.vbs\nif exist %BookMarkFolder%%1.URL start %BookMarkFolder%%1.URL\n" }, { "answer_id": 36609494, "author": "DieterDP", "author_id": 1436932, "author_profile": "https://Stackoverflow.com/users/1436932", "pm_score": 3, "selected": false, "text": "@ECHO OFF\nREM Source found on https://github.com/DieterDePaepe/windows-scripts\nREM Please share any improvements made!\n\nREM Folder where all links will end up\nset WARP_REPO=%USERPROFILE%\\.warp\n\nIF [%1]==[/?] GOTO :help\nIF [%1]==[--help] GOTO :help\nIF [%1]==[/create] GOTO :create\nIF [%1]==[/remove] GOTO :remove\nIF [%1]==[/list] GOTO :list\n\nset /p WARP_DIR=<%WARP_REPO%\\%1\ncd %WARP_DIR%\nGOTO :end\n\n:create\nIF [%2]==[] (\n ECHO Missing name for bookmark\n GOTO :EOF\n)\n\nif not exist %WARP_REPO%\\NUL mkdir %WARP_REPO%\nECHO %cd% > %WARP_REPO%\\%2\nECHO Created bookmark \"%2\"\nGOTO :end\n\n:list\ndir %WARP_REPO% /B\nGOTO :end\n\n:remove\nIF [%2]==[] (\n ECHO Missing name for bookmark\n GOTO :EOF\n)\nif not exist %WARP_REPO%\\%2 (\n ECHO Bookmark does not exist: %2\n GOTO :EOF\n)\ndel %WARP_REPO%\\%2\nGOTO :end\n\n:help\nECHO Create or navigate to folder bookmarks.\nECHO.\nECHO warp /? Display this help\nECHO warp [bookmark] Navigate to existing bookmark\nECHO warp /remove [bookmark] Remove an existing bookmark\nECHO warp /create [bookmark] Navigate to existing bookmark\nECHO warp /list List existing bookmarks\nECHO.\n\n:end\n c:\\Temp>warp /create temp # Create a new bookmark\nCreated bookmark \"temp\"\nc:\\Temp>cd c:\\Users\\Public # Go somewhere else\nc:\\Users\\Public>warp temp # Go to the stored bookmark\nc:\\Temp>\n c:\\Users\\Public>warp temp\nc:\\Temp>popd\nc:\\Users\\Public>\n warp /window <bookmark> warp /?" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1462/" ]
32,010
<p><a href="http://twitter.com/codinghorror/statuses/901272685" rel="nofollow noreferrer">Source</a></p> <blockquote> <p>RegexOptions.IgnoreCase is more expensive than I would have thought (eg, should be barely measurable)</p> </blockquote> <p>Assuming that this applies to PHP, Python, Perl, Ruby etc as well as C# (which is what I assume Jeff was using), how much of a slowdown is it and will I incur a similar penalty with <code>/[a-zA-z]/</code> as I will with <code>/[a-z]/i</code> ?</p>
[ { "answer_id": 32021, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 5, "selected": true, "text": "RegexOptions.IgnoreCase" }, { "answer_id": 32135, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 0, "selected": false, "text": "$x = \"abbCCDGBAdgfabv\";\n(lc $x) =~ /bad/;\n $x = \"abbCCDGBAdgfabv\";\n$x =~ /bad/i;\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
32,027
<p>I'm new to NAnt but have some experience with Ant and CruiseControl.</p> <p>What I want to do is have my SVN project include all tools needed (like NUnit and Mocks etc) so I can check out onto a fresh machine and build. This strategy is outlined by J.P Boodhoo <a href="http://blog.jpboodhoo.com/NAntStarterSeries.aspx" rel="noreferrer">here.</a></p> <p>So far so good if I only want to run on Windows, but I want to be able to check out onto Linux and build/test/run against Mono too. I want no dependencies external to the SVN project. I don't mind having two sets of tools in the project but want only one NAnt build file</p> <p>This must be possible - but how? what are the tricks / 'traps for young players' </p>
[ { "answer_id": 32317, "author": "RobertTheGrey", "author_id": 1107, "author_profile": "https://Stackoverflow.com/users/1107", "pm_score": 4, "selected": true, "text": "$ export MONO_NO_UNLOAD=1\n$ make clean\n$ make\n$ mono bin/NAnt.exe clean build\n <project name=\"DualBuild\">\n <property name=\"windowsDotNetPath\" value=\"C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\" />\n <property name=\"windowsSolutionPath\" value=\"D:\\WorkingDirectory\\branches\\1234\\source\" />\n <property name=\"windowsNUnitPath\" value=\"C:\\Program Files\\NUnit-Net-2.0 2.2.8\\bin\" />\n <property name=\"monoPath\" value=\"You get the idea...\" />\n\n <target name=\"BuildAndTestOnWindows\" depends=\"WinUpdateRevision, WinBuild, WinTest\" />\n <target name=\"BuildAndTestOnLinux\" depends=\"MonoUpdateRevision, MonoBuild, MonoTest\" />\n\n <target name=\"WinUpdateRevision\">\n <delete file=\"${windowsSolutionPath}\\Properties\\AssemblyInfo.cs\" />\n <exec program=\"subwcrev.exe\" basedir=\"C:\\Program Files\\TortoiseSVN\\bin\\\"\n workingdir=\"${windowsSolutionPath}\\Properties\"\n commandline=\"${windowsSolutionPath} .\\AssemblyInfoTemplate.cs\n .\\AssemblyInfo.cs\" />\n <delete file=\"${windowsSolutionPath}\\Properties\\AssemblyInfo.cs\" />\n <exec program=\"subwcrev.exe\" basedir=\"C:\\Program Files\\TortoiseSVN\\bin\\\"\n workingdir=\"${windowsSolutionPath}\\Properties\"\n commandline=\"${windowsSolutionPath} .\\AssemblyInfoTemplate.cs \n .\\AssemblyInfo.cs\" />\n </target>\n\n <target name=\"WinBuild\">\n <exec program=\"msbuild.exe\"\n basedir=\"${windowsDotNetPath}\"\n workingdir=\"${windowsSolutionPath}\"\n commandline=\"MySolution.sln /logger:ThoughtWorks.CruiseControl.MsBuild.XmlLogger,\n ThoughtWorks.CruiseControl.MsBuild.dll;msbuild-output.xml \n /nologo /verbosity:normal /noconsolelogger \n /p:Configuration=Debug /target:Rebuild\" />\n </target>\n\n <target name=\"WinTest\">\n <exec program=\"NCover.Console.exe\"\n basedir=\"C:\\Program Files\\NCover\"\n workingdir=\"${windowsSolutionPath}\">\n <arg value=\"//x &quot;ClientCoverage.xml&quot;\" />\n <arg value=\"&quot;C:\\Program Files\\NUnit-Net-2.0 2.2.8\\bin\n \\nunit-console.exe&quot; \n MySolution.nunit /xml=nunit-output.xml /nologo\" />\n </exec>\n </target>\n\n <target name=\"MonoUpdateRevision\">\n You get the idea...\n </target>\n\n\n <target name=\"MonoBuild\">\n You get the idea...\n </target>\n\n <target name=\"MonoTest\">\n You get the idea...\n </target>\n\n</project>\n" }, { "answer_id": 46075, "author": "Frep D-Oronge", "author_id": 3024, "author_profile": "https://Stackoverflow.com/users/3024", "pm_score": 1, "selected": false, "text": "mono nant.exe\n" }, { "answer_id": 34782467, "author": "Mark Bowker", "author_id": 4528082, "author_profile": "https://Stackoverflow.com/users/4528082", "pm_score": 0, "selected": false, "text": "build ./build.sh tools\\nant build-csproj test-project @tools\\nant\\nant.exe %*\n #!/bin/sh\n\n/usr/bin/cli tools/nant/NAnt.exe \"$@\"\n <?xml version=\"1.0\"?>\n<project name=\"MyProject\" default=\"all\">\n\n <if test=\"${not property::exists('configuration')}\">\n <property name=\"configuration\" value=\"release\" readonly=\"true\" />\n </if>\n\n <if test=\"${platform::is-windows()}\">\n <property name=\"BuildTool\" value=\"C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\MSBuild.exe\" readonly=\"true\"/>\n </if>\n <if test=\"${platform::is-unix()}\">\n <property name=\"BuildTool\" value=\"xbuild\" readonly=\"true\"/>\n </if>\n\n <property name=\"TestTool\" value=\"tools/mytesttool.exe\"/>\n\n <target name=\"all\" depends=\"myproject myprojectlib\" />\n\n <target name=\"build-csproj\" description=\"Build a given csproj\">\n <!-- Must not be called standalone as it requires some properties set. -->\n <exec program=\"${BuildTool}\">\n <arg path=\"src/${ProjectName}/${ProjectName}.csproj\" />\n <arg line=\"/property:Configuration=${configuration}\" />\n <arg value=\"/target:Rebuild\" />\n <arg value=\"/verbosity:normal\" />\n <arg value=\"/nologo\" />\n </exec>\n </target>\n\n <target name=\"test-project\">\n <!-- Must not be called standalone as it requires some properties set. -->\n <exec program=\"${TestTool}\">\n <arg path=\"my/${ProjectName}/tests/path/for/tool\" />\n <arg value=\"/aproperty=value\" />\n </exec>\n </target>\n\n <target name=\"myproject\" description=\"Build the project\">\n <property name=\"ProjectName\" value=\"MyProject\"/>\n <call target=\"build-csproj\" />\n <call target=\"test-project\" />\n </target>\n\n <target name=\"myprojectlib\" description=\"Build the project's library dll\">\n <property name=\"ProjectName\" value=\"MyProjectLib\"/>\n <call target=\"build-csproj\" />\n <call target=\"test-project\" />\n </target>\n\n</project>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3024/" ]
32,034
<p>After reading the Head First Design Patterns book and using a number of other design patterns, I'm trying to understand the Observer pattern. Isn't this already implemented using Events in the .NET Framework?</p>
[ { "answer_id": 100921, "author": "Hace", "author_id": 18703, "author_profile": "https://Stackoverflow.com/users/18703", "pm_score": 2, "selected": false, "text": "public void NotifyObservers()\n{\n foreach(Product product in ProductList)\n {\n if (product is IProductObserver)\n {\n product.Update(this)\n }\n }\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993/" ]
32,041
<p>Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations.</p> <p>It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish.</p>
[ { "answer_id": 32067, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": 3, "selected": false, "text": "public abstract class Config\n{\n public static final boolean ENABLELOGGING = true;\n}\n import static Config.*;\n\npublic class MyClass\n{\n public myMethod()\n {\n System.out.println(\"Hello, non-logging world\");\n\n if (ENABLELOGGING)\n {\n log(\"Hello, logging world.\");\n }\n }\n}\n public class MyClass\n{\n public myMethod()\n {\n System.out.println(\"Hello, non-logging world\");\n\n Log.log(\"Hello, logging world.\");\n }\n}\n import static Config.*;\n\npublic abstract class Log\n{\n public static void log(String s)\n {\n if (ENABLELOGGING)\n {\n log(s);\n }\n }\n}\n" }, { "answer_id": 32122, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 6, "selected": true, "text": "if (logger.isDebugEnabled()) {\n\n // perform expensive operations\n // build string to log\n\n logger.debug(\"....\");\n}\n assert (sky.state != FALLING) : \"The sky is falling!\";\n" }, { "answer_id": 32342, "author": "HadleyHope", "author_id": 3416, "author_profile": "https://Stackoverflow.com/users/3416", "pm_score": 0, "selected": false, "text": "logger.IsDebugEnabled() logger.error(\"Something bad happened\")\nlogger.debug(\"Something bad happend with loads more detail\")\n" }, { "answer_id": 23541646, "author": "Hiep", "author_id": 347051, "author_profile": "https://Stackoverflow.com/users/347051", "pm_score": 1, "selected": false, "text": "public static final boolean DEBUG = false;\n\nif (DEBUG) { //disapeared on compilation }\n javac static final boolean if (logger.isDebugEnabled()) {\n logger.debug(\"....\");\n}\nrealImportantWork();\n realImportantWork() logger.debug(\"....\");\nrealImportantWork()\n logger.isDebugEnabled()" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1772/" ]
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/" rel="noreferrer">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
[ { "answer_id": 32125, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 6, "selected": true, "text": "<li> </li>" }, { "answer_id": 11644588, "author": "Rohan", "author_id": 229410, "author_profile": "https://Stackoverflow.com/users/229410", "pm_score": 6, "selected": false, "text": "with <ul>\n{%for node in all_root_elems %} \n {%include \"tree_view_template.html\" %}\n{%endfor%}\n</ul>\n ul li node <li> {{node.name}}\n {%if node.has_childs %}\n <ul>\n {%for ch in node.all_childs %}\n {%with node=ch template_name=\"tree_view_template.html\" %}\n {%include template_name%}\n {%endwith%}\n {%endfor%}\n </ul>\n {%endif%}\n</li>\n" }, { "answer_id": 12558610, "author": "Vladimir", "author_id": 1153290, "author_profile": "https://Stackoverflow.com/users/1153290", "pm_score": 4, "selected": false, "text": "{% with template_name=\"file/to_include.html\" %}\n{% include template_name %}\n{% endwith %}\n" }, { "answer_id": 26045234, "author": "Carel", "author_id": 958580, "author_profile": "https://Stackoverflow.com/users/958580", "pm_score": 1, "selected": false, "text": "# Base.html\n<nav>\n{% with dict=contents template=\"treedict.html\" %}\n {% include template %}\n{% endwith %}\n<nav>\n # TreeDict.html\n<ul>\n{% for key,val in dict.items %}\n {% if val.items %}\n <li>{{ key }}</li>\n {%with dict=val template=\"treedict.html\" %}\n {%include template%}\n {%endwith%}\n {% else %} \n <li><a href=\"{{ val }}\">{{ key }}</a></li>\n {% endif %}\n{% endfor %} \n</ul>\n" }, { "answer_id": 33340554, "author": "Arthur Sult", "author_id": 3110300, "author_profile": "https://Stackoverflow.com/users/3110300", "pm_score": 5, "selected": false, "text": "<!-- lets say that menu_list is already defined -->\n<ul>\n {% include \"menu.html\" %}\n</ul>\n menu.html {% for menu in menu_list %}\n <li>\n {{ menu.name }}\n {% if menu.submenus|length %}\n <ul>\n {% include \"menu.html\" with menu_list=menu.submenus %}\n </ul>\n {% endif %}\n </li>\n{% endfor %}\n" }, { "answer_id": 45398510, "author": "meg2mag", "author_id": 5624832, "author_profile": "https://Stackoverflow.com/users/5624832", "pm_score": 1, "selected": false, "text": "{% extends 'students/base.html' %}\n{% load i18n %}\n{% load static from staticfiles %}\n\n{% block content %}\n\n<ul>\n{% for comment in comments %}\n {% if not comment.parent %} ## add this ligic\n {% include \"comment/tree_comment.html\" %}\n {% endif %}\n{% endfor %}\n</ul>\n\n{% endblock %}\n <li>{{ comment.text }}\n {%if comment.children %}\n <ul>\n {% for ch in comment.children.get_queryset %} # related_name in model\n {% with comment=ch template_name=\"comment/tree_comment.html\" %}\n {% include template_name %}\n {% endwith %}\n {% endfor %}\n </ul>\n {% endif %}\n</li>\n from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\n\n# Create your models here.\nclass Comment(models.Model):\n class Meta(object):\n verbose_name = _('Comment')\n verbose_name_plural = _('Comments')\n\n parent = models.ForeignKey(\n 'self',\n on_delete=models.CASCADE,\n parent_link=True,\n related_name='children',\n null=True,\n blank=True)\n\n text = models.TextField(\n max_length=2000,\n help_text=_('Please, your Comment'),\n verbose_name=_('Comment'),\n blank=True)\n\n public_date = models.DateTimeField(\n auto_now_add=True)\n\n correct_date = models.DateTimeField(\n auto_now=True)\n\n author = models.ForeignKey(User)\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3154/" ]
32,058
<p>I have a simple web service operation like this one:</p> <pre><code> [WebMethod] public string HelloWorld() { throw new Exception("HelloWorldException"); return "Hello World"; } </code></pre> <p>And then I have a client application that consumes the web service and then calls the operation. Obviously it will throw an exception :-)</p> <pre><code> try { hwservicens.Service1 service1 = new hwservicens.Service1(); service1.HelloWorld(); } catch(Exception e) { Console.WriteLine(e.ToString()); } </code></pre> <p>In my catch-block, what I would like to do is extract the Message of the actual exception to use it in my code. The exception caught is a <code>SoapException</code>, which is fine, but it's <code>Message</code> property is like this...</p> <pre><code>System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.Exception: HelloWorldException at WebService1.Service1.HelloWorld() in C:\svnroot\Vordur\WebService1\Service1.asmx.cs:line 27 --- End of inner exception stack trace --- </code></pre> <p>...and the <code>InnerException</code> is <code>null</code>.</p> <p>What I would like to do is extract the <code>Message</code> property of the <code>InnerException</code> (the <code>HelloWorldException</code> text in my sample), can anyone help with that? If you can avoid it, please don't suggest parsing the <code>Message</code> property of the <code>SoapException</code>.</p>
[ { "answer_id": 32508, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 4, "selected": true, "text": "[WebMethod]\npublic ResponseClass HelloWorld()\n{\n ResponseClass c = new ResponseClass();\n try \n {\n throw new Exception(\"Exception Text\");\n // The following would be returned on a success\n c.WasError = false;\n c.ReturnValue = \"Hello World\";\n }\n catch(Exception e)\n {\n c.WasError = true;\n c.ErrorMessage = e.Message;\n return c;\n }\n}\n" }, { "answer_id": 33525, "author": "Jacob Proffitt", "author_id": 1336, "author_profile": "https://Stackoverflow.com/users/1336", "pm_score": 2, "selected": false, "text": "catch (FaultException soapEx)\n{\n MessageFault mf = soapEx.CreateMessageFault();\n if (mf.HasDetail)\n {\n XmlDictionaryReader reader = mf.GetReaderAtDetailContents();\n Guid g = reader.ReadContentAsGuid();\n }\n}\n" }, { "answer_id": 12281546, "author": "BornToCode", "author_id": 1057791, "author_profile": "https://Stackoverflow.com/users/1057791", "pm_score": 3, "selected": false, "text": "try\n{\n // do something good for humanity\n}\ncatch (Exception e)\n{\n throw new SoapException(e.InnerException.Message,\n SoapException.ServerFaultCode);\n}\n try\n{\n // save humanity\n}\ncatch (Exception e)\n{\n Console.WriteLine(e.Message); \n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3379/" ]
32,059
<p>Let's say I have four tables: <code>PAGE</code>, <code>USER</code>, <code>TAG</code>, and <code>PAGE-TAG</code>:</p> <pre><code>Table | Fields ------------------------------------------ PAGE | ID, CONTENT TAG | ID, NAME USER | ID, NAME PAGE-TAG | ID, PAGE-ID, TAG-ID, USER-ID </code></pre> <p>And let's say I have four pages:</p> <pre><code>PAGE#1 'Content page 1' tagged with tag#1 by user1, tagged with tag#1 by user2 PAGE#2 'Content page 2' tagged with tag#3 by user2, tagged by tag#1 by user2, tagged by tag#8 by user1 PAGE#3 'Content page 3' tagged with tag#7 by user#1 PAGE#4 'Content page 4' tagged with tag#1 by user1, tagged with tag#8 by user1 </code></pre> <p>I expect my query to look something like this: </p> <pre><code>select page.content ? from page, page-tag where page.id = page-tag.pag-id and page-tag.tag-id in (1, 3, 8) order by ? desc </code></pre> <p>I would like to get output like this:</p> <pre><code>Content page 2, 3 Content page 4, 2 Content page 1, 1 </code></pre> <hr> <p>Quoting Neall </p> <blockquote> <p>Your question is a bit confusing. Do you want to get the number of times each page has been tagged? </p> </blockquote> <p>No</p> <blockquote> <p>The number of times each page has gotten each tag? </p> </blockquote> <p>No</p> <blockquote> <p>The number of unique users that have tagged a page? </p> </blockquote> <p>No </p> <blockquote> <p>The number of unique users that have tagged each page with each tag?</p> </blockquote> <p>No</p> <p>I want to know how many of the passed tags appear in a particular page, not just if any of the tags appear. </p> <p>SQL IN works like an boolean operator OR. If a page was tagged with any value within the IN Clause then it returns true. I would like to know how many of the values inside of the IN clause return true. </p> <p>Below i show, the output i expect: </p> <pre><code>page 1 | in (1,2) -&gt; 1 page 1 | in (1,2,3) -&gt; 1 page 1 | in (1) -&gt; 1 page 1 | in (1,3,8) -&gt; 1 page 2 | in (1,2) -&gt; 1 page 2 | in (1,2,3) -&gt; 2 page 2 | in (1) -&gt; 1 page 2 | in (1,3,8) -&gt; 3 page 4 | in (1,2,3) -&gt; 1 page 4 | in (1,2,3) -&gt; 1 page 4 | in (1) -&gt; 1 page 4 | in (1,3,8) -&gt; 2 </code></pre> <p>This will be the content of the page-tag table i mentioned before: </p> <pre><code> id page-id tag-id user-id 1 1 1 1 2 1 1 2 3 2 3 2 4 2 1 2 5 2 8 1 6 3 7 1 7 4 1 1 8 4 8 1 </code></pre> <p><strong>@Kristof</strong> does not exactly what i am searching for but thanks anyway. </p> <p><strong>@Daren</strong> If i execute you code i get the next error: </p> <pre><code>#1054 - Unknown column 'page-tag.tag-id' in 'having clause' </code></pre> <p><strong>@Eduardo Molteni</strong> Your answer does not give the output in the question but: </p> <pre><code>Content page 2 8 Content page 4 8 content page 2 3 content page 1 1 content page 1 1 content page 2 1 cotnent page 4 1 </code></pre> <p><strong>@Keith</strong> I am using plain SQL not T-SQL and i am not familiar with T-SQL, so i do not know how your query translate to plain SQL.</p> <p>Any more ideas?</p>
[ { "answer_id": 32070, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "select page.content, count(page-tag.tag-id) as tagcount\nfrom page inner join page-tag on page-tag.page-id = page.id\ngroup by page.content\nhaving page-tag.tag-id in (1, 3, 8)\n" }, { "answer_id": 32088, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "select count(distinct name)\nfrom page-tag\nwhere tag-id in (1, 3, 8) \n" }, { "answer_id": 32095, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 0, "selected": false, "text": "select page.content, page-tag.tag-id\nfrom page, page-tag \nwhere page.id = page-tag.pag-id \nand page-tag.tag-id in (1, 3, 8) \norder by page-tag.tag-id desc\n" }, { "answer_id": 32159, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 0, "selected": false, "text": "select \n page.content, \n count(pageTag.tagID) as tagCount\nfrom \n page\n inner join pageTag on page.ID = pageTag.pageID\nwhere \n pageTag.tagID in (1, 3, 8) \ngroup by\n page.content\norder by\n tagCount desc\n" }, { "answer_id": 32560, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 2, "selected": true, "text": "SELECT page.ID, page.content, count(*) AS uniquetags\nFROM\n ( SELECT DISTINCT page.content, page.ID, page-tag.tag-id \n FROM page INNER JOIN page-tag ON page.ID=page-tag.page-ID \n WHERE page-tag.tag-id IN (1, 3, 8) \n )\n GROUP BY page.ID\n ORDER BY uniquetags DESC\n ORDER BY SELECT" }, { "answer_id": 32655, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 0, "selected": false, "text": "SELECT page.ID, page.content, count(*) AS uniquetags FROM\n ( SELECT DISTINCT page.content, page.ID, page-tag.tag-id FROM page INNER JOIN page-tag ON page.ID=page-tag.page-ID WHERE page-tag.tag-id IN (1, 3, 8) ) as page\n GROUP BY page.ID\norder by uniquetags desc\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
32,085
<p>In XLST how would you find out the length of a node-set?</p>
[ { "answer_id": 32092, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 5, "selected": true, "text": "<xsl:variable name=\"length\" select=\"count(nodeset)\"/>\n" }, { "answer_id": 32217, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 2, "selected": false, "text": "Arrays nodesets sequences" }, { "answer_id": 39644, "author": "Pierre Spring", "author_id": 1532, "author_profile": "https://Stackoverflow.com/users/1532", "pm_score": 3, "selected": false, "text": "<xsl:variable name=\"length\" select=\"count(nodes/node)\"/>\n <xsl:value-of select=\"count(nodes/node)\"/>\n <xsl:if test=\"count(comments/comment) > '0'\">\n <ul>\n <xsl:apply-templates select=\"comments/comment\"/>\n </ul>\n</xsl:if>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
32,087
<p>I want to know what are the options to do some scripting jobs in windows platform. I need functionality like file manipulations, registry editing etc. Can files be edited using scripting tools? What other functionality does windows scripting tools offer? Can everything that can be done using the Windows GUI be done using a scripting language?</p>
[ { "answer_id": 55769598, "author": "Zhiyuan-Amos", "author_id": 8828382, "author_profile": "https://Stackoverflow.com/users/8828382", "pm_score": 0, "selected": false, "text": "(Get-Content c:\\temp\\test.txt).replace('[MYID]', 'MyValue') | Set-Content c:\\temp\\test.txt Set-ItemProperty -Path HKCU:\\Software\\hsg -Name newproperty -Value anewvalue" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
32,100
<p>What is the simplest SQL query to find the second largest integer value in a specific column? </p> <p>There are maybe duplicate values in the column.</p>
[ { "answer_id": 32108, "author": "Magnar", "author_id": 1123, "author_profile": "https://Stackoverflow.com/users/1123", "pm_score": 3, "selected": false, "text": "SELECT DISTINCT value \nFROM Table \nORDER BY value DESC \nLIMIT 2\n SELECT MIN(value) \nFROM ( SELECT DISTINCT value \n FROM Table \n ORDER BY value DESC \n LIMIT 2\n ) AS t\n" }, { "answer_id": 32109, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 4, "selected": false, "text": "SELECT * \nFROM Table \nORDER BY NumericalColumn DESC \nLIMIT 1 OFFSET 1\n SELECT * \nFROM Table ORDER BY NumericalColumn DESC \nLIMIT (1, 1)\n" }, { "answer_id": 32111, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 9, "selected": true, "text": "SELECT MAX( col )\n FROM table\n WHERE col < ( SELECT MAX( col )\n FROM table )\n" }, { "answer_id": 32114, "author": "Chris Conway", "author_id": 2849, "author_profile": "https://Stackoverflow.com/users/2849", "pm_score": 0, "selected": false, "text": "select top 1 MyIntColumn from MyTable\nwhere\n MyIntColumn <> (select top 1 MyIntColumn from MyTable order by MyIntColumn desc)\norder by MyIntColumn desc\n" }, { "answer_id": 32115, "author": "Tom Welch", "author_id": 1188, "author_profile": "https://Stackoverflow.com/users/1188", "pm_score": 0, "selected": false, "text": "select max([COLUMN_NAME]) from [TABLE_NAME] where [COLUMN_NAME] < \n ( select max([COLUMN_NAME]) from [TABLE_NAME] )\n" }, { "answer_id": 32119, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 0, "selected": false, "text": "select top 1 x\nfrom (\n select top 2 distinct x \n from y \n order by x desc\n) z\norder by x\n" }, { "answer_id": 32233, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 5, "selected": false, "text": "--filter out the max\nselect max( col )\nfrom [table]\nwhere col < ( \n select max( col )\n from [table] )\n\n--sort top two then bottom one\nselect top 1 col \nfrom (\n select top 2 col \n from [table]\n order by col) topTwo\norder by col desc \n max ROW_NUMBER() select col\nfrom (\n select ROW_NUMBER() over (order by col asc) as 'rowNum', col\n from [table] ) withRowNum \nwhere rowNum = 2\n" }, { "answer_id": 32284, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 0, "selected": false, "text": "SELECT TOP 1 START AT 2 value from table ORDER BY value\n" }, { "answer_id": 32393, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": false, "text": "SELECT MIN([column]) AS [column]\nFROM (\n SELECT TOP 2 [column] \n FROM [Table] \n GROUP BY [column] \n ORDER BY [column] DESC\n) a\n SELECT `column` \nFROM `table` \nGROUP BY `column` \nORDER BY `column` DESC \nLIMIT 1,1\n SELECT [column] \nFROM [Table] \nGROUP BY [column] \nORDER BY [column] DESC\nOFFSET 1 ROWS\nFETCH NEXT 1 ROWS ONLY;\n" }, { "answer_id": 1101910, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select * from emp e where 3>=(select count(distinct salary)\n from emp where s.salary<=salary)\n" }, { "answer_id": 1423692, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Select * from x x1 where 1 = (select count(*) from x where x1.a < a)\n" }, { "answer_id": 4279304, "author": "sunith", "author_id": 520440, "author_profile": "https://Stackoverflow.com/users/520440", "pm_score": 1, "selected": false, "text": "select max([COLUMN_NAME]) from [TABLE_NAME] select max([COLUMN_NAME]) \nfrom [TABLE_NAME] \nwhere [COLUMN_NAME] IN ( select max([COLUMN_NAME]) \n from [TABLE_NAME] \n )\n" }, { "answer_id": 4279338, "author": "sunith", "author_id": 520440, "author_profile": "https://Stackoverflow.com/users/520440", "pm_score": 1, "selected": false, "text": "select max(COL_NAME) \nfrom TABLE_NAME \nwhere COL_NAME in ( select COL_NAME \n from TABLE_NAME \n where COL_NAME < ( select max(COL_NAME) \n from TABLE_NAME\n )\n );\n" }, { "answer_id": 6967041, "author": "Ni3", "author_id": 881951, "author_profile": "https://Stackoverflow.com/users/881951", "pm_score": 1, "selected": false, "text": "select min(sal) from emp where sal in \n (select TOP 2 (sal) from emp order by sal desc)\n" }, { "answer_id": 7362165, "author": "Vinoy", "author_id": 936824, "author_profile": "https://Stackoverflow.com/users/936824", "pm_score": 6, "selected": false, "text": "SELECT MAX(col) \nFROM table \nWHERE col NOT IN ( SELECT MAX(col) \n FROM table\n );\n" }, { "answer_id": 9939606, "author": "Divya.N.R", "author_id": 1302822, "author_profile": "https://Stackoverflow.com/users/1302822", "pm_score": 1, "selected": false, "text": "select col_name\nfrom (\n select dense_rank() over (order by col_name desc) as 'rank', col_name\n from table_name ) withrank \nwhere rank = 2\n" }, { "answer_id": 11233270, "author": "Rohit Singh", "author_id": 1486677, "author_profile": "https://Stackoverflow.com/users/1486677", "pm_score": 2, "selected": false, "text": "\nselect * from (select ROW_NUMBER() over (Order by Col_x desc) as Row, Col_1\n from table_1)as table_new tn inner join table_1 t1\n on tn.col_1 = t1.col_1\nwhere row = 2\n" }, { "answer_id": 13034858, "author": "avie sparrows", "author_id": 1768911, "author_profile": "https://Stackoverflow.com/users/1768911", "pm_score": 1, "selected": false, "text": "SELECT \n * \nFROM \n table \nWHERE \n column < (SELECT max(columnq) FROM table) \nORDER BY \n column DESC LIMIT 1\n" }, { "answer_id": 13067166, "author": "petcy", "author_id": 1773950, "author_profile": "https://Stackoverflow.com/users/1773950", "pm_score": 3, "selected": false, "text": "SELECT `Column` \nFROM `Table` \nORDER BY `Column` DESC \nLIMIT 1,1;\n" }, { "answer_id": 14473566, "author": "user1796141", "author_id": 1796141, "author_profile": "https://Stackoverflow.com/users/1796141", "pm_score": 3, "selected": false, "text": "SELECT *\nFROM TableName a\nWHERE\n 2 = (SELECT count(DISTINCT(b.ColumnName))\n FROM TableName b WHERE\n a.ColumnName <= b.ColumnName);\n" }, { "answer_id": 15609026, "author": "nikita", "author_id": 2206467, "author_profile": "https://Stackoverflow.com/users/2206467", "pm_score": 0, "selected": false, "text": "select Top 1 (salary) from XYZ\nwhere Salary not in (select distinct TOP 1(salary) from XYZ order by Salary desc)\nORDER BY Salary DESC\n Top 1 TOP 2 3 4" }, { "answer_id": 16167516, "author": "Abhishek Gahlout", "author_id": 1966824, "author_profile": "https://Stackoverflow.com/users/1966824", "pm_score": 0, "selected": false, "text": "Select top 1 col_name from table_name\nwhere col_name < (Select top 1 col_name from table_name order by col_name desc)\norder by col_name desc \n" }, { "answer_id": 16516669, "author": "ReeSen", "author_id": 2064007, "author_profile": "https://Stackoverflow.com/users/2064007", "pm_score": 0, "selected": false, "text": "SELECT * FROM EMP\nWHERE salary=\n (SELECT MAX(salary) FROM EMP\n WHERE salary != (SELECT MAX(salary) FROM EMP)\n );\n" }, { "answer_id": 18248613, "author": "Pearl90", "author_id": 2082012, "author_profile": "https://Stackoverflow.com/users/2082012", "pm_score": 1, "selected": false, "text": "select top 1 Age \nfrom Student \nwhere Age in ( select distinct top 2 Age \n from Student order by Age desc \n ) order by Age asc\n" }, { "answer_id": 18409515, "author": "Ravind Maurya", "author_id": 2388598, "author_profile": "https://Stackoverflow.com/users/2388598", "pm_score": 1, "selected": false, "text": "SELECT\n Column name\nFROM\n Table name \nORDER BY \n Column name DESC\nLIMIT 1,1\n" }, { "answer_id": 18763283, "author": "Gopal", "author_id": 2772462, "author_profile": "https://Stackoverflow.com/users/2772462", "pm_score": 0, "selected": false, "text": "select a.* ,b.* from \n(select * from (select ROW_NUMBER() OVER(ORDER BY fc_amount desc) SrNo1, fc_amount as amount1 From entry group by fc_amount) tbl where tbl.SrNo1 = 2) a\n,\n(select * from (select ROW_NUMBER() OVER(ORDER BY fc_amount asc) SrNo2, fc_amount as amount2 From entry group by fc_amount) tbl where tbl.SrNo2 =2) b\n" }, { "answer_id": 20211216, "author": "anand", "author_id": 3035367, "author_profile": "https://Stackoverflow.com/users/3035367", "pm_score": 0, "selected": false, "text": "select * from [table] where (column)=(select max(column)from [table] where column < (select max(column)from [table]))\n" }, { "answer_id": 22607111, "author": "yogesh shelke", "author_id": 3454959, "author_profile": "https://Stackoverflow.com/users/3454959", "pm_score": 2, "selected": false, "text": "SELECT MAX( colname ) \nFROM Tablename \nwhere colname < (\n SELECT MAX( colname ) \n FROM Tablename)\n" }, { "answer_id": 23197335, "author": "Mitesh Vora", "author_id": 2153499, "author_profile": "https://Stackoverflow.com/users/2153499", "pm_score": 0, "selected": false, "text": "select MAX(salary) as SecondMax from test where salary !=(select MAX(salary) from test)\n" }, { "answer_id": 28785160, "author": "DEADLOCK", "author_id": 4554137, "author_profile": "https://Stackoverflow.com/users/4554137", "pm_score": 1, "selected": false, "text": "select age \nfrom student \ngroup by id having age< ( select max(age) \n from student \n )\norder by age \nlimit 1\n" }, { "answer_id": 30135366, "author": "Naresh Kumar", "author_id": 4669533, "author_profile": "https://Stackoverflow.com/users/4669533", "pm_score": 2, "selected": false, "text": "SELECT MAX(Salary) \nFROM Employee \nWHERE Salary NOT IN ( SELECT MAX(Salary) \n FROM Employee \n )\n" }, { "answer_id": 32496424, "author": "Sumeet", "author_id": 2347348, "author_profile": "https://Stackoverflow.com/users/2347348", "pm_score": 2, "selected": false, "text": "select sal \nfrom salary \norder by sal desc \nlimit 1 offset 1\n" }, { "answer_id": 35787707, "author": "Hiren Joshi", "author_id": 5784225, "author_profile": "https://Stackoverflow.com/users/5784225", "pm_score": 0, "selected": false, "text": "select score \nfrom table \nwhere score = (select max(score)-1 from table)\n" }, { "answer_id": 37399687, "author": "Zorkolot", "author_id": 3064345, "author_profile": "https://Stackoverflow.com/users/3064345", "pm_score": 0, "selected": false, "text": "SELECT TOP 1 q.* \nFROM (SELECT TOP 2 column_name FROM table_name ORDER BY column_name DESC) as q\nORDER BY column_name ASC;\n SELECT TOP 1 q.* \nFROM (SELECT TOP 5 column_name FROM table_name ORDER BY column_name DESC) as q\nORDER BY column_name;\n" }, { "answer_id": 38665733, "author": "dier", "author_id": 3605078, "author_profile": "https://Stackoverflow.com/users/3605078", "pm_score": 2, "selected": false, "text": " SELECT TOP 1 LEAD(MAX (column)) OVER (ORDER BY column desc)\n FROM TABLE \n GROUP BY column\n" }, { "answer_id": 39304076, "author": "Jinto John", "author_id": 4583281, "author_profile": "https://Stackoverflow.com/users/4583281", "pm_score": 0, "selected": false, "text": "select extension from [dbo].[Employees] order by extension desc offset 2 rows fetch next 1 rows only\n" }, { "answer_id": 40999700, "author": "Shourob Datta", "author_id": 1705371, "author_profile": "https://Stackoverflow.com/users/1705371", "pm_score": 1, "selected": false, "text": "SELECT amount FROM salary \nGROUP by amount\nORDER BY amount DESC \nLIMIT 1 , 1\n SELECT DISTINCT amount\nFROM salary \nORDER BY amount DESC \nLIMIT 1 , 1\n" }, { "answer_id": 42717600, "author": "Swadesh", "author_id": 7584349, "author_profile": "https://Stackoverflow.com/users/7584349", "pm_score": 1, "selected": false, "text": "SELECT MAX(sal) \nFROM emp\nWHERE sal NOT IN ( SELECT top 3 sal \n FROM emp order by sal desc \n )\n \n" }, { "answer_id": 43452698, "author": "Mani G", "author_id": 4830297, "author_profile": "https://Stackoverflow.com/users/4830297", "pm_score": 0, "selected": false, "text": "SELECT distinct SupplierID FROM [Products] order by SupplierID desc limit 1 offset 1\n" }, { "answer_id": 44383572, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "ORDER BY ColumnName DESC LIMIT 1,1 SELECT * from `TableName` ORDER BY `ColumnName` DESC LIMIT 1,1\n" }, { "answer_id": 44715852, "author": "Nijish.", "author_id": 8203886, "author_profile": "https://Stackoverflow.com/users/8203886", "pm_score": 2, "selected": false, "text": "salary \n\n1000\n1500\n1450\n7500\n select salary from test order by salary desc offset 1 rows fetch next 1 rows only;\n" }, { "answer_id": 45049174, "author": "Justine Jose", "author_id": 2742464, "author_profile": "https://Stackoverflow.com/users/2742464", "pm_score": 3, "selected": false, "text": "SELECT *\n FROM [Users]\n order by UserId desc OFFSET 1 ROW \nFETCH NEXT 1 ROW ONLY;\n SELECT *\n FROM Users\n order by UserId desc LIMIT 1 OFFSET 1\n" }, { "answer_id": 46404204, "author": "Amit Prajapati", "author_id": 5056304, "author_profile": "https://Stackoverflow.com/users/5056304", "pm_score": 0, "selected": false, "text": " SELECT * FROM `employee` WHERE employee_salary = (SELECT employee_salary \n FROM`employee` GROUP BY employee_salary ORDER BY employee_salary DESC LIMIT \n 1,1)\n" }, { "answer_id": 46407836, "author": "rashedcs", "author_id": 6714430, "author_profile": "https://Stackoverflow.com/users/6714430", "pm_score": 1, "selected": false, "text": "select max(column_name) \nfrom table_name\nwhere column_name not in ( select max(column_name) \n from table_name\n );\n" }, { "answer_id": 48964594, "author": "Md. Nahidul Alam Chowdhury", "author_id": 2149563, "author_profile": "https://Stackoverflow.com/users/2149563", "pm_score": 0, "selected": false, "text": " select top 1 UnitPrice from (select distinct top n UnitPrice from \n[Order Details] order by UnitPrice desc) as Result order by UnitPrice asc\n" }, { "answer_id": 53327142, "author": "Md. Shamim Alam Javed", "author_id": 6122642, "author_profile": "https://Stackoverflow.com/users/6122642", "pm_score": 0, "selected": false, "text": "SELECT max(salary) from (Select * FROM emp WHERE salary<> (SELECT MAX(salary) from emp)) temp\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
32,145
<p>I'm going to try something with the format of this question and I'm very open to suggestions about a better way to handle it.</p> <p>I didn't want to just dump a bunch of code in the question so I've posted the code for the class on <code>refactormycode</code>.</p> <p><strong><a href="http://www.refactormycode.com/codes/461-base-class-for-easy-class-property-handling" rel="nofollow noreferrer">base class for easy class property handling</a></strong></p> <p>My thought was that people can either post code snippets here or make changes on <code>refactormycode</code> and post links back to their refactorings. I'll make upvotes and accept an answer (assuming there's a clear "winner") based on that.</p> <p>At any rate, on to the class itself:</p> <p>I see a lot of debate about getter/setter class methods and is it better to just access simple property variables directly or should every class have explicit get/set methods defined, blah blah blah. I like the idea of having explicit methods in case you have to add more logic later. Then you don't have to modify any code that uses the class. However I hate having a million functions that look like this:</p> <pre><code>public function getFirstName() { return $this-&gt;firstName; } public function setFirstName($firstName) { return $this-&gt;firstName; } </code></pre> <p>Now I'm sure I'm not the first person to do this (I'm hoping that there's a better way of doing it that someone can suggest to me).</p> <p>Basically, the PropertyHandler class has a __call magic method. Any methods that come through __call that start with "get" or "set" are then routed to functions that set or retrieve values into an associative array. The key into the array is the name of the calling method after getting or setting. So, if the method coming into __call is "getFirstName", the array key is "FirstName".</p> <p>I liked using __call because it will automatically take care of the case where the subclass already has a "getFirstName" method defined. My impression (and I may be wrong) is that the __get &amp; __set magic methods don't do that.</p> <p>So here's an example of how it would work:</p> <pre><code>class PropTest extends PropertyHandler { public function __construct() { parent::__construct(); } } $props = new PropTest(); $props-&gt;setFirstName("Mark"); echo $props-&gt;getFirstName(); </code></pre> <p>Notice that PropTest doesn't actually have "setFirstName" or "getFirstName" methods and neither does PropertyHandler. All that's doing is manipulating array values.</p> <p>The other case would be where your subclass is already extending something else. Since you can't have true multiple inheritances in PHP, you can make your subclass have a PropertyHandler instance as a private variable. You have to add one more function but then things behave in exactly the same way.</p> <pre><code>class PropTest2 { private $props; public function __construct() { $this-&gt;props = new PropertyHandler(); } public function __call($method, $arguments) { return $this-&gt;props-&gt;__call($method, $arguments); } } $props2 = new PropTest2(); $props2-&gt;setFirstName('Mark'); echo $props2-&gt;getFirstName(); </code></pre> <p>Notice how the subclass has a __call method that just passes everything along to the PropertyHandler __call method.</p> <hr> <p>Another good argument against handling getters and setters this way is that it makes it really hard to document.</p> <p>In fact, it's basically impossible to use any sort of document generation tool since the explicit methods to be don't documented don't exist.</p> <p>I've pretty much abandoned this approach for now. It was an interesting learning exercise but I think it sacrifices too much clarity.</p>
[ { "answer_id": 32191, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 3, "selected": false, "text": "class test {\n protected $x='';\n protected $y='';\n\n function set_y ($y) {\n print \"specific function set_y\\n\";\n $this->y = $y;\n }\n\n function __call($function , $args) {\n print \"generic function $function\\n\";\n list ($name , $var ) = split ('_' , $function );\n if ($name == 'get' && isset($this->$var)) {\n return $this->$var;\n }\n if ($name == 'set' && isset($this->$var)) {\n $this->$var= $args[0];\n return;\n }\n trigger_error (\"Fatal error: Call to undefined method test::$function()\");\n }\n}\n\n$p = new test();\n$p->set_x(20);\n$p->set_y(30);\nprint $p->get_x();\nprint $p->get_y();\n\n$p->set_z(40);\n generic function set_x\nspecific function set_y\n\ngeneric function get_x\n20\ngeneric function get_y\n30\n\ngeneric function set_z\nNotice: Fatal error: Call to undefined method set_z() in [...] on line 16\n" }, { "answer_id": 32218, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "$props2->setFristName('Mark');\n" }, { "answer_id": 32356, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 2, "selected": false, "text": "class PropTest extends PropertyHandler\n{\n public function __construct()\n {\n parent::__construct();\n }\n}\n\n$props = new PropTest();\n\n$props->setFirstName(\"Mark\");\necho $props->getFirstName();\n class PropTest extends PropertyHandler\n{\n public function __construct()\n {\n parent::__construct();\n }\n\n public function setFirstName($name)\n {\n if($name == 'Mark')\n {\n echo \"I love you, Mark!\";\n }\n }\n}\n" }, { "answer_id": 32507, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 0, "selected": false, "text": "/**\n* Handles default set and get calls\n*/\npublic function __call($method, $params) {\n\n //did you call get or set\n if ( preg_match( \"|^[gs]et([A-Z][\\w]+)|\", $method, $matches ) ) {\n\n //which var?\n $var = strtolower($matches[1]);\n\n $r = new ReflectionClass($this);\n $properties = $r->getdefaultProperties();\n\n //if it exists\n if ( array_key_exists($var,$properties) ) {\n //set\n if ( 's' == $method[0] ) {\n $this->$var = $params[0];\n }\n //get\n elseif ( 'g' == $method[0] ) {\n return $this->$var;\n }\n }\n }\n}\n class MyClass {\n public $myvar = null;\n}\n\n$test = new MyClass;\n$test->setMyvar = \"arapaho\";\n\necho $test->getMyvar; //echos arapaho \n" }, { "answer_id": 2658786, "author": "SeanJA", "author_id": 75924, "author_profile": "https://Stackoverflow.com/users/75924", "pm_score": 0, "selected": false, "text": "__get __set $obj->var __get __set __get __set" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
32,149
<p>Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as <code>"GEORGE BURDELL"</code> or <code>"george burdell"</code> and turns it into <code>"George Burdell"</code>.</p> <p>I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as <code>"O'REILLY"</code> and turn it into <code>"O'Reilly"</code>, but I know that is tougher.</p> <p>I am mainly focused on the English language if that simplifies things.</p> <hr> <p><strong>UPDATE:</strong> I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists).</p> <p>I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post.</p>
[ { "answer_id": 32189, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "/\\w+/\n /(\\w)(\\w*)/\n def make_proper(match):\n return match[1].to_upper + match[2]\n" }, { "answer_id": 32236, "author": "JimmyJ", "author_id": 2083, "author_profile": "https://Stackoverflow.com/users/2083", "pm_score": 0, "selected": false, "text": "$words = explode(” “, $string);\nfor ($i=0; $i<count($words); $i++) {\n$s = strtolower($words[$i]);\n$s = substr_replace($s, strtoupper(substr($s, 0, 1)), 0, 1);\n$result .= “$s “;\n}\n$string = trim($result);\n $words = explode(” “, $string);\nfor ($i=0; $i<count($words); $i++) {\n\n$s = strtolower($words[$i]);\n\nif (substr($s, 0, 2) === \"o'\"){\n$s = substr_replace($s, strtoupper(substr($s, 0, 3)), 0, 3);\n}else{\n$s = substr_replace($s, strtoupper(substr($s, 0, 1)), 0, 1);\n}\n$result .= “$s “;\n}\n$string = trim($result);\n" }, { "answer_id": 32249, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "Loop through each character\n If the previous character was an alphabet letter\n Make the character lower case\n Otherwise\n Make the character upper case\nEnd loop\n" }, { "answer_id": 32254, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 2, "selected": false, "text": "#!/usr/bin/perl\n\n# This filter changes all words to Title Caps, and attempts to be clever\n# about *un*capitalizing small words like a/an/the in the input.\n#\n# The list of \"small words\" which are not capped comes from\n# the New York Times Manual of Style, plus 'vs' and 'v'. \n#\n# 10 May 2008\n# Original version by John Gruber:\n# http://daringfireball.net/2008/05/title_case\n#\n# 28 July 2008\n# Re-written and much improved by Aristotle Pagaltzis:\n# http://plasmasturm.org/code/titlecase/\n#\n# Full change log at __END__.\n#\n# License: http://www.opensource.org/licenses/mit-license.php\n#\n\n\nuse strict;\nuse warnings;\nuse utf8;\nuse open qw( :encoding(UTF-8) :std );\n\n\nmy @small_words = qw( (?<!q&)a an and as at(?!&t) but by en for if in of on or the to v[.]? via vs[.]? );\nmy $small_re = join '|', @small_words;\n\nmy $apos = qr/ (?: ['’] [[:lower:]]* )? /x;\n\nwhile ( <> ) {\n s{\\A\\s+}{}, s{\\s+\\z}{};\n\n $_ = lc $_ if not /[[:lower:]]/;\n\n s{\n \\b (_*) (?:\n ( (?<=[ ][/\\\\]) [[:alpha:]]+ [-_[:alpha:]/\\\\]+ | # file path or\n [-_[:alpha:]]+ [@.:] [-_[:alpha:]@.:/]+ $apos ) # URL, domain, or email\n |\n ( (?i: $small_re ) $apos ) # or small word (case-insensitive)\n |\n ( [[:alpha:]] [[:lower:]'’()\\[\\]{}]* $apos ) # or word w/o internal caps\n |\n ( [[:alpha:]] [[:alpha:]'’()\\[\\]{}]* $apos ) # or some other word\n ) (_*) \\b\n }{\n $1 . (\n defined $2 ? $2 # preserve URL, domain, or email\n : defined $3 ? \"\\L$3\" # lowercase small word\n : defined $4 ? \"\\u\\L$4\" # capitalize word w/o internal caps\n : $5 # preserve other kinds of word\n ) . $6\n }xeg;\n\n\n # Exceptions for small words: capitalize at start and end of title\n s{\n ( \\A [[:punct:]]* # start of title...\n | [:.;?!][ ]+ # or of subsentence...\n | [ ]['\"“‘(\\[][ ]* ) # or of inserted subphrase...\n ( $small_re ) \\b # ... followed by small word\n }{$1\\u\\L$2}xig;\n\n s{\n \\b ( $small_re ) # small word...\n (?= [[:punct:]]* \\Z # ... at the end of the title...\n | ['\"’”)\\]] [ ] ) # ... or of an inserted subphrase?\n }{\\u\\L$1}xig;\n\n # Exceptions for small words in hyphenated compound words\n ## e.g. \"in-flight\" -> In-Flight\n s{\n \\b\n (?<! -) # Negative lookbehind for a hyphen; we don't want to match man-in-the-middle but do want (in-flight)\n ( $small_re )\n (?= -[[:alpha:]]+) # lookahead for \"-someword\"\n }{\\u\\L$1}xig;\n\n ## # e.g. \"Stand-in\" -> \"Stand-In\" (Stand is already capped at this point)\n s{\n \\b\n (?<!…) # Negative lookbehind for a hyphen; we don't want to match man-in-the-middle but do want (stand-in)\n ( [[:alpha:]]+- ) # $1 = first word and hyphen, should already be properly capped\n ( $small_re ) # ... followed by small word\n (?! - ) # Negative lookahead for another '-'\n }{$1\\u$2}xig;\n\n print \"$_\";\n}\n\n__END__\n" }, { "answer_id": 33168, "author": "Markus Olsson", "author_id": 2114, "author_profile": "https://Stackoverflow.com/users/2114", "pm_score": 5, "selected": true, "text": "using System.Globalization;\n\nCultureInfo.InvariantCulture.TextInfo.ToTitleCase(\"GeOrGE bUrdEll\")\n" }, { "answer_id": 33291, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 1, "selected": false, "text": "public class ProperCaseHelper {\n public string ToProperCase(string input) {\n string ret = string.Empty;\n\n var words = input.Split(' ');\n\n for (int i = 0; i < words.Length; ++i) {\n ret += wordToProperCase(words[i]);\n if (i < words.Length - 1) ret += \" \";\n }\n\n return ret;\n }\n\n private string wordToProperCase(string word) {\n if (string.IsNullOrEmpty(word)) return word;\n\n // Standard case\n string ret = capitaliseFirstLetter(word);\n\n // Special cases:\n ret = properSuffix(ret, \"'\");\n ret = properSuffix(ret, \".\");\n ret = properSuffix(ret, \"Mc\");\n ret = properSuffix(ret, \"Mac\");\n\n return ret;\n }\n\n private string properSuffix(string word, string prefix) {\n if(string.IsNullOrEmpty(word)) return word;\n\n string lowerWord = word.ToLower(), lowerPrefix = prefix.ToLower();\n if (!lowerWord.Contains(lowerPrefix)) return word;\n\n int index = lowerWord.IndexOf(lowerPrefix);\n\n // If the search string is at the end of the word ignore.\n if (index + prefix.Length == word.Length) return word;\n\n return word.Substring(0, index) + prefix +\n capitaliseFirstLetter(word.Substring(index + prefix.Length));\n }\n\n private string capitaliseFirstLetter(string word) {\n return char.ToUpper(word[0]) + word.Substring(1).ToLower();\n }\n}\n" }, { "answer_id": 485362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "`if (!lowerWord.Contains(lowerPrefix)) return word`;\n if (!lowerWord.StartsWith(lowerPrefix)) return word;\n" }, { "answer_id": 3553524, "author": "Dasith Wijes", "author_id": 422427, "author_profile": "https://Stackoverflow.com/users/422427", "pm_score": 0, "selected": false, "text": "Public Shared Function DoProperCaseConvert(ByVal str As String, Optional ByVal allowCapital As Boolean = True) As String\n Dim strCon As String = \"\"\n Dim wordbreak As String = \" ,.1234567890;/\\-()#$%^&*€!~+=@\"\n Dim nextShouldBeCapital As Boolean = True\n\n 'Improve to recognize all caps input\n 'If str.Equals(str.ToUpper) Then\n ' str = str.ToLower\n 'End If\n\n For Each s As Char In str.ToCharArray\n\n If allowCapital Then\n strCon = strCon & If(nextShouldBeCapital, s.ToString.ToUpper, s)\n Else\n strCon = strCon & If(nextShouldBeCapital, s.ToString.ToUpper, s.ToLower)\n End If\n\n If wordbreak.Contains(s.ToString) Then\n nextShouldBeCapital = True\n Else\n nextShouldBeCapital = False\n End If\n Next\n\n Return strCon\nEnd Function\n" }, { "answer_id": 6576464, "author": "Colin", "author_id": 645902, "author_profile": "https://Stackoverflow.com/users/645902", "pm_score": 4, "selected": false, "text": "void Main()\n{\n List<string> names = new List<string>() {\n \"bill o'reilly\", \n \"johannes diderik van der waals\", \n \"mr. moseley-williams\", \n \"Joe VanWyck\", \n \"mcdonald's\", \n \"william the third\", \n \"hrh prince charles\", \n \"h.r.m. queen elizabeth the third\",\n \"william gates, iii\", \n \"pope leo xii\",\n \"a.k. jennings\"\n };\n \n names.Select(name => name.ToProperCase()).Dump();\n}\n\n// http://stackoverflow.com/questions/32149/does-anyone-have-a-good-proper-case-algorithm\npublic static class ProperCaseHelper\n{\n public static string ToProperCase(this string input)\n {\n if (IsAllUpperOrAllLower(input))\n {\n // fix the ALL UPPERCASE or all lowercase names\n return string.Join(\" \", input.Split(' ').Select(word => wordToProperCase(word)));\n }\n else\n {\n // leave the CamelCase or Propercase names alone\n return input;\n }\n }\n\n public static bool IsAllUpperOrAllLower(this string input)\n {\n return (input.ToLower().Equals(input) || input.ToUpper().Equals(input));\n }\n\n private static string wordToProperCase(string word)\n {\n if (string.IsNullOrEmpty(word)) return word;\n\n // Standard case\n string ret = capitaliseFirstLetter(word);\n\n // Special cases:\n ret = properSuffix(ret, \"'\"); // D'Artagnon, D'Silva\n ret = properSuffix(ret, \".\"); // ???\n ret = properSuffix(ret, \"-\"); // Oscar-Meyer-Weiner\n ret = properSuffix(ret, \"Mc\", t => t.Length > 4); // Scots\n ret = properSuffix(ret, \"Mac\", t => t.Length > 5); // Scots except Macey\n\n // Special words:\n ret = specialWords(ret, \"van\"); // Dick van Dyke\n ret = specialWords(ret, \"von\"); // Baron von Bruin-Valt\n ret = specialWords(ret, \"de\");\n ret = specialWords(ret, \"di\");\n ret = specialWords(ret, \"da\"); // Leonardo da Vinci, Eduardo da Silva\n ret = specialWords(ret, \"of\"); // The Grand Old Duke of York\n ret = specialWords(ret, \"the\"); // William the Conqueror\n ret = specialWords(ret, \"HRH\"); // His/Her Royal Highness\n ret = specialWords(ret, \"HRM\"); // His/Her Royal Majesty\n ret = specialWords(ret, \"H.R.H.\"); // His/Her Royal Highness\n ret = specialWords(ret, \"H.R.M.\"); // His/Her Royal Majesty\n\n ret = dealWithRomanNumerals(ret); // William Gates, III\n\n return ret;\n }\n\n private static string properSuffix(string word, string prefix, Func<string, bool> condition = null)\n {\n if (string.IsNullOrEmpty(word)) return word;\n if (condition != null && ! condition(word)) return word;\n \n string lowerWord = word.ToLower();\n string lowerPrefix = prefix.ToLower();\n\n if (!lowerWord.Contains(lowerPrefix)) return word;\n\n int index = lowerWord.IndexOf(lowerPrefix);\n\n // If the search string is at the end of the word ignore.\n if (index + prefix.Length == word.Length) return word;\n\n return word.Substring(0, index) + prefix +\n capitaliseFirstLetter(word.Substring(index + prefix.Length));\n }\n\n private static string specialWords(string word, string specialWord)\n {\n if (word.Equals(specialWord, StringComparison.InvariantCultureIgnoreCase))\n {\n return specialWord;\n }\n else\n {\n return word;\n }\n }\n\n private static string dealWithRomanNumerals(string word)\n {\n // Roman Numeral parser thanks to [djk](https://stackoverflow.com/users/785111/djk)\n // Note that it excludes the Chinese last name Xi\n return new Regex(@\"\\b(?!Xi\\b)(X|XX|XXX|XL|L|LX|LXX|LXXX|XC|C)?(I|II|III|IV|V|VI|VII|VIII|IX)?\\b\", RegexOptions.IgnoreCase).Replace(word, match => match.Value.ToUpperInvariant());\n }\n\n private static string capitaliseFirstLetter(string word)\n {\n return char.ToUpper(word[0]) + word.Substring(1).ToLower();\n }\n\n}\n" }, { "answer_id": 22058928, "author": "gillytech", "author_id": 1332828, "author_profile": "https://Stackoverflow.com/users/1332828", "pm_score": 2, "selected": false, "text": "mary-jane => Mary-Jane o'brien => O'Brien Joël VON WINTEREGG => Joël von Winteregg jose de la acosta => Jose de la Acosta function name_title_case($str)\n{\n // name parts that should be lowercase in most cases\n $ok_to_be_lower = array('av','af','da','dal','de','del','der','di','la','le','van','der','den','vel','von');\n // name parts that should be lower even if at the beginning of a name\n $always_lower = array('van', 'der');\n\n // Create an array from the parts of the string passed in\n $parts = explode(\" \", mb_strtolower($str));\n\n foreach ($parts as $part)\n {\n (in_array($part, $ok_to_be_lower)) ? $rules[$part] = 'nocaps' : $rules[$part] = 'caps';\n }\n\n // Determine the first part in the string\n reset($rules);\n $first_part = key($rules);\n\n // Loop through and cap-or-dont-cap\n foreach ($rules as $part => $rule)\n {\n if ($rule == 'caps')\n {\n // ucfirst() words and also takes into account apostrophes and hyphens like this:\n // O'brien -> O'Brien || mary-kaye -> Mary-Kaye\n $part = str_replace('- ','-',ucwords(str_replace('-','- ', $part)));\n $c13n[] = str_replace('\\' ', '\\'', ucwords(str_replace('\\'', '\\' ', $part)));\n }\n else if ($part == $first_part && !in_array($part, $always_lower))\n {\n // If the first part of the string is ok_to_be_lower, cap it anyway\n $c13n[] = ucfirst($part);\n }\n else\n {\n $c13n[] = $part;\n }\n }\n\n $titleized = implode(' ', $c13n);\n\n return trim($titleized);\n}\n" }, { "answer_id": 45774526, "author": "user326608", "author_id": 326608, "author_profile": "https://Stackoverflow.com/users/326608", "pm_score": 2, "selected": false, "text": "public static class CIQNameCase\n{\n static Dictionary<string, string> _exceptions = new Dictionary<string, string>\n {\n {@\"\\bMacEdo\" ,\"Macedo\"},\n {@\"\\bMacEvicius\" ,\"Macevicius\"},\n {@\"\\bMacHado\" ,\"Machado\"},\n {@\"\\bMacHar\" ,\"Machar\"},\n {@\"\\bMacHin\" ,\"Machin\"},\n {@\"\\bMacHlin\" ,\"Machlin\"},\n {@\"\\bMacIas\" ,\"Macias\"},\n {@\"\\bMacIulis\" ,\"Maciulis\"},\n {@\"\\bMacKie\" ,\"Mackie\"},\n {@\"\\bMacKle\" ,\"Mackle\"},\n {@\"\\bMacKlin\" ,\"Macklin\"},\n {@\"\\bMacKmin\" ,\"Mackmin\"},\n {@\"\\bMacQuarie\" ,\"Macquarie\"}\n };\n\n static Dictionary<string, string> _replacements = new Dictionary<string, string>\n {\n {@\"\\bAl(?=\\s+\\w)\" , @\"al\"}, // al Arabic or forename Al.\n {@\"\\b(Bin|Binti|Binte)\\b\" , @\"bin\"}, // bin, binti, binte Arabic\n {@\"\\bAp\\b\" , @\"ap\"}, // ap Welsh.\n {@\"\\bBen(?=\\s+\\w)\" , @\"ben\"}, // ben Hebrew or forename Ben.\n {@\"\\bDell([ae])\\b\" , @\"dell$1\"}, // della and delle Italian.\n {@\"\\bD([aeiou])\\b\" , @\"d$1\"}, // da, de, di Italian; du French; do Brasil\n {@\"\\bD([ao]s)\\b\" , @\"d$1\"}, // das, dos Brasileiros\n {@\"\\bDe([lrn])\\b\" , @\"de$1\"}, // del Italian; der/den Dutch/Flemish.\n {@\"\\bEl\\b\" , @\"el\"}, // el Greek or El Spanish.\n {@\"\\bLa\\b\" , @\"la\"}, // la French or La Spanish.\n {@\"\\bL([eo])\\b\" , @\"l$1\"}, // lo Italian; le French.\n {@\"\\bVan(?=\\s+\\w)\" , @\"van\"}, // van German or forename Van.\n {@\"\\bVon\\b\" , @\"von\"} // von Dutch/Flemish\n };\n\n static string[] _conjunctions = { \"Y\", \"E\", \"I\" };\n\n static string _romanRegex = @\"\\b((?:[Xx]{1,3}|[Xx][Ll]|[Ll][Xx]{0,3})?(?:[Ii]{1,3}|[Ii][VvXx]|[Vv][Ii]{0,3})?)\\b\";\n\n /// <summary>\n /// Case a name field into its appropriate case format \n /// e.g. Smith, de la Cruz, Mary-Jane, O'Brien, McTaggart\n /// </summary>\n /// <param name=\"nameString\"></param>\n /// <returns></returns>\n public static string NameCase(string nameString)\n {\n // Capitalize\n nameString = Capitalize(nameString);\n nameString = UpdateIrish(nameString);\n\n // Fixes for \"son (daughter) of\" etc\n foreach (var replacement in _replacements.Keys)\n {\n if (Regex.IsMatch(nameString, replacement))\n {\n Regex rgx = new Regex(replacement);\n nameString = rgx.Replace(nameString, _replacements[replacement]);\n } \n }\n\n nameString = UpdateRoman(nameString);\n nameString = FixConjunction(nameString);\n\n return nameString;\n }\n\n /// <summary>\n /// Capitalize first letters.\n /// </summary>\n /// <param name=\"nameString\"></param>\n /// <returns></returns>\n private static string Capitalize(string nameString)\n {\n nameString = nameString.ToLower();\n nameString = Regex.Replace(nameString, @\"\\b\\w\", x => x.ToString().ToUpper());\n nameString = Regex.Replace(nameString, @\"'\\w\\b\", x => x.ToString().ToLower()); // Lowercase 's\n return nameString;\n }\n\n /// <summary>\n /// Update for Irish names.\n /// </summary>\n /// <param name=\"nameString\"></param>\n /// <returns></returns>\n private static string UpdateIrish(string nameString)\n {\n if(Regex.IsMatch(nameString, @\".*?\\bMac[A-Za-z^aciozj]{2,}\\b\") || Regex.IsMatch(nameString, @\".*?\\bMc\"))\n {\n nameString = UpdateMac(nameString);\n } \n return nameString;\n }\n\n /// <summary>\n /// Updates irish Mac & Mc.\n /// </summary>\n /// <param name=\"nameString\"></param>\n /// <returns></returns>\n private static string UpdateMac(string nameString)\n {\n MatchCollection matches = Regex.Matches(nameString, @\"\\b(Ma?c)([A-Za-z]+)\");\n if(matches.Count == 1 && matches[0].Groups.Count == 3)\n {\n string replacement = matches[0].Groups[1].Value;\n replacement += matches[0].Groups[2].Value.Substring(0, 1).ToUpper();\n replacement += matches[0].Groups[2].Value.Substring(1);\n nameString = nameString.Replace(matches[0].Groups[0].Value, replacement);\n\n // Now fix \"Mac\" exceptions\n foreach (var exception in _exceptions.Keys)\n {\n nameString = Regex.Replace(nameString, exception, _exceptions[exception]);\n }\n }\n return nameString;\n }\n\n /// <summary>\n /// Fix roman numeral names.\n /// </summary>\n /// <param name=\"nameString\"></param>\n /// <returns></returns>\n private static string UpdateRoman(string nameString)\n {\n MatchCollection matches = Regex.Matches(nameString, _romanRegex);\n if (matches.Count > 1)\n {\n foreach(Match match in matches)\n {\n if(!string.IsNullOrEmpty(match.Value))\n {\n nameString = Regex.Replace(nameString, match.Value, x => x.ToString().ToUpper());\n }\n }\n }\n return nameString;\n }\n\n /// <summary>\n /// Fix Spanish conjunctions.\n /// </summary>\n /// <param name=\"\"></param>\n /// <returns></returns>\n private static string FixConjunction(string nameString)\n { \n foreach (var conjunction in _conjunctions)\n {\n nameString = Regex.Replace(nameString, @\"\\b\" + conjunction + @\"\\b\", x => x.ToString().ToLower());\n }\n return nameString;\n }\n}\n string name_cased = CIQNameCase.NameCase(\"McCarthy\");\n [TestMethod]\npublic void Test_NameCase_1()\n{\n string[] names = {\n \"Keith\", \"Yuri's\", \"Leigh-Williams\", \"McCarthy\",\n // Mac exceptions\n \"Machin\", \"Machlin\", \"Machar\",\n \"Mackle\", \"Macklin\", \"Mackie\",\n \"Macquarie\", \"Machado\", \"Macevicius\",\n \"Maciulis\", \"Macias\", \"MacMurdo\",\n // General\n \"O'Callaghan\", \"St. John\", \"von Streit\",\n \"van Dyke\", \"Van\", \"ap Llwyd Dafydd\",\n \"al Fahd\", \"Al\",\n \"el Grecco\",\n \"ben Gurion\", \"Ben\",\n \"da Vinci\",\n \"di Caprio\", \"du Pont\", \"de Legate\",\n \"del Crond\", \"der Sind\", \"van der Post\", \"van den Thillart\",\n \"von Trapp\", \"la Poisson\", \"le Figaro\",\n \"Mack Knife\", \"Dougal MacDonald\",\n \"Ruiz y Picasso\", \"Dato e Iradier\", \"Mas i Gavarró\",\n // Roman numerals\n \"Henry VIII\", \"Louis III\", \"Louis XIV\",\n \"Charles II\", \"Fred XLIX\", \"Yusof bin Ishak\",\n };\n\n foreach(string name in names)\n {\n string name_upper = name.ToUpper();\n string name_cased = CIQNameCase.NameCase(name_upper);\n Console.WriteLine(string.Format(\"name: {0} -> {1} -> {2}\", name, name_upper, name_cased));\n Assert.IsTrue(name == name_cased);\n }\n\n}\n" }, { "answer_id": 45872439, "author": "Klyphtn", "author_id": 4705498, "author_profile": "https://Stackoverflow.com/users/4705498", "pm_score": 0, "selected": false, "text": "public static String toProperName(String name)\n{\n if (name != null)\n {\n if (name.Length >= 2 && name.ToLower().Substring(0, 2) == \"mc\") // Changes mcdonald to \"McDonald\"\n return \"Mc\" + Regex.Replace(name.ToLower().Substring(2), @\"\\b[a-z]\", m => m.Value.ToUpper());\n\n if (name.Length >= 3 && name.ToLower().Substring(0, 3) == \"van\") // Changes vanwinkle to \"VanWinkle\"\n return \"Van\" + Regex.Replace(name.ToLower().Substring(3), @\"\\b[a-z]\", m => m.Value.ToUpper());\n\n return Regex.Replace(name.ToLower(), @\"\\b[a-z]\", m => m.Value.ToUpper()); // Changes to title case but also fixes \n // appostrophes like O'HARE or o'hare to O'Hare\n }\n\n return \"\";\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3203/" ]
32,151
<p>Is there a way to export a simple HTML page to Word (.doc format, not .docx) without having Microsoft Word installed?</p>
[ { "answer_id": 32176, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 5, "selected": true, "text": "application/msword doc" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3396/" ]
32,168
<p>A question related to <a href="https://stackoverflow.com/questions/28002">Regular cast vs. static_cast vs. dynamic_cast</a>:</p> <p>What cast syntax style do you prefer in C++?</p> <ul> <li>C-style cast syntax: <code>(int)foo</code></li> <li>C++-style cast syntax: <code>static_cast&lt;int&gt;(foo)</code></li> <li>constructor syntax: <code>int(foo)</code></li> </ul> <p>They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?).</p> <p>If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax.</p> <p>What do you think?</p>
[ { "answer_id": 32224, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": true, "text": "void f(auto_ptr<int> x);\n\nf(static_cast<auto_ptr<int> >(new int(5))); // GOOD\nf(auto_ptr<int>(new int(5)); // BAD\n static_cast auto_ptr" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2686/" ]
32,173
<p>I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is <code>RadioButton</code>)) is never hit and the RadioButton control is identified as a <code>Checkbox</code> control.</p> <pre><code> private static void DisableControl(WebControl control) { if (control is CheckBox) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (control is RadioButton) { } else if (control is ImageButton) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } </code></pre> <p>Two Questions:<br> 1. How do I identify which control is a radiobutton? <br> 2. How do I disable it so that it posts back its value?</p>
[ { "answer_id": 32473, "author": "Nicholas", "author_id": 2808, "author_profile": "https://Stackoverflow.com/users/2808", "pm_score": 3, "selected": true, "text": " private static void DisableControl(WebControl control)\n {\n Type controlType = control.GetType();\n\n if (controlType == typeof(CheckBox))\n {\n ((CheckBox)control).InputAttributes.Add(\"disabled\", \"disabled\");\n\n }\n else if (controlType == typeof(RadioButton))\n {\n ((RadioButton)control).InputAttributes.Add(\"disabled\", \"true\");\n }\n else if (controlType == typeof(ImageButton))\n {\n ((ImageButton)control).Enabled = false;\n }\n else\n {\n control.Attributes.Add(\"readonly\", \"readonly\");\n }\n }\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2808/" ]
32,175
<p>I'm trying to install a .NET service I wrote. As recommended by MSDN, I'm using InstallUtil. But I have missed how I can set the default service user on the command-line or even in the service itself. Now, when InstallUtil is run, it will display a dialog asking the user for the credentials for a user. I'm trying to integrate the service installation into a larger install and need the service installation to remain silent.</p>
[ { "answer_id": 50661256, "author": "D. Lockett", "author_id": 7716585, "author_profile": "https://Stackoverflow.com/users/7716585", "pm_score": 0, "selected": false, "text": "/username /password installutil.exe /username=user /password=password yourservice.exe\n public override void Install(IDictionary stateSaver)\n{\n serviceProcessInstaller1.Username=\"<username>\";\n serviceProcessInstaller1.Password=\"<password>\";\n base.Install(stateSaver);\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2494/" ]
32,231
<p>Are there any rapid Database protoyping tools that don't require me to declare a database schema, but rather create it based on the way I'm using my entities.</p> <p>For example, assuming an empty database (pseudo code):</p> <pre><code>user1 = new User() // Creates the user table with a single id column user1.firstName = "Allain" // alters the table to have a firstName column as varchar(255) user2 = new User() // Reuses the table user2.firstName = "Bob" user2.lastName = "Loblaw" // Alters the table to have a last name column </code></pre> <p>Since there are logical assumptions that can be made when dynamically creating the schema, and you could always override its choices by using your DB tools to tweak it later.</p> <p>Also, you could generate your schema by unit testing it this way.</p> <p>And obviously this is only for prototyping.</p> <p>Is there anything like this out there?</p>
[ { "answer_id": 32463, "author": "Ed.T", "author_id": 3014, "author_profile": "https://Stackoverflow.com/users/3014", "pm_score": 1, "selected": false, "text": "class User {\n\n String userName\n String firstName\n String lastName\n Date dateCreated\n Date lastUpdated\n\n static constraints = {\n userName(blank: false, unique: true)\n firstName(blank: false)\n lastName(blank: false)\n }\n\n String toString() {\"$lastName, $firstName\"}\n\n}\n" }, { "answer_id": 52086, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 1, "selected": false, "text": "[ActiveRecord]\npublic class User : ActiveRecordBase<User>\n{\n [PrimaryKey]\n public Int32 UserId { get; set; }\n\n [Property]\n public String FirstName { get; set; }\n}\n ActiveRecordStarter.Initialize();\nActiveRecordStarter.CreateSchema();\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
32,241
<p><a href="https://stackoverflow.com/questions/32149/does-anyone-have-a-good-proper-case-algorithm">Using this question</a> as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.</p> <p>For example:</p> <pre><code>mynameisfred </code></pre> <p>becomes</p> <pre><code>Camel: myNameIsFred Pascal: MyNameIsFred </code></pre>
[ { "answer_id": 32429, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 3, "selected": true, "text": "camelCase(\"hithisisatest\");\n \"hiThisIsATest\"\n \"hitHisIsATest\"\n SetPhraseCase(phrase, CamelOrPascal):\n if no delimiters\n if camelCase\n return lowerFirstLetter(phrase)\n else\n return capitaliseFirstLetter(phrase)\n words = splitOnDelimiter(phrase)\n if camelCase \n ret = lowerFirstLetter(first word) \n else\n ret = capitaliseFirstLetter(first word)\n for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])\n return ret\n\ncapitaliseFirstLetter(word):\n if len(word) <= 1 return upper(word)\n return upper(word[0]) + word[1..len(word)]\n\nlowerFirstLetter(word):\n if len(word) <= 1 return lower(word)\n return lower(word[0]) + word[1..len(word)]\n using System;\n\nclass Program {\n static void Main(string[] args) {\n\n var caseAlgorithm = new CaseAlgorithm('_');\n\n while (true) {\n string input = Console.ReadLine();\n\n if (string.IsNullOrEmpty(input)) return;\n\n Console.WriteLine(\"Input '{0}' in camel case: '{1}', pascal case: '{2}'\",\n input,\n caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),\n caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));\n }\n }\n}\n\npublic class CaseAlgorithm {\n\n public enum CaseMode { PascalCase, CamelCase }\n\n private char delimiterChar;\n\n public CaseAlgorithm(char inDelimiterChar) {\n delimiterChar = inDelimiterChar;\n }\n\n public string SetPhraseCase(string phrase, CaseMode caseMode) {\n\n // You might want to do some sanity checks here like making sure\n // there's no invalid characters, etc.\n\n if (string.IsNullOrEmpty(phrase)) return phrase;\n\n // .Split() will simply return a string[] of size 1 if no delimiter present so\n // no need to explicitly check this.\n var words = phrase.Split(delimiterChar);\n\n // Set first word accordingly.\n string ret = setWordCase(words[0], caseMode);\n\n // If there are other words, set them all to pascal case.\n if (words.Length > 1) {\n for (int i = 1; i < words.Length; ++i)\n ret += setWordCase(words[i], CaseMode.PascalCase);\n }\n\n return ret;\n }\n\n private string setWordCase(string word, CaseMode caseMode) {\n switch (caseMode) {\n case CaseMode.CamelCase:\n return lowerFirstLetter(word);\n case CaseMode.PascalCase:\n return capitaliseFirstLetter(word);\n default:\n throw new NotImplementedException(\n string.Format(\"Case mode '{0}' is not recognised.\", caseMode.ToString()));\n }\n }\n\n private string lowerFirstLetter(string word) {\n return char.ToLower(word[0]) + word.Substring(1);\n }\n\n private string capitaliseFirstLetter(string word) {\n return char.ToUpper(word[0]) + word.Substring(1);\n }\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
32,243
<p>The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. </p> <p>Even though <code>imagesavealpha</code> is set, something isn't quite right.</p> <p>What's the best way to preserve the transparency in the resampled image?</p> <pre><code>$uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); imagesavealpha( $targetImage, true ); $targetImage = imagecreatetruecolor( 128, 128 ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 ); </code></pre>
[ { "answer_id": 32270, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 4, "selected": false, "text": "$srcImage = imagecreatefrompng($uploadTempFile);\nimagealphablending($srcImage, false);\nimagesavealpha($srcImage, true);\n imagealphablending" }, { "answer_id": 32302, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 9, "selected": true, "text": "imagealphablending( $targetImage, false );\nimagesavealpha( $targetImage, true );\n $uploadTempFile = $myField[ 'tmp_name' ]\nlist( $uploadWidth, $uploadHeight, $uploadType ) \n = getimagesize( $uploadTempFile );\n\n$srcImage = imagecreatefrompng( $uploadTempFile ); \n\n$targetImage = imagecreatetruecolor( 128, 128 ); \nimagealphablending( $targetImage, false );\nimagesavealpha( $targetImage, true );\n\nimagecopyresampled( $targetImage, $srcImage, \n 0, 0, \n 0, 0, \n 128, 128, \n $uploadWidth, $uploadHeight );\n\nimagepng( $targetImage, 'out.png', 9 );\n" }, { "answer_id": 37364, "author": "Kalle", "author_id": 3908, "author_profile": "https://Stackoverflow.com/users/3908", "pm_score": 2, "selected": false, "text": "getimagesize() imagecopyresmapled() $uploadWidth $uploadHeight -1 0 1 imagesx($targetImage) - 1 imagesy($targetImage) - 1" }, { "answer_id": 291766, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "$im = ImageCreateFromPNG($source);\n$new_im = imagecreatetruecolor($new_size[0],$new_size[1]);\nimagecolortransparent($new_im, imagecolorallocate($new_im, 0, 0, 0));\nimagecopyresampled($new_im,$im,0,0,0,0,$new_size[0],$new_size[1],$size[0],$size[1]);\n" }, { "answer_id": 1302888, "author": "Linus Unnebäck", "author_id": 148072, "author_profile": "https://Stackoverflow.com/users/148072", "pm_score": 3, "selected": false, "text": "$uploadTempFile = $myField[ 'tmp_name' ]\nlist( $uploadWidth, $uploadHeight, $uploadType ) \n = getimagesize( $uploadTempFile );\n\n$srcImage = imagecreatefrompng( $uploadTempFile );\n\n$targetImage = imagecreatetruecolor( 128, 128 );\n\n$transparent = imagecolorallocate($targetImage,0,255,0);\nimagecolortransparent($targetImage,$transparent);\nimagefilledrectangle($targetImage,0,0,127,127,$transparent);\n\nimagecopyresampled( $targetImage, $srcImage, \n 0, 0, \n 0, 0, \n 128, 128, \n $uploadWidth, $uploadHeight );\n\nimagepng( $targetImage, 'out.png', 9 );\n" }, { "answer_id": 7731400, "author": "pricopz", "author_id": 990203, "author_profile": "https://Stackoverflow.com/users/990203", "pm_score": 3, "selected": false, "text": "copyimageresample $myfile=$_FILES[\"youimage\"];\n\nfunction ismyimage($myfile) {\n if((($myfile[\"type\"] == \"image/gif\") || ($myfile[\"type\"] == \"image/jpg\") || ($myfile[\"type\"] == \"image/jpeg\") || ($myfile[\"type\"] == \"image/png\")) && ($myfile[\"size\"] <= 2097152 /*2mb*/) ) return true; \n else return false;\n}\n\nfunction upload_file($myfile) { \n if(ismyimage($myfile)) {\n $information=getimagesize($myfile[\"tmp_name\"]);\n $mywidth=$information[0];\n $myheight=$information[1];\n\n $newwidth=$mywidth;\n $newheight=$myheight;\n while(($newwidth > 600) || ($newheight > 400 )) {\n $newwidth = $newwidth-ceil($newwidth/100);\n $newheight = $newheight-ceil($newheight/100);\n } \n\n $files=$myfile[\"name\"];\n\n if($myfile[\"type\"] == \"image/gif\") {\n $tmp=imagecreatetruecolor($newwidth,$newheight);\n $src=imagecreatefromgif($myfile[\"tmp_name\"]);\n imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n $con=imagegif($tmp, $files);\n imagedestroy($tmp);\n imagedestroy($src);\n if($con){\n return true;\n } else {\n return false;\n }\n } else if(($myfile[\"type\"] == \"image/jpg\") || ($myfile[\"type\"] == \"image/jpeg\") ) {\n $tmp=imagecreatetruecolor($newwidth,$newheight);\n $src=imagecreatefromjpeg($myfile[\"tmp_name\"]); \n imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n $con=imagejpeg($tmp, $files);\n imagedestroy($tmp);\n imagedestroy($src);\n if($con) { \n return true;\n } else {\n return false;\n }\n } else if($myfile[\"type\"] == \"image/png\") {\n $tmp=imagecreatetruecolor($newwidth,$newheight);\n $src=imagecreatefrompng($myfile[\"tmp_name\"]);\n imagealphablending($tmp, false);\n imagesavealpha($tmp,true);\n $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);\n imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent); \n imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n $con=imagepng($tmp, $files);\n imagedestroy($tmp);\n imagedestroy($src);\n if($con) {\n return true;\n } else {\n return false;\n }\n } \n } else\n return false;\n}\n" }, { "answer_id": 37871122, "author": "Md. Imadul Islam", "author_id": 3950386, "author_profile": "https://Stackoverflow.com/users/3950386", "pm_score": 0, "selected": false, "text": "$imageFileType = pathinfo($_FILES[\"image\"][\"name\"], PATHINFO_EXTENSION);\n$filename = 'test.' . $imageFileType;\nmove_uploaded_file($_FILES[\"image\"][\"tmp_name\"], $filename);\n\n$source_image = imagecreatefromjpeg($filename);\n\n$source_imagex = imagesx($source_image);\n$source_imagey = imagesy($source_image);\n\n$dest_imagex = 400;\n$dest_imagey = 600;\n$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);\n\nimagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);\n\nimagesavealpha($dest_image, true);\n$trans_colour = imagecolorallocatealpha($dest_image, 0, 0, 0, 127);\nimagefill($dest_image, 0, 0, $trans_colour);\n\nimagepng($dest_image,\"test1.png\",1);\n" }, { "answer_id": 46084683, "author": "nsinvocation", "author_id": 1804311, "author_profile": "https://Stackoverflow.com/users/1804311", "pm_score": 0, "selected": false, "text": "width height imagecopyresampled" }, { "answer_id": 51810856, "author": "Marco", "author_id": 2969320, "author_profile": "https://Stackoverflow.com/users/2969320", "pm_score": 0, "selected": false, "text": "$img3 = imagecreatetruecolor(128, 128);\nimagecolortransparent($img3, imagecolorallocate($img3, 0, 0, 0));\nimagealphablending( $img3, false );\nimagesavealpha( $img3, true );\nimagecopyresampled($img3, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight);\nimagepng($img3, 'filename.png', 9);\n" }, { "answer_id": 72346188, "author": "Lepy", "author_id": 11582724, "author_profile": "https://Stackoverflow.com/users/11582724", "pm_score": 0, "selected": false, "text": "imagecopyresampled imagerotate // get image sizes (X,Y)\n $wx = imagesx($imageW);\n $wy = imagesy($imageW);\n\n // create a new image from the sizes on transparent canvas\n $new = imagecreatetruecolor($wx, $wy);\n\n $transparent = imagecolorallocatealpha($new, 0, 0, 0, 127);\n $rotate = imagerotate($imageW, 280, $transparent);\n imagealphablending($rotate, true);\n imagesavealpha($rotate, true);\n\n // get the newest image X and Y\n $ix = imagesx($rotate);\n $iy = imagesy($rotate);\n\n //copy the image to the canvas\n imagecopyresampled($destImg, $rotate, 940, 2050, 0, 0, $ix, $iy, $ix, $iy);\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1820/" ]
32,260
<p>Instead of relying on my host to send an email, I was thinking of sending the email messages using my <strong>Gmail</strong> account. The emails are personalized emails to the bands I play on my show. </p> <p>Is it possible to do it?</p>
[ { "answer_id": 32336, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 11, "selected": true, "text": "System.Net.Mail System.Web.Mail System.Web.Mail using System.Net;\nusing System.Net.Mail;\n\nvar fromAddress = new MailAddress(\"[email protected]\", \"From Name\");\nvar toAddress = new MailAddress(\"[email protected]\", \"To Name\");\nconst string fromPassword = \"fromPassword\";\nconst string subject = \"Subject\";\nconst string body = \"Body\";\n\nvar smtp = new SmtpClient\n{\n Host = \"smtp.gmail.com\",\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n UseDefaultCredentials = false,\n Credentials = new NetworkCredential(fromAddress.Address, fromPassword)\n};\nusing (var message = new MailMessage(fromAddress, toAddress)\n{\n Subject = subject,\n Body = body\n})\n{\n smtp.Send(message);\n}\n fromPassword" }, { "answer_id": 489594, "author": "Donny V.", "author_id": 1231, "author_profile": "https://Stackoverflow.com/users/1231", "pm_score": 7, "selected": false, "text": "DeliveryMethod = SmtpDeliveryMethod.Network using System.Net.Mail;\nusing System.Net;\n\nvar fromAddress = new MailAddress(\"[email protected]\", \"From Name\");\nvar toAddress = new MailAddress(\"[email protected]\", \"To Name\");\nconst string fromPassword = \"password\";\nconst string subject = \"test\";\nconst string body = \"Hey now!!\";\n\nvar smtp = new SmtpClient\n{\n Host = \"smtp.gmail.com\",\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n Credentials = new NetworkCredential(fromAddress.Address, fromPassword),\n Timeout = 20000\n};\nusing (var message = new MailMessage(fromAddress, toAddress)\n{\n Subject = subject,\n Body = body\n})\n{\n smtp.Send(message);\n}\n" }, { "answer_id": 3955349, "author": "tehie", "author_id": 478781, "author_profile": "https://Stackoverflow.com/users/478781", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Net;\nusing System.Net.Mail;\n\nnamespace SendMailViaGmail\n{\n class Program\n {\n static void Main(string[] args)\n {\n\n //Specify senders gmail address\n string SendersAddress = \"[email protected]\";\n //Specify The Address You want to sent Email To(can be any valid email address)\n string ReceiversAddress = \"[email protected]\";\n //Specify The password of gmial account u are using to sent mail(pw of [email protected])\n const string SendersPassword = \"Password\";\n //Write the subject of ur mail\n const string subject = \"Testing\";\n //Write the contents of your mail\n const string body = \"Hi This Is my Mail From Gmail\";\n\n try\n {\n //we will use Smtp client which allows us to send email using SMTP Protocol\n //i have specified the properties of SmtpClient smtp within{}\n //gmails smtp server name is smtp.gmail.com and port number is 587\n SmtpClient smtp = new SmtpClient\n {\n Host = \"smtp.gmail.com\",\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n Credentials = new NetworkCredential(SendersAddress, SendersPassword),\n Timeout = 3000\n };\n\n //MailMessage represents a mail message\n //it is 4 parameters(From,TO,subject,body)\n\n MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);\n /*WE use smtp sever we specified above to send the message(MailMessage message)*/\n\n smtp.Send(message);\n Console.WriteLine(\"Message Sent Successfully\");\n Console.ReadKey();\n }\n\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n Console.ReadKey();\n }\n }\n }\n }\n" }, { "answer_id": 10784857, "author": "Ranadheer Reddy", "author_id": 1215594, "author_profile": "https://Stackoverflow.com/users/1215594", "pm_score": 6, "selected": false, "text": "using System.Net;\nusing System.Net.Mail;\n\npublic void email_send()\n{\n MailMessage mail = new MailMessage();\n SmtpClient SmtpServer = new SmtpClient(\"smtp.gmail.com\");\n mail.From = new MailAddress(\"your [email protected]\");\n mail.To.Add(\"[email protected]\");\n mail.Subject = \"Test Mail - 1\";\n mail.Body = \"mail with attachment\";\n\n System.Net.Mail.Attachment attachment;\n attachment = new System.Net.Mail.Attachment(\"c:/textfile.txt\");\n mail.Attachments.Add(attachment);\n\n SmtpServer.Port = 587;\n SmtpServer.Credentials = new System.Net.NetworkCredential(\"your [email protected]\", \"your password\");\n SmtpServer.EnableSsl = true;\n\n SmtpServer.Send(mail);\n\n}\n" }, { "answer_id": 12073195, "author": "Yasser Shaikh", "author_id": 1182982, "author_profile": "https://Stackoverflow.com/users/1182982", "pm_score": 4, "selected": false, "text": "public void SendEmail(string address, string subject, string message)\n{\n string email = \"[email protected]\";\n string password = \"put-your-GMAIL-password-here\";\n\n var loginInfo = new NetworkCredential(email, password);\n var msg = new MailMessage();\n var smtpClient = new SmtpClient(\"smtp.gmail.com\", 587);\n\n msg.From = new MailAddress(email);\n msg.To.Add(new MailAddress(address));\n msg.Subject = subject;\n msg.Body = message;\n msg.IsBodyHtml = true;\n\n smtpClient.EnableSsl = true;\n smtpClient.UseDefaultCredentials = false;\n smtpClient.Credentials = loginInfo;\n smtpClient.Send(msg);\n}\n" }, { "answer_id": 17516257, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 3, "selected": false, "text": "From msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));\n" }, { "answer_id": 17806790, "author": "RAJESH KUMAR", "author_id": 2598139, "author_profile": "https://Stackoverflow.com/users/2598139", "pm_score": 3, "selected": false, "text": " public void SendEmail(string address, string subject, string message)\n {\n Thread threadSendMails;\n threadSendMails = new Thread(delegate()\n {\n\n //Place your Code here \n\n });\n threadSendMails.IsBackground = true;\n threadSendMails.Start();\n}\n using System.Threading;\n" }, { "answer_id": 19240345, "author": "iTURTEV", "author_id": 2853517, "author_profile": "https://Stackoverflow.com/users/2853517", "pm_score": 2, "selected": false, "text": "public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)\n{\n try\n {\n System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings[\"mailCfg\"], To, Subject, Msg);\n newMsg.BodyEncoding = System.Text.Encoding.UTF8;\n newMsg.HeadersEncoding = System.Text.Encoding.UTF8;\n newMsg.SubjectEncoding = System.Text.Encoding.UTF8;\n\n System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();\n if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)\n {\n System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);\n System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;\n disposition.FileName = AttachmentFileName;\n disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;\n\n newMsg.Attachments.Add(attachment);\n }\n if (test)\n {\n smtpClient.PickupDirectoryLocation = \"C:\\\\TestEmail\";\n smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;\n }\n else\n {\n //smtpClient.EnableSsl = true;\n }\n\n newMsg.IsBodyHtml = bodyHtml;\n smtpClient.Send(newMsg);\n return SENT_OK;\n }\n catch (Exception ex)\n {\n\n return \"Error: \" + ex.Message\n + \"<br/><br/>Inner Exception: \"\n + ex.InnerException;\n }\n\n}\n <appSettings>\n <add key=\"mailCfg\" value=\"[email protected]\"/>\n</appSettings>\n<system.net>\n <mailSettings>\n <smtp deliveryMethod=\"Network\" from=\"[email protected]\">\n <network defaultCredentials=\"false\" host=\"mail.exapmple.com\" userName=\"[email protected]\" password=\"your_password\" port=\"25\"/>\n </smtp>\n </mailSettings>\n</system.net>\n" }, { "answer_id": 19272274, "author": "GOPI", "author_id": 2522714, "author_profile": "https://Stackoverflow.com/users/2522714", "pm_score": 4, "selected": false, "text": "using System.Net.Mail;\n MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); \nSmtpClient client = new SmtpClient(\"smtp.gmail.com\");\n\nclient.Port = 587;\nclient.Credentials = new System.Net.NetworkCredential(\"[email protected]\",\"password\");\nclient.EnableSsl = true;\n\nclient.Send(sendmsg);\n" }, { "answer_id": 19378314, "author": "Premdeep Mohanty", "author_id": 2749766, "author_profile": "https://Stackoverflow.com/users/2749766", "pm_score": 4, "selected": false, "text": "// Include this. \nusing System.Net.Mail;\n\nstring fromAddress = \"[email protected]\";\nstring mailPassword = \"*****\"; // Mail id password from where mail will be sent.\nstring messageBody = \"Write the body of the message here.\";\n\n\n// Create smtp connection.\nSmtpClient client = new SmtpClient();\nclient.Port = 587;//outgoing port for the mail.\nclient.Host = \"smtp.gmail.com\";\nclient.EnableSsl = true;\nclient.Timeout = 10000;\nclient.DeliveryMethod = SmtpDeliveryMethod.Network;\nclient.UseDefaultCredentials = false;\nclient.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);\n\n\n// Fill the mail form.\nvar send_mail = new MailMessage();\n\nsend_mail.IsBodyHtml = true;\n//address from where mail will be sent.\nsend_mail.From = new MailAddress(\"[email protected]\");\n//address to which mail will be sent. \nsend_mail.To.Add(new MailAddress(\"[email protected]\");\n//subject of the mail.\nsend_mail.Subject = \"put any subject here\";\n\nsend_mail.Body = messageBody;\nclient.Send(send_mail);\n" }, { "answer_id": 25216277, "author": "mjb", "author_id": 520848, "author_profile": "https://Stackoverflow.com/users/520848", "pm_score": 5, "selected": false, "text": "using (MailMessage mail = new MailMessage())\n{\n mail.From = new MailAddress(\"[email protected]\");\n mail.To.Add(\"[email protected]\");\n mail.Subject = \"Hello World\";\n mail.Body = \"<h1>Hello</h1>\";\n mail.IsBodyHtml = true;\n mail.Attachments.Add(new Attachment(\"C:\\\\file.zip\"));\n\n using (SmtpClient smtp = new SmtpClient(\"smtp.gmail.com\", 587))\n {\n smtp.Credentials = new NetworkCredential(\"[email protected]\", \"password\");\n smtp.EnableSsl = true;\n smtp.Send(mail);\n }\n}\n" }, { "answer_id": 31310222, "author": "alireza amini", "author_id": 3970128, "author_profile": "https://Stackoverflow.com/users/3970128", "pm_score": 3, "selected": false, "text": "MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); \nSmtpClient client = new SmtpClient(\"smtp.gmail.com\");\n\nclient.Port = Convert.ToInt32(\"587\");\nclient.EnableSsl = true;\nclient.Credentials = new System.Net.NetworkCredential(\"[email protected]\",\"MyPassWord\");\nclient.Send(sendmsg);\n using System.Net;\nusing System.Net.Mail;\n" }, { "answer_id": 32457468, "author": "BCS Software", "author_id": 4222871, "author_profile": "https://Stackoverflow.com/users/4222871", "pm_score": 7, "selected": false, "text": "public static void SendMail2Step(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body, string[] FileNames) { \n var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {\n DeliveryMethod = SmtpDeliveryMethod.Network,\n UseDefaultCredentials = false,\n EnableSsl = true\n }; \n smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!\n var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, \"SendMail2Step\"), new System.Net.Mail.MailAddress(To, To));\n smtpClient.Send(message);\n }\n SendMail2Step(\"smtp.gmail.com\", 587, \"[email protected]\",\n \"yjkjcipfdfkytgqv\",//This will be generated by google, copy it here.\n \"[email protected]\", \"test message subject\", \"Test message body ...\", null);\n" }, { "answer_id": 33054757, "author": "Moin Shirazi", "author_id": 4033273, "author_profile": "https://Stackoverflow.com/users/4033273", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Net;\nusing System.Net.Mail;\n\nnamespace SendMailViaGmail\n{\n class Program\n {\n static void Main(string[] args)\n {\n\n //Specify senders gmail address\n string SendersAddress = \"[email protected]\";\n //Specify The Address You want to sent Email To(can be any valid email address)\n string ReceiversAddress = \"[email protected]\";\n //Specify The password of gmial account u are using to sent mail(pw of [email protected])\n const string SendersPassword = \"Password\";\n //Write the subject of ur mail\n const string subject = \"Testing\";\n //Write the contents of your mail\n const string body = \"Hi This Is my Mail From Gmail\";\n\n try\n {\n //we will use Smtp client which allows us to send email using SMTP Protocol\n //i have specified the properties of SmtpClient smtp within{}\n //gmails smtp server name is smtp.gmail.com and port number is 587\n SmtpClient smtp = new SmtpClient\n {\n Host = \"smtp.gmail.com\",\n Port = 587,\n EnableSsl = true,\n DeliveryMethod = SmtpDeliveryMethod.Network,\n Credentials = new NetworkCredential(SendersAddress, SendersPassword),\n Timeout = 3000\n };\n\n //MailMessage represents a mail message\n //it is 4 parameters(From,TO,subject,body)\n\n MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);\n /*WE use smtp sever we specified above to send the message(MailMessage message)*/\n\n smtp.Send(message);\n Console.WriteLine(\"Message Sent Successfully\");\n Console.ReadKey();\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n Console.ReadKey();\n }\n}\n}\n}\n" }, { "answer_id": 35669909, "author": "reza.cse08", "author_id": 2597706, "author_profile": "https://Stackoverflow.com/users/2597706", "pm_score": 2, "selected": false, "text": "public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)\n{\n MailMessage mailMessage = new MailMessage();\n MailAddress mailAddress = new MailAddress(\"[email protected]\", \"Sender Name\"); // [email protected] = input Sender Email Address \n mailMessage.From = mailAddress;\n mailAddress = new MailAddress(receiverEmail, ReceiverName);\n mailMessage.To.Add(mailAddress);\n mailMessage.Subject = subject;\n mailMessage.Body = body;\n mailMessage.IsBodyHtml = true;\n\n SmtpClient mailSender = new SmtpClient(\"smtp.gmail.com\", 587)\n {\n EnableSsl = true,\n UseDefaultCredentials = false,\n DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,\n Credentials = new NetworkCredential(\"[email protected]\", \"pass\") // [email protected] = input sender email address \n //pass = sender email password\n };\n\n try\n {\n mailSender.Send(mailMessage);\n return true;\n }\n catch (SmtpFailedRecipientException ex)\n { \n // Write the exception to a Log file.\n }\n catch (SmtpException ex)\n { \n // Write the exception to a Log file.\n }\n finally\n {\n mailSender = null;\n mailMessage.Dispose();\n }\n return false;\n}\n" }, { "answer_id": 41952779, "author": "Trimantra Software Solution", "author_id": 777171, "author_profile": "https://Stackoverflow.com/users/777171", "pm_score": 3, "selected": false, "text": " private void button1_Click(object sender, EventArgs e)\n {\n try\n {\n MailMessage mail = new MailMessage();\n SmtpClient SmtpServer = new SmtpClient(\"smtp.gmail.com\");\n\n mail.From = new MailAddress(\"[email protected]\");\n mail.To.Add(\"to_address\");\n mail.Subject = \"Test Mail\";\n mail.Body = \"This is for testing SMTP mail from GMAIL\";\n\n SmtpServer.Port = 587;\n SmtpServer.Credentials = new System.Net.NetworkCredential(\"username\", \"password\");\n SmtpServer.EnableSsl = true;\n\n SmtpServer.Send(mail);\n MessageBox.Show(\"mail Send\");\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.ToString());\n }\n }\n" }, { "answer_id": 56423660, "author": "Naveen", "author_id": 5718260, "author_profile": "https://Stackoverflow.com/users/5718260", "pm_score": 2, "selected": false, "text": "Mailkit MimeMessage message = new MimeMessage();\n message.From.Add(new MailboxAddress(\"FromName\", \"[email protected]\"));\n message.To.Add(new MailboxAddress(\"ToName\", \"[email protected]\"));\n message.Subject = \"MyEmailSubject\";\n\n message.Body = new TextPart(\"plain\")\n {\n Text = @\"MyEmailBodyOnlyTextPart\"\n };\n\n using (var client = new SmtpClient())\n {\n client.Connect(\"SERVER\", 25); // 25 is port you can change accordingly\n\n // Note: since we don't have an OAuth2 token, disable\n // the XOAUTH2 authentication mechanism.\n client.AuthenticationMechanisms.Remove(\"XOAUTH2\");\n\n // Note: only needed if the SMTP server requires authentication\n client.Authenticate(\"YOUR_USER_NAME\", \"YOUR_PASSWORD\");\n\n client.Send(message);\n client.Disconnect(true);\n }\n" }, { "answer_id": 74054933, "author": "Bhadresh Patel", "author_id": 3134543, "author_profile": "https://Stackoverflow.com/users/3134543", "pm_score": 2, "selected": false, "text": "public static void SendMailFromApp(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body) { \n var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {\n DeliveryMethod = SmtpDeliveryMethod.Network,\n UseDefaultCredentials = false,\n EnableSsl = true\n }; \n smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!\n var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, \"SendMail2Step\"), new System.Net.Mail.MailAddress(To, To));\n smtpClient.Send(message);\n }\n SendMailFromApp(\"smtp.gmail.com\", 25, \"[email protected]\",\n \"tyugyyj1556jhghg\",//This will be generated by google, copy it here.\n \"[email protected]\", \"New Mail Subject\", \"Body of mail from My App\");\n" }, { "answer_id": 74404794, "author": "DaImTo", "author_id": 1841839, "author_profile": "https://Stackoverflow.com/users/1841839", "pm_score": 1, "selected": false, "text": "class Program\n{\n private const string To = \"[email protected]\";\n private const string From = \"[email protected]\";\n \n private const string GoogleAppPassword = \"XXXXXXXX\";\n \n private const string Subject = \"Test email\";\n private const string Body = \"<h1>Hello</h1>\";\n \n \n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello World!\");\n \n var smtpClient = new SmtpClient(\"smtp.gmail.com\")\n {\n Port = 587,\n Credentials = new NetworkCredential(From , GoogleAppPassword),\n EnableSsl = true,\n };\n var mailMessage = new MailMessage\n {\n From = new MailAddress(From),\n Subject = Subject,\n Body = Body,\n IsBodyHtml = true,\n };\n mailMessage.To.Add(To);\n\n smtpClient.Send(mailMessage);\n }\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
32,280
<p>I am in the middle of reading the excellent <a href="https://rads.stackoverflow.com/amzn/click/com/0132350882" rel="noreferrer" rel="nofollow noreferrer">Clean Code</a></p> <p>One discussion is regarding passing nulls into a method.</p> <pre><code>public class MetricsCalculator { public double xProjection(Point p1, Point p2) { return (p2.x - p1.x) * 1.5; } } ... calculator.xProjection(null, new Point(12,13)); </code></pre> <p>It represents different ways of handling this:</p> <pre><code>public double xProjection(Point p1, Point p2) { if (p1 == null || p2 == null) { throw new IllegalArgumentException("Invalid argument for xProjection"); } return (p2.x - p1.x) * 1.5; } public double xProjection(Point p1, Point p2) { assert p1 != null : "p1 should not be null"; assert p2 != null : "p2 should not be null"; return (p2.x - p1.x) * 1.5; } </code></pre> <p>I prefer the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html" rel="noreferrer">assertions</a> approach, but I don't like the fact that assertions are turned off by default.</p> <p>The book finally states:</p> <blockquote> <p>In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.</p> </blockquote> <p>It doesn't really go into how you would enforce this restriction?</p> <p>Do any of you have strong opinions either way.</p>
[ { "answer_id": 32304, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 2, "selected": false, "text": "if (p1 == null || p2 == null) {\n throw new IllegalArgumentException(\"Invalid argument for xProjection\");\n}\n" }, { "answer_id": 32305, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "null" }, { "answer_id": 32313, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "null Exception" }, { "answer_id": 32384, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 1, "selected": false, "text": " public static int Divide(int x, int y)\n requires y != 0 otherwise ArgumentException; \n {\n }\n public static int Subtract(int x, int y)\n requires x > y;\n ensures result > y;\n {\n return x - y;\n } \n" }, { "answer_id": 32666, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 2, "selected": false, "text": "/**\n * Checks to see if an object is null, and if so \n * generates an IllegalArgumentException with a fitting message.\n * \n * @param o The object to check against null.\n * @param name The name of the object, used to format the exception message\n *\n * @throws IllegalArgumentException if o is null.\n */\npublic static void checkNull(Object o, String name) \n throws IllegalArgumentException {\n if (null == o)\n throw new IllegalArgumentException(name + \" must not be null\");\n}\n\npublic static void checkNull(Object o) throws IllegalArgumentException {\n checkNull(o, \"object\");\n} \n\n// untested:\npublic static void checkNull(Object... os) throws IllegalArgumentException {\n for(Object o in os) checkNull(o); \n}\n public void someFun(String val1, String val2) throws IllegalArgumentException {\n ExceptionUtilities.checkNull(val1, \"val1\");\n ExceptionUtilities.checkNull(val2, \"val2\");\n\n /** alternatively:\n ExceptionUtilities.checkNull(val1, val2);\n **/\n\n /** ... **/\n} \n" }, { "answer_id": 32716, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 2, "selected": false, "text": "public class MetricsCalculator {\n public double xProjection(#Point p1, #Point p2) {\n return (p2.x - p1.x) * 1.5;\n }\n}\n #Point null Point" }, { "answer_id": 32791, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 0, "selected": false, "text": "ArgumentException IllegalArgumentException" }, { "answer_id": 32907, "author": "Andrei", "author_id": 2718, "author_profile": "https://Stackoverflow.com/users/2718", "pm_score": 2, "selected": false, "text": "@Nullable @NotNull" }, { "answer_id": 248687, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 1, "selected": false, "text": "Option // allocate null\nvar name : Option[String]\nname = None\n\n// allocate a value\nname = Any[\"Hello\"]\n\n// print the value if we can\nname match {\n Any[x] => print x\n _ => print \"Nothing at all\"\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3295/" ]
32,282
<p>How can I test the same regex against different regular expression engines?</p>
[ { "answer_id": 32354, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 3, "selected": false, "text": "re-builder" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
32,332
<p>This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ <code>std::fstream</code> classes don't take a <code>std::string</code> in their constructor or open methods. Everyone loves code examples so:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; int main() { std::string filename = "testfile"; std::ifstream fin; fin.open(filename.c_str()); // Works just fine. fin.close(); //fin.open(filename); // Error: no such method. //fin.close(); } </code></pre> <p>This gets me all the time when working with files. Surely the C++ library would use <code>std::string</code> wherever possible?</p>
[ { "answer_id": 32368, "author": "Christopher", "author_id": 3186, "author_profile": "https://Stackoverflow.com/users/3186", "pm_score": 4, "selected": false, "text": "std::string std::swap std::sort" }, { "answer_id": 37542, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 6, "selected": true, "text": "std::fstream std::string std::fstream std::string std:string std::string std::string std::string std::string fstream std::string void f(std::string str1, std::string str2);\nvoid f(char* cstr1, char* cstr2);\n\nvoid g()\n{\n char* cstr = \"abc\";\n std::string str = \"def\";\n f(cstr, str); // ERROR: ambiguous\n}\n std::string f() f() c_str()" }, { "answer_id": 35925171, "author": "Jonathan Birge", "author_id": 787906, "author_profile": "https://Stackoverflow.com/users/787906", "pm_score": 0, "selected": false, "text": "-std=c++11 CFLAGS" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
32,333
<p>Here's a perfect example of the problem: <a href="http://blog.teksol.info/2009/03/27/argumenterror-on-number-sum-when-using-classifier-bayes.html" rel="nofollow noreferrer">Classifier gem breaks Rails</a>.</p> <p>** Original question: **</p> <p>One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby:</p> <pre><code>public module Foo public module Bar # factory method for new Bar implementations def self.new(...) SimpleBarImplementation.new(...) end def baz raise NotImplementedError.new('Implementing Classes MUST redefine #baz') end end private class SimpleBarImplementation include Bar def baz ... end end end </code></pre> <p>It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call <code>freeze</code> on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not <strong>very</strong> careful about load order.</p> <p>Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions?</p> <p>(And no, core classes are not frozen by default in Ruby. See below:)</p> <pre><code>require 'md5' # =&gt; true MD5.frozen? # =&gt; false </code></pre>
[ { "answer_id": 33611, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 3, "selected": false, "text": "require 'awesome'\n# Do something awesome.\n require 'evil_cracker_lib_from_russian_pr0n_site'\n# Overrides crypto functions and sends all data to mafia\nrequire 'awesome'\n# Now everything is insecure because awesome lib uses \n# cracker lib instead of builtin\n private final" }, { "answer_id": 33900, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "require 'evil_cracker_lib_from_russian_pr0n_site'\nrequire 'awesome'\n awesome foobar fazbot foobar has_gumption" }, { "answer_id": 331458, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "class Module\n def anonymous_module(&block)\n self.send :include, Module.new(&block)\n end\nend\n\nclass Acronym\n anonymous_module do\n fu = lambda { 'fu' }\n bar = lambda { 'bar' }\n define_method :fubar do\n fu.call + bar.call\n end\n end\nend\n fubar Acronym fu bar" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
32,338
<p>I just saw <a href="http://www.codeplex.com/CloneDetectiveVS" rel="nofollow noreferrer">Clone Detective</a> linked on YCombinator news, and the idea heavily appeals to me. It seems like it would be useful for many languages, not just C#, but I haven't seen anything similar elsewhere.</p> <p>Edit: For those who don't want to follow the link, Clone Detective scans the codebase for duplicate code that may warrant refactoring to minimize duplication.</p>
[ { "answer_id": 33611, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 3, "selected": false, "text": "require 'awesome'\n# Do something awesome.\n require 'evil_cracker_lib_from_russian_pr0n_site'\n# Overrides crypto functions and sends all data to mafia\nrequire 'awesome'\n# Now everything is insecure because awesome lib uses \n# cracker lib instead of builtin\n private final" }, { "answer_id": 33900, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "require 'evil_cracker_lib_from_russian_pr0n_site'\nrequire 'awesome'\n awesome foobar fazbot foobar has_gumption" }, { "answer_id": 331458, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "class Module\n def anonymous_module(&block)\n self.send :include, Module.new(&block)\n end\nend\n\nclass Acronym\n anonymous_module do\n fu = lambda { 'fu' }\n bar = lambda { 'bar' }\n define_method :fubar do\n fu.call + bar.call\n end\n end\nend\n fubar Acronym fu bar" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3326/" ]
32,341
<p>I may just be missing this functionality, but does anyone know if there is a widget available:</p> <p>I need to list the subject for all the entries that are associated with a given tag.</p> <p>For example: I have 5 articles tagged with "Tutorial", I'd like to see a list as follows:</p> <ul> <li>Tutorial 1: Installing the app</li> <li>Tutorial 2: Customizing</li> <li>Tutorial 3: Advanced edits</li> <li>Tutorial 4: User managment</li> </ul> <p>Does functionality like this exists in wordpress allready?</p>
[ { "answer_id": 33611, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 3, "selected": false, "text": "require 'awesome'\n# Do something awesome.\n require 'evil_cracker_lib_from_russian_pr0n_site'\n# Overrides crypto functions and sends all data to mafia\nrequire 'awesome'\n# Now everything is insecure because awesome lib uses \n# cracker lib instead of builtin\n private final" }, { "answer_id": 33900, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "require 'evil_cracker_lib_from_russian_pr0n_site'\nrequire 'awesome'\n awesome foobar fazbot foobar has_gumption" }, { "answer_id": 331458, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "class Module\n def anonymous_module(&block)\n self.send :include, Module.new(&block)\n end\nend\n\nclass Acronym\n anonymous_module do\n fu = lambda { 'fu' }\n bar = lambda { 'bar' }\n define_method :fubar do\n fu.call + bar.call\n end\n end\nend\n fubar Acronym fu bar" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490/" ]
32,343
<p>Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3s. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had and spin up an encoding thread on each core. So, when I run the program on a quad core CPU, the program figures out it's a quad core CPU, figures out there are four cores to work with, then spawns four threads for the encoding, each of which is running on its own separate CPU. How would I do this?</p> <p>And would this be any different if the cores were spread out across multiple physical CPUs? As in, if I had a machine with two quad core CPUs on it, are there any special considerations or are the eight cores across the two dies considered equal in Windows?</p>
[ { "answer_id": 32352, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 2, "selected": false, "text": "Environment.ProcessorCount" }, { "answer_id": 568002, "author": "Joe Erickson", "author_id": 56710, "author_profile": "https://Stackoverflow.com/users/56710", "pm_score": 4, "selected": false, "text": "int processors = 1;\nstring processorsStr = System.Environment.GetEnvironmentVariable(\"NUMBER_OF_PROCESSORS\");\nif (processorsStr != null)\n processors = int.Parse(processorsStr);\n" }, { "answer_id": 18499947, "author": "Mantosh Kumar", "author_id": 2724703, "author_profile": "https://Stackoverflow.com/users/2724703", "pm_score": 3, "selected": false, "text": "#define MAX_CORE 256\nprocessor_mask[MAX_CORE] = {0};\ncore_number = 0;\n\nCall GetLogicalProcessorInformation();\n// From Here we calculate the core_number and also we populate the process_mask[] array\n// which would be used later on to set to run different threads on different CORES.\n\n\nfor(j = 0; j < THREAD_POOL_SIZE; j++)\nCall SetThreadAffinityMask(hThread[j],processor_mask[j]);\n//hThread is the array of handles of thread.\n//Now if your number of threads are higher than the actual number of cores,\n// you can use reset the counters(j) once you reach to the \"core_number\".\n Thread1-> Core1\nThread2-> Core2\nThread3-> Core3\nThread4-> Core4\nThread5-> Core5\nThread6-> Core6\nThread7-> Core7\nThread8-> Core8\n\nThread9-> Core1\nThread10-> Core2\n...............\n" }, { "answer_id": 29392050, "author": "AlexDev", "author_id": 733760, "author_profile": "https://Stackoverflow.com/users/733760", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace Esquenta\n{\n class Program\n {\n private static int numThreads = 1;\n static bool affinity = false;\n static void Main(string[] args)\n {\n if (args.Contains(\"-a\"))\n {\n affinity = true;\n }\n if (args.Length < 1 || !int.TryParse(args[0], out numThreads))\n {\n numThreads = 1;\n }\n Console.WriteLine(\"numThreads:\" + numThreads);\n for (int j = 0; j < numThreads; j++)\n {\n var param = new ParameterizedThreadStart(EsquentaP);\n var thread = new Thread(param);\n thread.Start(j);\n }\n\n }\n\n static void EsquentaP(object numero_obj)\n {\n int i = 0;\n DateTime ultimo = DateTime.Now;\n if(affinity)\n {\n Thread.BeginThreadAffinity();\n CurrentThread.ProcessorAffinity = new IntPtr(1);\n }\n try\n {\n while (true)\n {\n i++;\n if (i == int.MaxValue)\n {\n i = 0;\n var lps = int.MaxValue / (DateTime.Now - ultimo).TotalSeconds / 1000000;\n Console.WriteLine(\"Thread \" + numero_obj + \" \" + lps.ToString(\"0.000\") + \" M loops/s\");\n ultimo = DateTime.Now;\n }\n }\n }\n finally\n {\n Thread.EndThreadAffinity();\n }\n }\n\n [DllImport(\"kernel32.dll\")]\n public static extern int GetCurrentThreadId();\n\n [DllImport(\"kernel32.dll\")]\n public static extern int GetCurrentProcessorNumber();\n private static ProcessThread CurrentThread\n {\n get\n {\n int id = GetCurrentThreadId();\n return Process.GetCurrentProcess().Threads.Cast<ProcessThread>().Single(x => x.Id == id);\n }\n }\n }\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
32,366
<p>I just started thinking about creating/customizing a web crawler today, and know very little about web crawler/robot etiquette. A majority of the writings on etiquette I've found seem old and awkward, so I'd like to get some current (and practical) insights from the web developer community.</p> <p>I want to use a crawler to walk over "the web" for a super simple purpose - "does the markup of site XYZ meet condition ABC?".</p> <p>This raises a lot of questions for me, but I think the two main questions I need to get out of the way first are:</p> <ul> <li>It feels a little "iffy" from the get go -- is this sort of thing acceptable?</li> <li>What specific considerations should the crawler take to not upset people?</li> </ul>
[ { "answer_id": 32452, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "no-cache <link> <script src=\"...\"></script>" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326/" ]
32,369
<p>One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy.</p> <p>Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site.</p> <p><strong>Question</strong>: Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 32386, "author": "Markus Olsson", "author_id": 2114, "author_profile": "https://Stackoverflow.com/users/2114", "pm_score": 9, "selected": true, "text": "<form id=\"loginForm\" action=\"login.cgi\" method=\"post\" autocomplete=\"off\">\n $('#loginForm').attr('autocomplete', 'off');\n" }, { "answer_id": 32388, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": -1, "selected": false, "text": "<input type=\"password\">" }, { "answer_id": 32408, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 1, "selected": false, "text": "autocomplete" }, { "answer_id": 2359480, "author": "Howard Young", "author_id": 283958, "author_profile": "https://Stackoverflow.com/users/283958", "pm_score": 3, "selected": false, "text": "$(function() { \n $('#PasswordEdit').attr(\"autocomplete\", \"off\");\n setTimeout('$(\"#PasswordEdit\").val(\"\");', 50); \n});\n setTimeout()" }, { "answer_id": 2555771, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 5, "selected": false, "text": "autocomplete=\"off\" <input type=\"text\" id=\"username\" name=\"username\"/>\n<input type=\"password\" id=\"password\" name=\"password\"/>\n\n<form id=\"theForm\" action=\"/your/login\" method=\"post\">\n <input type=\"hidden\" id=\"hiddenUsername\" name=\"username\"/>\n <input type=\"hidden\" id=\"hiddenPassword\" name=\"password\"/>\n <input type=\"submit\" value=\"Login\"/>\n</form>\n\n<script type=\"text/javascript\" language=\"JavaScript\">\n $(\"#theForm\").submit(function() {\n $(\"#hiddenUsername\").val($(\"#username\").val());\n $(\"#hiddenPassword\").val($(\"#password\").val());\n });\n $(\"#username,#password\").keypress(function(e) {\n if (e.which == 13) {\n $(\"#theForm\").submit();\n }\n });\n</script>\n" }, { "answer_id": 10853609, "author": "Tom", "author_id": 1431092, "author_profile": "https://Stackoverflow.com/users/1431092", "pm_score": -1, "selected": false, "text": "<html>\n <head>\n <script>\n function pw_edited() {\n document.this_form.password_edited.value = 1;\n }\n function pw_blank() {\n document.this_form.password.value = \"\";\n }\n function submitf() {\n if(document.this_form.password_edited.value < 1) {\n alert(\"Please Enter Your Password!\");\n }\n else {\n document.this_form.submit();\n }\n }\n </script>\n </head>\n <body>\n <form name=\"this_form\" method=\"post\" action=\"../../cgi-bin/yourscript.cgi?login\">\n <div style=\"padding-left:25px;\">\n <p>\n <label>User:</label>\n <input name=\"user_name\" type=\"text\" class=\"input\" value=\"\" size=\"30\" maxlength=\"60\">\n </p>\n <p>\n <label>Password:</label>\n <input name=\"password\" type=\"password\" class=\"input\" size=\"20\" value=\"\" maxlength=\"50\" onfocus=\"pw_blank();\" onchange=\"pw_edited();\">\n </p>\n <p>\n <span id=\"error_msg\"></span>\n </p>\n <p>\n <input type=\"hidden\" name=\"password_edited\" value=\"0\">\n <input name=\"submitform\" type=\"button\" class=\"button\" value=\"Login\" onclick=\"return submitf();\">\n </p>\n </div>\n </form>\n </body>\n</html>\n" }, { "answer_id": 11141892, "author": "Marcelo Finki", "author_id": 996605, "author_profile": "https://Stackoverflow.com/users/996605", "pm_score": -1, "selected": false, "text": "type=password <form>\n <input type=password id=pwd67584 ...>\n <input type=text id=username ...>\n <input type=submit>\n</form>\n" }, { "answer_id": 19223143, "author": "venimus", "author_id": 623288, "author_profile": "https://Stackoverflow.com/users/623288", "pm_score": 4, "selected": false, "text": "autocomplete=\"off\" <input type=\"text\" id=\"username\" name=\"username\"/>\n<input type=\"password\" id=\"prevent_autofill\" autocomplete=\"off\" style=\"display:none\" tabindex=\"-1\" />\n<input type=\"password\" id=\"password\" autocomplete=\"off\" name=\"password\"/>\n #prevent_autofill type=\"password\"" }, { "answer_id": 20968859, "author": "Biau", "author_id": 3168622, "author_profile": "https://Stackoverflow.com/users/3168622", "pm_score": -1, "selected": false, "text": "<input type=\"text\" name=\"preventAutoPass\" id=\"preventAutoPass\" style=\"display:none\" />\n <input type=\"text\" name=\"txtUserName\" id=\"txtUserName\" />\n<input type=\"text\" name=\"preventAutoPass\" id=\"preventAutoPass\" style=\"display:none\" />\n<input type=\"password\" name=\"txtPass\" id=\"txtPass\" autocomplete=\"off\" />" }, { "answer_id": 22215004, "author": "JW Lim", "author_id": 3155705, "author_profile": "https://Stackoverflow.com/users/3155705", "pm_score": -1, "selected": false, "text": "autocomplete=\"off\" input type=\"password\" autocomplete=\"off\"" }, { "answer_id": 23927796, "author": "Asik", "author_id": 1387002, "author_profile": "https://Stackoverflow.com/users/1387002", "pm_score": 4, "selected": false, "text": "<form id=\"HiddenLoginForm\" action=\"\" method=\"post\">\n<input type=\"hidden\" name=\"username\" id=\"hidden_username\" />\n<input type=\"hidden\" name=\"password\" id=\"hidden_password\" />\n</form>\n\nUsername: <input type=\"text\" name=\"username\" id=\"username\" onKeyPress=\"return checkAndSubmit(event);\" /> \nPassword: <input type=\"text\" name=\"password\" id=\"password\" onKeyPress=\"return checkAndSubmit(event);\" /> \n<input type=\"button\" value=\"submit\" onClick=\"return validateAndLogin();\" onKeyPress=\"return checkAndSubmit(event);\" /> \n //For validation- you can modify as you like\nfunction validateAndLogin(){\n var username = document.getElementById(\"username\");\n var password = document.getElementById(\"password\");\n\n if(username && username.value == ''){\n alert(\"Please enter username!\");\n return false;\n }\n\n if(password && password.value == ''){\n alert(\"Please enter password!\");\n return false;\n }\n\n document.getElementById(\"hidden_username\").value = username.value;\n document.getElementById(\"hidden_password\").value = password.value;\n document.getElementById(\"HiddenLoginForm\").submit();\n}\n\n//For enter event\nfunction checkAndSubmit(e) {\n if (e.keyCode == 13) {\n validateAndLogin();\n }\n}\n" }, { "answer_id": 24955110, "author": "Dai Bok", "author_id": 198762, "author_profile": "https://Stackoverflow.com/users/198762", "pm_score": 2, "selected": false, "text": "<form autocomplete='off' ...>\n <input type=\"text\" name=\"email\" ...>\n <input type=\"text\" name=\"password\" class=\"password\" autocomplete='off' ...>\n <input type=submit>\n</form>\n @font-face {\n font-family: 'myCustomfont';\n src: url('myCustomfont.eot');\n src: url('myCustomfont?#iefix') format('embedded-opentype'),\n url('myCustomfont.woff') format('woff'),\n url('myCustomfont.ttf') format('truetype'),\n url('myCustomfont.svg#myCustomfont') format('svg');\n font-weight: normal;\n font-style: normal;\n\n}\n.password {\n font-family:'myCustomfont';\n}\n" }, { "answer_id": 25111774, "author": "whyAto8", "author_id": 1122463, "author_profile": "https://Stackoverflow.com/users/1122463", "pm_score": 5, "selected": false, "text": "<form method=\"post\" action=\"yoururl\">\n <div class=\"hidden\">\n <input type=\"password\"/>\n </div>\n <input type=\"text\" name=\"username\" placeholder=\"username\"/>\n <input type=\"password\" name=\"password\" placeholder=\"password\"/>\n </form>\n .hidden {display:none;}\n" }, { "answer_id": 31655148, "author": "Sheiky", "author_id": 3732989, "author_profile": "https://Stackoverflow.com/users/3732989", "pm_score": -1, "selected": false, "text": "<input type=\"text\" style=\"display:none\">\n<input type=\"text\" name=\"OriginalLoginTextBox\">\n\n<input type=\"password\" style=\"display:none\">\n<input type=\"text\" name=\"OriginalPasswordTextBox\">\n" }, { "answer_id": 31813922, "author": "knee-cola", "author_id": 268905, "author_profile": "https://Stackoverflow.com/users/268905", "pm_score": 2, "selected": false, "text": "<!doctype html>\n<html>\n<head>\n <title>Login & Save password test</title>\n <meta charset=\"utf-8\">\n <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"></script>\n</head>\n\n <body>\n <!-- the following fields will show on page, but are not part of the form -->\n <input class=\"username\" type=\"text\" placeholder=\"Username\" />\n <input class=\"password\" type=\"password\" placeholder=\"Password\" />\n\n <form id=\"loginForm\" action=\"login.aspx\" method=\"post\">\n <!-- thw following two fields are part of the form, but are not visible -->\n <input name=\"username\" id=\"username\" type=\"hidden\" />\n <input name=\"password\" id=\"password\" type=\"hidden\" />\n <!-- standard submit button -->\n <button type=\"submit\">Login</button>\n </form>\n\n <script>\n // attache a event listener which will get called just before the form data is sent to server\n $('form').submit(function(ev) {\n console.log('xxx');\n // read the value from the visible INPUT and save it to invisible one\n // ... so that it gets sent to the server\n $('#username').val($('.username').val());\n $('#password').val($('.password').val());\n });\n </script>\n\n </body>\n</html>" }, { "answer_id": 32281293, "author": "ovalek", "author_id": 1102219, "author_profile": "https://Stackoverflow.com/users/1102219", "pm_score": 2, "selected": false, "text": "$('form').submit(function(event) {\n $(this).find('input[type=password]').css('visibility', 'hidden').attr('type', 'text');\n});\n" }, { "answer_id": 36073643, "author": "Mike", "author_id": 4240993, "author_profile": "https://Stackoverflow.com/users/4240993", "pm_score": 0, "selected": false, "text": "<input type=\"password\" name=\"password[]\" style=\"display:none\" />\n <input type=\"password\" name=\"password[]\" />\n echo $_POST['password'][1];\n" }, { "answer_id": 37292424, "author": "Murat Yıldız", "author_id": 1604048, "author_profile": "https://Stackoverflow.com/users/1604048", "pm_score": 6, "selected": false, "text": "autocomplete=\"off\"\n readonly onfocus=\"this.removeAttribute('readonly');\"\n username password <input type=\"text\" name=\"UserName\" autocomplete=\"off\" readonly \n onfocus=\"this.removeAttribute('readonly');\" >\n\n<input type=\"password\" name=\"Password\" autocomplete=\"off\" readonly \n onfocus=\"this.removeAttribute('readonly');\" >\n Google Chrome Mozilla Firefox Microsoft Edge" }, { "answer_id": 42929645, "author": "Lasitha Benaragama", "author_id": 853671, "author_profile": "https://Stackoverflow.com/users/853671", "pm_score": 1, "selected": false, "text": "autocomplete=\"off\" <button type=\"button\" class=\"\" ng-click=\"vm.login()\" />\n" }, { "answer_id": 43206336, "author": "mfernandes", "author_id": 1892887, "author_profile": "https://Stackoverflow.com/users/1892887", "pm_score": 2, "selected": false, "text": "<input type=\"password\" data-password-autocomplete=\"off\">\n $(function(){\n $('[data-password-autocomplete=\"off\"]').each(function() {\n $(this).prop('type', 'text');\n $('<input type=\"password\"/>').hide().insertBefore(this);\n $(this).focus(function() {\n $(this).prop('type', 'password');\n });\n }); \n});\n" }, { "answer_id": 43353829, "author": "Cedric Simon", "author_id": 2838910, "author_profile": "https://Stackoverflow.com/users/2838910", "pm_score": 2, "selected": false, "text": "<input style=\"background-color: rgb(239, 179, 196); color: black; text-shadow: none;\" name=\"password\" size=\"10\" maxlength=\"30\" onfocus=\"this.value='';this.style.color='black'; this.style.textShadow='none';\" onkeypress=\"this.style.color='transparent'; this.style.textShadow='1px 1px 6px green';\" autocomplete=\"off\" type=\"text\">\n" }, { "answer_id": 49114022, "author": "CubicleSoft", "author_id": 917198, "author_profile": "https://Stackoverflow.com/users/917198", "pm_score": 0, "selected": false, "text": "autocomplete autocomplete password text (function($) {\n$.fn.StopPasswordManager = function() {\n return this.each(function() {\n var $this = $(this);\n\n $this.addClass('no-print');\n $this.attr('data-background-color', $this.css('background-color'));\n $this.css('background-color', $this.css('color'));\n $this.attr('type', 'text');\n $this.attr('autocomplete', 'off');\n\n $this.focus(function() {\n $this.attr('type', 'password');\n $this.css('background-color', $this.attr('data-background-color'));\n });\n\n $this.blur(function() {\n $this.css('background-color', $this.css('color'));\n $this.attr('type', 'text');\n $this[0].selectionStart = $this[0].selectionEnd;\n });\n\n $this.on('keydown', function(e) {\n if (e.keyCode == 13)\n {\n $this.css('background-color', $this.css('color'));\n $this.attr('type', 'text');\n $this[0].selectionStart = $this[0].selectionEnd;\n }\n });\n });\n}\n}(jQuery));\n" }, { "answer_id": 64872142, "author": "Burak Ekincioğlu", "author_id": 9559819, "author_profile": "https://Stackoverflow.com/users/9559819", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\">\n #login_parola {\n font-family: 'passwordsecretregular' !important;\n -webkit-text-security: disc !important;\n font-size: 22px !important;\n }\n </style>\n\n\n<input type=\"text\" class=\"w205 has-keyboard-alpha\" name=\"login_parola\" id=\"login_parola\" onkeyup=\"checkCapsWarning(event)\" \n onfocus=\"checkCapsWarning(event)\" onblur=\"removeCapsWarning()\" onpaste=\"return false;\" maxlength=\"32\"/>\n" }, { "answer_id": 73055897, "author": "Stu", "author_id": 14274352, "author_profile": "https://Stackoverflow.com/users/14274352", "pm_score": 0, "selected": false, "text": "<input type=\"text\" id=\"mPassword\" required=\"required\" title=\"Valid password required\" autocomplete=\"off\" list=\"autocompleteOff\" readonly onfocus=\"this.removeAttribute('readonly');\" style=\"text-security:disc; -webkit-text-security:disc;\" oncopy=\"return false;\" onpaste=\"return false;\"/>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3262/" ]
32,397
<p>On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine. </p>
[ { "answer_id": 32399, "author": "Tall Jeff", "author_id": 1553, "author_profile": "https://Stackoverflow.com/users/1553", "pm_score": 5, "selected": true, "text": "t = (time of entry post) - (Dec 8, 2005)\nx = upvotes - downvotes\n\ny = {1 if x > 0, 0 if x = 0, -1 if x < 0)\nz = {1 if x < 1, otherwise x}\n\nlog(z) + (y * t)/45000\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942/" ]
32,404
<p>I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.</p> <p>I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.</p> <p><strong>Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?</strong> I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.</p> <p><i>Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: <b>How is Windows aware of my service? Can I manage it with the native Windows utilities?</b> <strong>What is the equivalent of putting a start/stop script in /etc/init.d?</i></strong></p>
[ { "answer_id": 32440, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 9, "selected": true, "text": "import win32serviceutil\nimport win32service\nimport win32event\nimport servicemanager\nimport socket\n\n\nclass AppServerSvc (win32serviceutil.ServiceFramework):\n _svc_name_ = \"TestService\"\n _svc_display_name_ = \"Test Service\"\n\n def __init__(self,args):\n win32serviceutil.ServiceFramework.__init__(self,args)\n self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n def SvcDoRun(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_,''))\n self.main()\n\n def main(self):\n pass\n\nif __name__ == '__main__':\n win32serviceutil.HandleCommandLine(AppServerSvc)\n main() SvcStop" }, { "answer_id": 597750, "author": "popcnt", "author_id": 47850, "author_profile": "https://Stackoverflow.com/users/47850", "pm_score": 5, "selected": false, "text": "Service Name : PythonTest\nDisplay Name : PythonTest \nStartup : Manual (or whatever you like)\nDependencies : (Leave blank or fill to fit your needs)\nExecutable : c:\\python25\\python.exe\nArguments : c:\\path_to_your_python_script\\test.py\nWorking Directory : c:\\path_to_your_python_script\n" }, { "answer_id": 41017425, "author": "pyOwner", "author_id": 5165357, "author_profile": "https://Stackoverflow.com/users/5165357", "pm_score": 5, "selected": false, "text": "sc create PythonApp binPath= \"C:\\Python34\\Python.exe --C:\\tmp\\pythonscript.py\"\n" }, { "answer_id": 42587921, "author": "Seliverstov Maksim", "author_id": 7589877, "author_profile": "https://Stackoverflow.com/users/7589877", "pm_score": 3, "selected": false, "text": "from xmlrpc.server import SimpleXMLRPCServer\n\nfrom pysc import event_stop\n\n\nclass TestServer:\n\n def echo(self, msg):\n return msg\n\n\nif __name__ == '__main__':\n server = SimpleXMLRPCServer(('127.0.0.1', 9001))\n\n @event_stop\n def stop():\n server.server_close()\n\n server.register_instance(TestServer())\n server.serve_forever()\n import os\nimport sys\nfrom xmlrpc.client import ServerProxy\n\nimport pysc\n\n\nif __name__ == '__main__':\n service_name = 'test_xmlrpc_server'\n script_path = os.path.join(\n os.path.dirname(__file__), 'xmlrpc_server.py'\n )\n pysc.create(\n service_name=service_name,\n cmd=[sys.executable, script_path]\n )\n pysc.start(service_name)\n\n client = ServerProxy('http://127.0.0.1:9001')\n print(client.echo('test scm'))\n import pysc\n\nservice_name = 'test_xmlrpc_server'\n\npysc.stop(service_name)\npysc.delete(service_name)\n pip install pysc\n" }, { "answer_id": 44820139, "author": "Seckin Sanli", "author_id": 8230298, "author_profile": "https://Stackoverflow.com/users/8230298", "pm_score": 5, "selected": false, "text": "import win32serviceutil\nimport win32service\nimport win32event\nimport servicemanager\nimport socket\n\n\nclass AppServerSvc (win32serviceutil.ServiceFramework):\n _svc_name_ = \"TestService\"\n _svc_display_name_ = \"Test Service\"\n\n\n def __init__(self,args):\n win32serviceutil.ServiceFramework.__init__(self,args)\n self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n def SvcDoRun(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_,''))\n self.main()\n\n def main(self):\n # Your business logic or call to any class should be here\n # this time it creates a text.txt and writes Test Service in a daily manner \n f = open('C:\\\\test.txt', 'a')\n rc = None\n while rc != win32event.WAIT_OBJECT_0:\n f.write('Test Service \\n')\n f.flush()\n # block for 24*60*60 seconds and wait for a stop event\n # it is used for a one-day loop\n rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)\n f.write('shut down \\n')\n f.close()\n\nif __name__ == '__main__':\n win32serviceutil.HandleCommandLine(AppServerSvc)\n" }, { "answer_id": 46450007, "author": "Adriano P", "author_id": 8221383, "author_profile": "https://Stackoverflow.com/users/8221383", "pm_score": 6, "selected": false, "text": "c:\\>nssm.exe install WinService\n nssm.exe c:\\path\\to\\nssm.exe nssm.exe install ProjectService \"c:\\path\\to\\python.exe\" \"c:\\path\\to\\project\\app\\main.py\"\n nssm.exe install ProjectService \nnssm.exe set ProjectService Application \"c:\\path\\to\\python.exe\"\nnssm.exe set ProjectService AppParameters \"c:\\path\\to\\project\\app\\main.py\"\n nssm.exe install ProjectService \"c:\\path\\to\\python.exe\" \"-m app.main\"\nnssm.exe set ProjectService AppDirectory \"c:\\path\\to\\project\"\n nssm.exe start ProjectService \n nssm.exe stop ProjectService\n confirm nssm.exe remove ProjectService confirm\n" }, { "answer_id": 52780201, "author": "flam3", "author_id": 1407255, "author_profile": "https://Stackoverflow.com/users/1407255", "pm_score": 2, "selected": false, "text": "Error 1053: The service did not respond to the start or control request in a timely fashion. Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect." }, { "answer_id": 53240642, "author": "ndemou", "author_id": 1011025, "author_profile": "https://Stackoverflow.com/users/1011025", "pm_score": 1, "selected": false, "text": "win32serviceutil nssm.exe install NameOfYourService C:\\Python27\\Python.exe c:\\path\\to\\program.py" }, { "answer_id": 56451724, "author": "coder", "author_id": 10534497, "author_profile": "https://Stackoverflow.com/users/10534497", "pm_score": 3, "selected": false, "text": "python {{your python.py file name}}" }, { "answer_id": 59923084, "author": "Alias_Knagg", "author_id": 2156089, "author_profile": "https://Stackoverflow.com/users/2156089", "pm_score": 2, "selected": false, "text": "# uncomment mainthread() or mainloop() call below\n# run without parameters to see HandleCommandLine options\n# install service with \"install\" and remove with \"remove\"\n# run with \"debug\" to see print statements\n# with \"start\" and \"stop\" watch for files to appear\n# check Windows EventViever for log messages\n\nimport socket\nimport sys\nimport threading\nimport time\nfrom random import randint\nfrom os import path\n\nimport servicemanager\nimport win32event\nimport win32service\nimport win32serviceutil\n# see http://timgolden.me.uk/pywin32-docs/contents.html for details\n\n\ndef dummytask_once(msg='once'):\n fn = path.join(path.dirname(__file__),\n '%s_%s.txt' % (msg, randint(1, 10000)))\n with open(fn, 'w') as fh:\n print(fn)\n fh.write('')\n\n\ndef dummytask_loop():\n global do_run\n while do_run:\n dummytask_once(msg='loop')\n time.sleep(3)\n\n\nclass MyThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n global do_run\n do_run = True\n print('thread start\\n')\n dummytask_loop()\n print('thread done\\n')\n\n def exit(self):\n global do_run\n do_run = False\n\n\nclass SMWinservice(win32serviceutil.ServiceFramework):\n _svc_name_ = 'PyWinSvc'\n _svc_display_name_ = 'Python Windows Service'\n _svc_description_ = 'An example of a windows service in Python'\n\n @classmethod\n def parse_command_line(cls):\n win32serviceutil.HandleCommandLine(cls)\n\n def __init__(self, args):\n win32serviceutil.ServiceFramework.__init__(self, args)\n self.stopEvt = win32event.CreateEvent(None, 0, 0, None) # create generic event\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STOPPED,\n (self._svc_name_, ''))\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.stopEvt) # raise event\n\n def SvcDoRun(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_, ''))\n # UNCOMMENT ONE OF THESE\n # self.mainthread()\n # self.mainloop()\n\n # Wait for stopEvt indefinitely after starting thread.\n def mainthread(self):\n print('main start')\n self.server = MyThread()\n self.server.start()\n print('wait for win32event')\n win32event.WaitForSingleObject(self.stopEvt, win32event.INFINITE)\n self.server.exit()\n print('wait for thread')\n self.server.join()\n print('main done')\n\n # Wait for stopEvt event in loop.\n def mainloop(self):\n print('loop start')\n rc = None\n while rc != win32event.WAIT_OBJECT_0:\n dummytask_once()\n rc = win32event.WaitForSingleObject(self.stopEvt, 3000)\n print('loop done')\n\n\nif __name__ == '__main__':\n SMWinservice.parse_command_line()\n" }, { "answer_id": 60775892, "author": "gunarajulu renganathan", "author_id": 13095056, "author_profile": "https://Stackoverflow.com/users/13095056", "pm_score": -1, "selected": false, "text": "setx /M PATH \"%PATH%;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Scripts;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\pywin32_system32;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\win32\n cd C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32 NET START PySvc NET STOP PySvc" }, { "answer_id": 64637599, "author": "Russell McDonell", "author_id": 12791160, "author_profile": "https://Stackoverflow.com/users/12791160", "pm_score": 2, "selected": false, "text": "'''\nA script to create a Windows Service, which, when started, will run an executable with the specified parameters.\nOptionally, you can also specify a startup directory\n\nTo use this script you MUST define (in class Service)\n1. A name for your service (short - preferably no spaces)\n2. A display name for your service (the name visibile in Windows Services)\n3. A description for your service (long details visible when you inspect the service in Windows Services)\n4. The full path of the executable (usually C:/Python38/python.exe or C:WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe\n5. The script which Python or PowerShell will run(or specify None if your executable is standalone - in which case you don't need pyGlue)\n6. The startup directory (or specify None)\n7. Any parameters for your script (or for your executable if you have no script)\n\nNOTE: This does not make a portable script.\nThe associated '_svc_name.exe' in the dist folder will only work if the executable,\n(and any optional startup directory) actually exist in those locations on the target system\n\nUsage: 'pyGlue.exe [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'\nOptions for 'install' and 'update' commands only:\n --username domain\\\\username : The Username the service is to run under\n --password password : The password for the username\n --startup [manual|auto|disabled|delayed] : How the service starts, default = manual\n --interactive : Allow the service to interact with the desktop.\n --perfmonini file: .ini file to use for registering performance monitor data\n --perfmondll file: .dll file to use when querying the service for performance data, default = perfmondata.dll\nOptions for 'start' and 'stop' commands only:\n --wait seconds: Wait for the service to actually start or stop.\n If you specify --wait with the 'stop' option, the service and all dependent services will be stopped,\n each waiting the specified period.\n'''\n\n# Import all the modules that make life easy\nimport servicemanager\nimport socket\nimport sys\nimport win32event\nimport win32service\nimport win32serviceutil\nimport win32evtlogutil\nimport os\nfrom logging import Formatter, Handler\nimport logging\nimport subprocess\n\n\n# Define the win32api class\nclass Service (win32serviceutil.ServiceFramework):\n # The following variable are edited by the build.sh script\n _svc_name_ = \"TestService\"\n _svc_display_name_ = \"Test Service\"\n _svc_description_ = \"Test Running Python Scripts as a Service\"\n service_exe = 'c:/Python27/python.exe'\n service_script = None\n service_params = []\n service_startDir = None\n\n # Initialize the service\n def __init__(self, args):\n win32serviceutil.ServiceFramework.__init__(self, args)\n self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)\n self.configure_logging()\n socket.setdefaulttimeout(60)\n\n # Configure logging to the WINDOWS Event logs\n def configure_logging(self):\n self.formatter = Formatter('%(message)s')\n self.handler = logHandler()\n self.handler.setFormatter(self.formatter)\n self.logger = logging.getLogger()\n self.logger.addHandler(self.handler)\n self.logger.setLevel(logging.INFO)\n\n # Stop the service\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n # Run the service\n def SvcDoRun(self):\n self.main()\n\n # This is the service\n def main(self):\n\n # Log that we are starting\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_, ''))\n\n # Fire off the real process that does the real work\n logging.info('%s - about to call Popen() to run %s %s %s', self._svc_name_, self.service_exe, self.service_script, self.service_params)\n self.process = subprocess.Popen([self.service_exe, self.service_script] + self.service_params, shell=False, cwd=self.service_startDir)\n logging.info('%s - started process %d', self._svc_name_, self.process.pid)\n\n # Wait until WINDOWS kills us - retrigger the wait for stop every 60 seconds\n rc = None\n while rc != win32event.WAIT_OBJECT_0:\n rc = win32event.WaitForSingleObject(self.hWaitStop, (1 * 60 * 1000))\n\n # Shut down the real process and exit\n logging.info('%s - is terminating process %d', self._svc_name_, self.process.pid)\n self.process.terminate()\n logging.info('%s - is exiting', self._svc_name_)\n\n\nclass logHandler(Handler):\n '''\nEmit a log record to the WINDOWS Event log\n '''\n\n def emit(self, record):\n servicemanager.LogInfoMsg(record.getMessage())\n\n\n# The main code\nif __name__ == '__main__':\n '''\nCreate a Windows Service, which, when started, will run an executable with the specified parameters.\n '''\n\n # Check that configuration contains valid values just in case this service has accidentally\n # been moved to a server where things are in different places\n if not os.path.isfile(Service.service_exe):\n print('Executable file({!s}) does not exist'.format(Service.service_exe), file=sys.stderr)\n sys.exit(0)\n if not os.access(Service.service_exe, os.X_OK):\n print('Executable file({!s}) is not executable'.format(Service.service_exe), file=sys.stderr)\n sys.exit(0)\n # Check that any optional startup directory exists\n if (Service.service_startDir is not None) and (not os.path.isdir(Service.service_startDir)):\n print('Start up directory({!s}) does not exist'.format(Service.service_startDir), file=sys.stderr)\n sys.exit(0)\n\n if len(sys.argv) == 1:\n servicemanager.Initialize()\n servicemanager.PrepareToHostSingle(Service)\n servicemanager.StartServiceCtrlDispatcher()\n else:\n # install/update/remove/start/stop/restart or debug the service\n # One of those command line options must be specified\n win32serviceutil.HandleCommandLine(Service)\n #!/bin/sh\n# This script build a Windows Service that will install/start/stop/remove a service that runs a script\n# That is, executes Python to run a Python script, or PowerShell to run a PowerShell script, etc\n\nif [ $# -lt 6 ]; then\n echo \"Usage: build.sh Name Display Description Executable Script StartupDir [Params]...\"\n exit 0\nfi\n\nname=$1\ndisplay=$2\ndesc=$3\nexe=$4\nscript=$5\nstartDir=$6\nshift; shift; shift; shift; shift; shift\nparams=\nwhile [ $# -gt 0 ]; do\n if [ \"${params}\" != \"\" ]; then\n params=\"${params}, \"\n fi\n params=\"${params}'$1'\"\n shift\ndone\n\ncat pyGlue.py | sed -e \"s/pyGlue/${name}/g\" | \\\n sed -e \"/_svc_name_ =/s?=.*?= '${name}'?\" | \\\n sed -e \"/_svc_display_name_ =/s?=.*?= '${display}'?\" | \\\n sed -e \"/_svc_description_ =/s?=.*?= '${desc}'?\" | \\\n sed -e \"/service_exe =/s?=.*?= '$exe'?\" | \\\n sed -e \"/service_script =/s?=.*?= '$script'?\" | \\\n sed -e \"/service_params =/s?=.*?= [${params}]?\" | \\\n sed -e \"/service_startDir =/s?=.*?= '${startDir}'?\" > ${name}.py\n\ncxfreeze ${name}.py --include-modules=win32timezone\n # A script to build all the script based Services on this PC\nsh build.sh AutoCode 'AutoCode Medical Documents' 'Autocode Medical Documents to SNOMED_CT and AIHW codes' C:/Python38/python.exe autocode.py C:/Users/russell/Documents/autocoding -S -T\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
32,412
<p>I've been tasked with the the maintenance of a nonprofit website that recently fell victim to a SQL injection attack. Someone exploited a form on the site to add text to every available text-like field in the database (varchar, nvarchar, etc.) which, when rendered as HTML, includes and executes a JavaScript file. </p> <p>A Google search of the URL indicates that it's from email spammers based out of Romania or China, but that's not what's important right now.</p> <p>I went through and manually removed the information from the the text fields that render on most visible and popular pages on the site but I'm curious as to what would be the best programmatic way of removing the text from the other text fields on the site. </p> <p>Obviously there's more that needs to be done (hardening the site against SQL injections, using something like markdown instead of storing HTML, etc.) and I am working on those but for the time being what I really need is a good way to go in and programmatically remove the injected text. I know what the exact text is, it's the same every time, and it's always appended to the end of any text field. I can't afford to strip out all HTML in the database at this time and I don't know when this happened exactly so I can't just roll back to a backup. Also, the site is on shared hosting and I cannot connect to the database directly with SQL Server tools. I can execute queries against it though, so if there's any way of constructing a SQL update statement to the effect of "hey find all the text fields in all of the tables in the entire database and do this to clean them" that would be the best. </p>
[ { "answer_id": 32422, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "DECLARE @T VARCHAR(255),@C VARCHAR(4000) \nDECLARE Table_Cursor CURSOR FOR \nSELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id and a.xtype='u' and\n(b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167) \nOPEN Table_Cursor \nFETCH NEXT FROM Table_Cursor INTO @T,@C \nWHILE(@@FETCH_STATUS=0) \nBEGIN \nEXEC('if exists (select 1 from ['+@T+'] where ['+@C+'] like ''%\"></title><script src=\"http://1.verynx.cn/w.js\"></script><!--'') begin print ''update ['+@T+'] set ['+@C+']=replace(['+@C+'],''''\"></title><script src=\"http://1.verynx.cn/w.js\"></script><!--'''','''''''') where ['+@C+'] like ''''%\"></title><script src=\"http://1.verynx.cn/w.js\"></script><!--'''''' end')\nFETCH NEXT FROM Table_Cursor INTO @T,@C \nEND \nCLOSE Table_Cursor \nDEALLOCATE Table_Cursor\n" }, { "answer_id": 3894547, "author": "Carlos", "author_id": 470692, "author_profile": "https://Stackoverflow.com/users/470692", "pm_score": 2, "selected": false, "text": "UPDATE Table \nSET TextField = SUBSTRING(TextField, 1, CHARINDEX('</title', TextField) - 1)\nWHERE (ID IN (SELECT ID FROM Table WHERE (CHARINDEX('</title', Textfield, 1) > 0)))\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
32,414
<p>We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a <kbd>ctrl</kbd><kbd>F5</kbd> refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time.</p> <p>Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome.</p> <p>As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change?</p>
[ { "answer_id": 32427, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 10, "selected": true, "text": "?<version> <script type=\"text/javascript\" src=\"myfile.js?1500\"></script>\n <script type=\"text/javascript\" src=\"myfile.js?$$REVISION$$\"></script>\n" }, { "answer_id": 83853, "author": "Richard Turner", "author_id": 12559, "author_profile": "https://Stackoverflow.com/users/12559", "pm_score": 2, "selected": false, "text": "snazzy_javascript_file.js snazzy_javascript_file_7.js snazzy_javascript_file_8.js" }, { "answer_id": 84846, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 7, "selected": false, "text": "Cache-Control: max-age=86400, must-revalidate\n Cache-Control: no-cache, must-revalidate\n" }, { "answer_id": 84871, "author": "Echo says Reinstate Monica", "author_id": 13778, "author_profile": "https://Stackoverflow.com/users/13778", "pm_score": 4, "selected": false, "text": "stuff.js?123 stuff_123.js mod_redirect have stuff_*.js stuff.js" }, { "answer_id": 857557, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "file.js?V=1 fileV1.js file.js?V=1 jQuery.1.3.js jQuery.1.1.js" }, { "answer_id": 4293901, "author": "Derek Adair", "author_id": 231435, "author_profile": "https://Stackoverflow.com/users/231435", "pm_score": 2, "selected": false, "text": "GET ?v=AUTO_INCREMENT_VERSION" }, { "answer_id": 14672139, "author": "user1944129", "author_id": 1944129, "author_profile": "https://Stackoverflow.com/users/1944129", "pm_score": 3, "selected": false, "text": "function latest_version($file_name){\n echo $file_name.\"?\".filemtime($_SERVER['DOCUMENT_ROOT'] .$file_name);\n}\n <script type=\"text/javascript\" src=\"<?php latest_version('/a-o/javascript/almanacka.js'); ?>\">< /script>\n filepath filetime filepath+name+\"?\"+time" }, { "answer_id": 18033575, "author": "Ivan Kochurkin", "author_id": 1046374, "author_profile": "https://Stackoverflow.com/users/1046374", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\" src=\"Scripts/exampleScript<%=Global.JsPostfix%>\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"Css/exampleCss<%=Global.CssPostfix%>\" />\n protected void Application_Start(object sender, EventArgs e)\n{\n ...\n string jsVersion = ConfigurationManager.AppSettings[\"JsVersion\"];\n bool updateEveryAppStart = Convert.ToBoolean(ConfigurationManager.AppSettings[\"UpdateJsEveryAppStart\"]);\n int buildNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Revision;\n JsPostfix = \"\";\n#if !DEBUG\n JsPostfix += \".min\";\n#endif \n JsPostfix += \".js?\" + jsVersion + \"_\" + buildNumber;\n if (updateEveryAppStart)\n {\n Random rand = new Random();\n JsPosfix += \"_\" + rand.Next();\n }\n ...\n}\n" }, { "answer_id": 21297413, "author": "Ravi Ram", "author_id": 665387, "author_profile": "https://Stackoverflow.com/users/665387", "pm_score": 4, "selected": false, "text": "<script src=\"/Scripts/pages/common.js\" type=\"text/javascript\"></script>\n <script src=\"/Scripts/pages/common.js?ver<%=DateTime.Now.Ticks.ToString()%>\" type=\"text/javascript\"></script>\n" }, { "answer_id": 25316713, "author": "amos", "author_id": 319034, "author_profile": "https://Stackoverflow.com/users/319034", "pm_score": 5, "selected": false, "text": "CACHE MANIFEST\n# Aug 14, 2014\n/mycode.js\n\nNETWORK:\n*\n" }, { "answer_id": 33058872, "author": "Michael Franz", "author_id": 4479748, "author_profile": "https://Stackoverflow.com/users/4479748", "pm_score": 2, "selected": false, "text": "$(document).ready(function(){\n $.getScript(\"../data/playlist.js\", function(data, textStatus, jqxhr){\n startProgram();\n });\n});\n" }, { "answer_id": 34032995, "author": "Erik Corona", "author_id": 5531314, "author_profile": "https://Stackoverflow.com/users/5531314", "pm_score": 5, "selected": false, "text": "<script type='text/javascript' src='path/to/file/mylibrary.js?filever=<?=filesize('path/to/file/mylibrary.js')?>'></script>\n" }, { "answer_id": 41501905, "author": "Goran Siriev", "author_id": 5917218, "author_profile": "https://Stackoverflow.com/users/5917218", "pm_score": 1, "selected": false, "text": "RewriteEngine On\nRewriteBase /\nRewriteCond %{REQUEST_URI} \\.(jpe?g|bmp|png|gif|css|js|mp3|ogg)$ [NC]\nRewriteCond %{QUERY_STRING} !^(.+?&v33|)v=33[^&]*(?:&(.*)|)$ [NC]\nRewriteRule ^ %{REQUEST_URI}?v=33 [R=301,L]\n" }, { "answer_id": 44835940, "author": "ccherwin", "author_id": 3320423, "author_profile": "https://Stackoverflow.com/users/3320423", "pm_score": 2, "selected": false, "text": "<link rel=\"stylesheet\" href=\"~/css/site.min.css\" asp-append-version=\"true\"/>\n" }, { "answer_id": 47174803, "author": "Aman Singh", "author_id": 2570255, "author_profile": "https://Stackoverflow.com/users/2570255", "pm_score": 3, "selected": false, "text": "<script src=\"https://thesaasdomain.com/somejsfile.js\" data-ut=\"user_token\"></script>\n if($('script[src^=\"https://thesaasdomain.com/somejsfile.js?\"]').length !== 0) {\n init();\n} else {\n loadScript(\"https://thesaasdomain.com/somejsfile.js?\" + guid());\n}\n\nvar loadscript = function(scriptURL) {\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = scriptURL;\n head.appendChild(script);\n}\n\nvar guid = function() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\nvar init = function() {\n // our main code\n}\n" }, { "answer_id": 53721063, "author": "dragonal", "author_id": 7376037, "author_profile": "https://Stackoverflow.com/users/7376037", "pm_score": 2, "selected": false, "text": "<script src=\"~/JsFilePath/[email protected]()\"></script>\n" }, { "answer_id": 54941810, "author": "H.Ostwal", "author_id": 7750626, "author_profile": "https://Stackoverflow.com/users/7750626", "pm_score": 0, "selected": false, "text": "<head>\n<meta charset=\"UTF-8\">\n<meta http-equiv=\"cache-control\" content=\"no-cache, must-revalidate, post-check=0, pre-check=0\" />\n<meta http-equiv=\"cache-control\" content=\"max-age=0\" />\n<meta http-equiv=\"expires\" content=\"0\" />\n<meta http-equiv=\"expires\" content=\"Tue, 01 Jan 1980 1:00:00 GMT\" />\n<meta http-equiv=\"pragma\" content=\"no-cache\" />\n</head>\n" }, { "answer_id": 62428811, "author": "Mohamad Hamouday", "author_id": 4110122, "author_profile": "https://Stackoverflow.com/users/4110122", "pm_score": 1, "selected": false, "text": "https://www.example.com/script_fv25.js\n RewriteEngine On\nRewriteRule (.*)_fv\\d+\\.(js|css|txt|jpe?g|png|svg|ico|gif) $1.$2 [L]\n https://www.example.com/script.js\n" }, { "answer_id": 63309105, "author": "Luis Lobo", "author_id": 11212275, "author_profile": "https://Stackoverflow.com/users/11212275", "pm_score": 1, "selected": false, "text": "new Date().getTime()\n // cache-expires-after.js v1\nfunction cacheExpiresAfter(delay = 1, prefix = '', suffix = '') { // seconds\n let now = new Date().getTime().toString();\n now = now.substring(now.length - 11, 10); // remove decades and milliseconds\n now = parseInt(now / delay).toString();\n return prefix + now + suffix;\n};\n\n// examples (of the delay argument):\n// the value changes every 1 second\nvar cache = cacheExpiresAfter(1);\n// see the sync\nsetInterval(function(){\n console.log(cacheExpiresAfter(1), new Date().getSeconds() + 's');\n}, 1000);\n\n// the value changes every 1 minute\nvar cache = cacheExpiresAfter(60);\n// see the sync\nsetInterval(function(){\n console.log(cacheExpiresAfter(60), new Date().getMinutes() + 'm:' + new Date().getSeconds() + 's');\n}, 1000);\n\n// the value changes every 5 minutes\nvar cache = cacheExpiresAfter(60 * 5); // OR 300\n\n// the value changes every 1 hour\nvar cache = cacheExpiresAfter(60 * 60); // OR 3600\n\n// the value changes every 3 hours\nvar cache = cacheExpiresAfter(60 * 60 * 3); // OR 10800\n\n// the value changes every 1 day\nvar cache = cacheExpiresAfter(60 * 60 * 24); // OR 86400\n\n// usage example:\nlet head = document.head || document.getElementsByTagName('head')[0];\nlet script = document.createElement('script');\nscript.setAttribute('src', '//unpkg.com/[email protected]/dist/sweetalert.min.js' + cacheExpiresAfter(60 * 5, '?'));\nhead.append(script);\n\n// this works?\nlet waitSwal = setInterval(function() {\n if (window.swal) {\n clearInterval(waitSwal);\n swal('Script successfully injected', script.outerHTML);\n };\n}, 100);\n" }, { "answer_id": 65130064, "author": "Hans-Peter Stricker", "author_id": 363429, "author_profile": "https://Stackoverflow.com/users/363429", "pm_score": -1, "selected": false, "text": "<h1 id=\"welcome\"> Welcome to this page <span style=\"color:red\">... press Ctrl-F5</span></h1>\n document.getElementById(\"welcome\").innerHTML = \"Welcome to this page\"\n" }, { "answer_id": 66656955, "author": "Darshan Jain", "author_id": 5840973, "author_profile": "https://Stackoverflow.com/users/5840973", "pm_score": 0, "selected": false, "text": "$fileVersion = rand();\n<script src=\"addNewStudent.js?v=<?php echo $fileVersion; ?>\"></script>\n" }, { "answer_id": 73223699, "author": "Ingo", "author_id": 2278668, "author_profile": "https://Stackoverflow.com/users/2278668", "pm_score": -1, "selected": false, "text": "# DISABLE CACHING\n<IfModule mod_headers.c>\n <FilesMatch \"\\.js$\">\n Header set Cache-Control \"no-store, max-age=0\"\n </FilesMatch>\n</IfModule>\n" }, { "answer_id": 73327865, "author": "Reggie Pinkham", "author_id": 2927114, "author_profile": "https://Stackoverflow.com/users/2927114", "pm_score": 0, "selected": false, "text": "<script> \n var version = new Date().getTime(); \n var script = document.createElement(\"script\"); \n script.src = \"app.js?=\" + version; \n document.body.appendChild(script); \n</script>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176/" ]
32,428
<p>I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work).</p> <p>Here is the error that is thrown by the custom code I've written.</p> <blockquote> <p>System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark&amp; stackMark, Int32 unrestrictedOverride, Int32 create) at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark&amp; stackMark) at System.Security.CodeAccessPermission.Assert() at [Snipped Method Name] at ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.SecurityPermission The Zone of the assembly that failed was: MyComputer</p> </blockquote> <p>This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it :)</p> <p>I believe the code that is failing is this:</p> <pre><code> Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted) fio.Assert() </code></pre> <p>However, this kind of stuff is everywhere too:</p> <pre><code>Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer </code></pre> <p>I can see either of these being things that Reporting Services would not accommodate out of the box.</p>
[ { "answer_id": 37379, "author": "Ian Robinson", "author_id": 326, "author_profile": "https://Stackoverflow.com/users/326", "pm_score": 4, "selected": true, "text": " <CodeGroup\n class=\"UnionCodeGroup\"\n version=\"1\"\n PermissionSetName=\"FullTrust\"\n Name=\"Test\"\n Description=\"This code group grants the Test code full trust. \">\n <IMembershipCondition\n class=\"StrongNameMembershipCondition\"\n version=\"1\"\n PublicKeyBlob=\"0024000004800000940100000602000000240000575341310004000001000100ab4b135615ca6dfd586aa0c5807b3e07fa7a02b3f376c131e0442607de792a346e64710e82c833b42c672680732f16193ba90b2819a77fa22ac6d41559724b9c253358614c270c651fad5afe9a0f8cbd1e5e79f35e0f04cb3e3b020162ac86f633cf0d205263280e3400d1a5b5781bf6bd12f97917dcdde3c8d03ee61ccba2c0\"\n />\n </CodeGroup>\n" }, { "answer_id": 5516520, "author": "Noorani raza", "author_id": 687994, "author_profile": "https://Stackoverflow.com/users/687994", "pm_score": 4, "selected": false, "text": "<system.web>\n\n<trust level=\"Full\"/>\n\n</system.web>\n" }, { "answer_id": 54830270, "author": "Neil Schurrer", "author_id": 6104737, "author_profile": "https://Stackoverflow.com/users/6104737", "pm_score": 0, "selected": false, "text": " <CodeGroup class=\"FirstMatchCodeGroup\" version=\"1\" PermissionSetName=\"FullTrust\">\n rssrvpolicy.config \"None\" \"FullTrust\"" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326/" ]
32,433
<p>This query works great:</p> <pre><code>var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select op) .SingleOrDefault(); </code></pre> <p>I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but</p> <pre><code>select op, pg).SingleOrDefault(); </code></pre> <p>doesn't work.</p> <p>How can I select everything from both tables so that they appear in my new pageObject type?</p>
[ { "answer_id": 32445, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": " select new { op, pg }\n" }, { "answer_id": 32449, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "select op) \n select new { op, pg })\n" }, { "answer_id": 32465, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 8, "selected": true, "text": "var pageObject = (from op in db.ObjectPermissions\n join pg in db.Pages on op.ObjectPermissionName equals page.PageName\n where pg.PageID == page.PageID\n select new { pg, op }).SingleOrDefault();\n var pageObject = (from op in db.ObjectPermissions\n join pg in db.Pages on op.ObjectPermissionName equals page.PageName\n where pg.PageID == page.PageID\n select new\n {\n PermissionName = pg, \n ObjectPermission = op\n }).SingleOrDefault();\n if (pageObject.PermissionName.FooBar == \"golden goose\") Application.Exit();\n" }, { "answer_id": 144219, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 3, "selected": false, "text": "db.DeferredLoadingEnabled = false;\nDataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith<ObjectPermissions>(op => op.Pages)\ndb.LoadOptions = dlo;\n\nvar pageObject = from op in db.ObjectPermissions\n select op;\n\n// no join needed\n pageObject.Pages.PageID\n DataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith<Pages>(p => p.ObjectPermissions)\ndb.LoadOptions = dlo;\n\nvar pageObject = from p in db.Pages\n select p;\n\n// no join needed\n\nvar objectPermissionName = pageObject.ObjectPermissions.ObjectPermissionName;\n" }, { "answer_id": 10050917, "author": "daviddeath", "author_id": 1277335, "author_profile": "https://Stackoverflow.com/users/1277335", "pm_score": 2, "selected": false, "text": "public class PermissionsAndPages\n{\n public ObjectPermissions Permissions {get;set}\n public Pages Pages {get;set}\n}\n select new PermissionsAndPages { Permissions = op, Page = pg };\n return queryResult.SingleOrDefault(); // as PermissionsAndPages\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
32,448
<p>The product-group I work for is currently using gcc 3.4.6 (we know it is ancient) for a large low-level c-code base, and want to upgrade to a later version. We have seen performance benefits testing different versions of gcc 4.x on all hardware platforms we tested it on. We are however <em>very</em> scared of c-compiler bugs (for a good reason historically), and wonder if anyone has insight to which version we should upgrade to.</p> <p>Are people using 4.3.2 for large code-bases and feel that it works fine?</p>
[ { "answer_id": 14654717, "author": "vonbrand", "author_id": 1839777, "author_profile": "https://Stackoverflow.com/users/1839777", "pm_score": 1, "selected": false, "text": "-Wall" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1524/" ]
32,458
<p>I have a coworker who writes unit tests for objects which fill their fields with random data. His reason is that it gives a wider range of testing, since it will test a lot of different values, whereas a normal test only uses a single static value.</p> <p>I've given him a number of different reasons against this, the main ones being:</p> <ul> <li>random values means the test isn't truly repeatable (which also means that if the test can randomly fail, it can do so on the build server and break the build)</li> <li>if it's a random value and the test fails, we need to a) fix the object and b) force ourselves to test for that value every time, so we know it works, but since it's random we don't know what the value was</li> </ul> <p>Another coworker added:</p> <ul> <li>If I am testing an exception, random values will not ensure that the test ends up in the expected state</li> <li>random data is used for flushing out a system and load testing, not for unit tests</li> </ul> <p>Can anyone else add additional reasons I can give him to get him to stop doing this?</p> <p>(Or alternately, is this an acceptable method of writing unit tests, and I and my other coworker are wrong?)</p>
[ { "answer_id": 71762174, "author": "armandino", "author_id": 45112, "author_profile": "https://Stackoverflow.com/users/45112", "pm_score": 2, "selected": false, "text": "Person person = Instancio.create(Person.class);\n Person person = Instancio.of(Person.class)\n .generate(field(\"age\"), gen -> gen.ints.min(18).max(65))\n .create();\n <dependency>\n <groupId>org.instancio</groupId>\n <artifactId>instancio-junit</artifactId>\n <version>LATEST</version>\n</dependency>\n\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/517/" ]
32,460
<p>Here's the situation: I need to bind a WPF <code>FixedPage</code> against a <code>DataRow</code>. Bindings don't work against <code>DataRows</code>; they work against <code>DataRowViews</code>. I need to do this in the most generic way possible, as I know nothing about and have no control over what is in the <code>DataRow</code>. </p> <p>What I need is to be able to get a <code>DataRowView</code> for a given <code>DataRow</code>. I can't use the <code>Find()</code> method on the <code>DefaultView</code> because that takes a key, and there is no guarantee the table will have a primary key set.</p> <p>Does anybody have a suggestion as to the best way to go around this? </p>
[ { "answer_id": 32483, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "row.Table.DefaultView[row.Table.Rows.IndexOf(row)]\n" }, { "answer_id": 6989851, "author": "Joel Barsotti", "author_id": 37154, "author_profile": "https://Stackoverflow.com/users/37154", "pm_score": 4, "selected": true, "text": " DataRowView newRowView = null;\n foreach (DataRowView tempRowView in myDataTable.DefaultView)\n {\n if (tempRowView.Row == rowToMatch)\n newRowView = tempRowView;\n }\n if (newRow != null)\n UseNewRowView(newRowView);\n else\n HandleRowNotFound();\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
32,462
<p>So I've got a hobby site I'm working on. I've got items that are tagged and I want to associate those items with photos from Flickr. Even with restrictive searches, I might get results numbering in the thousands.</p> <p>Requirements:</p> <ol> <li>I want to display between 10-20 pictures but I want to randomize the photos each time. </li> <li>I don't want to hit Flickr every time a page request is made. </li> <li>Not every Flickr photo with the same tags as my item will be relevant.</li> </ol> <p>How should I store that number of results and how would I determine which ones are relevant?</p>
[ { "answer_id": 32483, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "row.Table.DefaultView[row.Table.Rows.IndexOf(row)]\n" }, { "answer_id": 6989851, "author": "Joel Barsotti", "author_id": 37154, "author_profile": "https://Stackoverflow.com/users/37154", "pm_score": 4, "selected": true, "text": " DataRowView newRowView = null;\n foreach (DataRowView tempRowView in myDataTable.DefaultView)\n {\n if (tempRowView.Row == rowToMatch)\n newRowView = tempRowView;\n }\n if (newRow != null)\n UseNewRowView(newRowView);\n else\n HandleRowNotFound();\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863/" ]
32,529
<p>I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory.</p> <p>How should I go about doing that?</p>
[ { "answer_id": 32658, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 5, "selected": false, "text": "class DirectoryRestrictedFileSystemView extends FileSystemView\n{\n private final File[] rootDirectories;\n\n DirectoryRestrictedFileSystemView(File rootDirectory)\n {\n this.rootDirectories = new File[] {rootDirectory};\n }\n\n DirectoryRestrictedFileSystemView(File[] rootDirectories)\n {\n this.rootDirectories = rootDirectories;\n }\n\n @Override\n public File createNewFolder(File containingDir) throws IOException\n { \n throw new UnsupportedOperationException(\"Unable to create directory\");\n }\n\n @Override\n public File[] getRoots()\n {\n return rootDirectories;\n }\n\n @Override\n public boolean isRoot(File file)\n {\n for (File root : rootDirectories) {\n if (root.equals(file)) {\n return true;\n }\n }\n return false;\n }\n}\n FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File(\"X:\\\\\"));\nJFileChooser fileChooser = new JFileChooser(fsv);\n FileSystemView fsv = new DirectoryRestrictedFileSystemView( new File[] {\n new File(\"X:\\\\\"),\n new File(\"Y:\\\\\")\n});\nJFileChooser fileChooser = new JFileChooser(fsv);\n" }, { "answer_id": 6852912, "author": "mlh", "author_id": 866528, "author_profile": "https://Stackoverflow.com/users/866528", "pm_score": 3, "selected": false, "text": "public TFile getHomeDirectory()\n{\n return rootDirectories[0];\n} public JFileChooser fileChooser = new JFileChooser(fsv); JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);" }, { "answer_id": 12244107, "author": "Siddharth Tyagi", "author_id": 1052227, "author_profile": "https://Stackoverflow.com/users/1052227", "pm_score": -1, "selected": false, "text": "JFileChooser fc = new JFileChooser();\nfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\nfc.setMultiSelectionEnabled(false);\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
32,537
<p>For scripting languages, what is the most effective way to utilize a console when developing? Are there ways to be more productive with a console than a "compile and run" only language?</p> <p>Added clarification: I am thinking more along the lines of Ruby, Python, Boo, etc. Languages that are used for full blown apps, but also have a way to run small snippets of code in a console.</p>
[ { "answer_id": 32686, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 3, "selected": true, "text": "irb .irbrc \"\".ch<tab> String#[] joe[~]$ irb\n>> \"12341:asdf\"[/\\d+/]\n# => \"12341\" \n>> \"12341:asdf\"[/\\d*/]\n# => \"12341\" \n>> \"12341:asdf\"[0..5]\n# => \"12341:\" \n>> \"12341:asdf\"[0...5]\n# => \"12341\" \n>> \"12341:asdf\"[0, ':']\nTypeError: can't convert String into Integer\n from (irb):5:in `[]'\n from (irb):5\n>> \"12341:asdf\"[0, 5]\n# => \"12341\" \n time .irbrc" }, { "answer_id": 36446, "author": "asussex", "author_id": 3796, "author_profile": "https://Stackoverflow.com/users/3796", "pm_score": 1, "selected": false, "text": " ----------------\n| |\n| 1 |\n| |\n ----------------\n ----------------\n| |\n| 2 |\n| |\n ----------------\n ------- -------\n| || |\n| || |\n| 1 || 2 |\n| || |\n| || |\n ------- -------\n ------- -------\n| || 2 |\n| || |\n| | -------\n| 1 | -------\n| || 3 |\n| || |\n ------- -------\n ------- -------\n| | -------\n| || |\n| 1 || 3 |\n| || |\n| || |\n ------- -------\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2001/" ]
32,540
<p>How is your javaScript code organized? Does it follow patterns like MVC, or something else? </p> <p>I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with <a href="http://jquery.com" rel="noreferrer">jQuery</a>, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":</p> <ul> <li>The 'model' is a JSON tree that gets extended with helpers</li> <li>The view is the DOM plus classes that tweak it</li> <li>The controller is the object where I connect events handling and kick off view or model manipulation</li> </ul> <p>I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + &lt;generic web service-y thingy here&gt;"</p> <p>Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.</p>
[ { "answer_id": 32594, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 4, "selected": true, "text": "var Vehicle = jQuery.Class.create({ \n init: function(name) { this.name = name; } \n});\n\nvar Car = Vehicle.extend({ \n fillGas: function(){ \n this.gas = 100; \n } \n});\n" }, { "answer_id": 1316984, "author": "Justin Meyer", "author_id": 161238, "author_profile": "https://Stackoverflow.com/users/161238", "pm_score": 2, "selected": false, "text": "$.Controller.extend('TodosController',{\n 'click' : function(el, ev){ ... },\n '.delete mouseover': function(el, ev){ ...}\n '.drag draginit' : function(el, ev, drag){ ...}\n})\n '.show click' : function(el, ev){ \n Todo.findAll({after: new Date()}, this.callback('list'));\n},\nlist : function(todos){\n $('#todos').html( this.view(todos));\n}\n <% for(var i =0; i < this.length; i++){ %>\n <label><%= this[i].description %></label>\n<%}%>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3436/" ]
32,541
<p>Anybody have a good example how to deep clone a WPF object, preserving databindings?</p> <hr> <p>The marked answer is the first part.</p> <p>The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here:<br> <a href="http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2801571" rel="noreferrer">http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2801571</a></p>
[ { "answer_id": 32575, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 0, "selected": false, "text": " public static T DeepClone<T>(T from)\n {\n using (MemoryStream s = new MemoryStream())\n {\n BinaryFormatter f = new BinaryFormatter();\n f.Serialize(s, from);\n s.Position = 0;\n object clone = f.Deserialize(s);\n\n return (T)clone;\n }\n }\n" }, { "answer_id": 33036, "author": "Alan Le", "author_id": 1133, "author_profile": "https://Stackoverflow.com/users/1133", "pm_score": 7, "selected": true, "text": "string gridXaml = XamlWriter.Save(myGrid);\n StringReader stringReader = new StringReader(gridXaml);\nXmlReader xmlReader = XmlReader.Create(stringReader);\nGrid newGrid = (Grid)XamlReader.Load(xmlReader);\n" }, { "answer_id": 4973369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "var sb = new StringBuilder();\nvar writer = XmlWriter.Create(sb, new XmlWriterSettings\n{\n Indent = true,\n ConformanceLevel = ConformanceLevel.Fragment,\n OmitXmlDeclaration = true,\n NamespaceHandling = NamespaceHandling.OmitDuplicates, \n});\nvar mgr = new XamlDesignerSerializationManager(writer);\n\n// HERE BE MAGIC!!!\nmgr.XamlWriterMode = XamlWriterMode.Expression;\n// THERE WERE MAGIC!!!\n\nSystem.Windows.Markup.XamlWriter.Save(this, mgr);\nreturn sb.ToString();\n" }, { "answer_id": 14740448, "author": "John Zabroski", "author_id": 1040437, "author_profile": "https://Stackoverflow.com/users/1040437", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Extension methods for the WPF Binding class.\n/// </summary>\npublic static class BindingExtensions\n{\n public static BindingBase CloneViaXamlSerialization(this BindingBase binding)\n {\n var sb = new StringBuilder();\n var writer = XmlWriter.Create(sb, new XmlWriterSettings\n {\n Indent = true,\n ConformanceLevel = ConformanceLevel.Fragment,\n OmitXmlDeclaration = true,\n NamespaceHandling = NamespaceHandling.OmitDuplicates,\n });\n var mgr = new XamlDesignerSerializationManager(writer);\n\n // HERE BE MAGIC!!!\n mgr.XamlWriterMode = XamlWriterMode.Expression;\n // THERE WERE MAGIC!!!\n\n System.Windows.Markup.XamlWriter.Save(binding, mgr);\n StringReader stringReader = new StringReader(sb.ToString());\n XmlReader xmlReader = XmlReader.Create(stringReader);\n object newBinding = (object)XamlReader.Load(xmlReader);\n if (newBinding == null)\n {\n throw new ArgumentNullException(\"Binding could not be cloned via Xaml Serialization Stack.\");\n }\n\n if (newBinding is Binding)\n {\n return (Binding)newBinding;\n }\n else if (newBinding is MultiBinding)\n {\n return (MultiBinding)newBinding;\n }\n else if (newBinding is PriorityBinding)\n {\n return (PriorityBinding)newBinding;\n }\n else\n {\n throw new InvalidOperationException(\"Binding could not be cast.\");\n }\n }\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
32,570
<p>Is there some way I can use URLs like: </p> <p><em><a href="http://www.blog.com/team-spirit/" rel="nofollow noreferrer">http://www.blog.com/team-spirit/</a></em></p> <p>instead of</p> <p><em><a href="http://www.blog.com/?p=122" rel="nofollow noreferrer">http://www.blog.com/?p=122</a></em></p> <p>in a Windows hosted PHP server?</p>
[ { "answer_id": 73370706, "author": "Alamin Sarkar", "author_id": 19773925, "author_profile": "https://Stackoverflow.com/users/19773925", "pm_score": 0, "selected": false, "text": "# any file that exists just return it \nRewriteCond %{REQUEST_FILENAME} -f \nRewriteRule ^(.*) $1 [L]\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
32,586
<p>Is there an easy way to discover a File's creation time with Java? The File class only has a method to get the "last modified" time. According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.</p> <p>The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time. I guess this works, I only need to support Windows, but it seems very error prone to me.</p> <p>Are there any third party libraries that provide the info I need?</p> <p><strong>Update:</strong> In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a good choice for anyone else that has this problem. </p>
[ { "answer_id": 3350512, "author": "LiuYan 刘研", "author_id": 404192, "author_profile": "https://Stackoverflow.com/users/404192", "pm_score": 3, "selected": false, "text": "// Get/Set windows file CreationTime/LastWriteTime/LastAccessTime\n// Test with jna-3.2.7\n// [http://maclife.net/wiki/index.php?title=Java_get_and_set_windows_system_file_creation_time_via_JNA_(Java_Native_Access)][1]\n\nimport java.io.*;\nimport java.nio.*;\nimport java.util.Date;\n\n// Java Native Access library: jna.dev.java.net\nimport com.sun.jna.*;\nimport com.sun.jna.ptr.*;\nimport com.sun.jna.win32.*;\nimport com.sun.jna.platform.win32.*;\n\npublic class WindowsFileTime\n{\n public static final int GENERIC_READ = 0x80000000;\n //public static final int GENERIC_WRITE = 0x40000000; // defined in com.sun.jna.platform.win32.WinNT\n public static final int GENERIC_EXECUTE = 0x20000000;\n public static final int GENERIC_ALL = 0x10000000;\n\n // defined in com.sun.jna.platform.win32.WinNT\n //public static final int CREATE_NEW = 1;\n //public static final int CREATE_ALWAYS = 2;\n //public static final int OPEN_EXISTING = 3;\n //public static final int OPEN_ALWAYS = 4;\n //public static final int TRUNCATE_EXISTING = 5;\n\n public interface MoreKernel32 extends Kernel32\n {\n static final MoreKernel32 instance = (MoreKernel32)Native.loadLibrary (\"kernel32\", MoreKernel32.class, W32APIOptions.DEFAULT_OPTIONS);\n boolean GetFileTime (WinNT.HANDLE hFile, WinBase.FILETIME lpCreationTime, WinBase.FILETIME lpLastAccessTime, WinBase.FILETIME lpLastWriteTime);\n boolean SetFileTime (WinNT.HANDLE hFile, final WinBase.FILETIME lpCreationTime, final WinBase.FILETIME lpLastAccessTime, final WinBase.FILETIME lpLastWriteTime);\n }\n\n static MoreKernel32 win32 = MoreKernel32.instance;\n //static Kernel32 _win32 = (Kernel32)win32;\n\n static WinBase.FILETIME _creationTime = new WinBase.FILETIME ();\n static WinBase.FILETIME _lastWriteTime = new WinBase.FILETIME ();\n static WinBase.FILETIME _lastAccessTime = new WinBase.FILETIME ();\n\n static boolean GetFileTime (String sFileName, Date creationTime, Date lastWriteTime, Date lastAccessTime)\n {\n WinNT.HANDLE hFile = OpenFile (sFileName, GENERIC_READ); // may be WinNT.GENERIC_READ in future jna version.\n if (hFile == WinBase.INVALID_HANDLE_VALUE) return false;\n\n boolean rc = win32.GetFileTime (hFile, _creationTime, _lastAccessTime, _lastWriteTime);\n if (rc)\n {\n if (creationTime != null) creationTime.setTime (_creationTime.toLong());\n if (lastAccessTime != null) lastAccessTime.setTime (_lastAccessTime.toLong());\n if (lastWriteTime != null) lastWriteTime.setTime (_lastWriteTime.toLong());\n }\n else\n {\n int iLastError = win32.GetLastError();\n System.out.print (\"获取文件时间失败,错误码:\" + iLastError + \" \" + GetWindowsSystemErrorMessage (iLastError));\n }\n win32.CloseHandle (hFile);\n return rc;\n }\n static boolean SetFileTime (String sFileName, final Date creationTime, final Date lastWriteTime, final Date lastAccessTime)\n {\n WinNT.HANDLE hFile = OpenFile (sFileName, WinNT.GENERIC_WRITE);\n if (hFile == WinBase.INVALID_HANDLE_VALUE) return false;\n\n ConvertDateToFILETIME (creationTime, _creationTime);\n ConvertDateToFILETIME (lastWriteTime, _lastWriteTime);\n ConvertDateToFILETIME (lastAccessTime, _lastAccessTime);\n\n //System.out.println (\"creationTime: \" + creationTime);\n //System.out.println (\"lastWriteTime: \" + lastWriteTime);\n //System.out.println (\"lastAccessTime: \" + lastAccessTime);\n\n //System.out.println (\"_creationTime: \" + _creationTime);\n //System.out.println (\"_lastWriteTime: \" + _lastWriteTime);\n //System.out.println (\"_lastAccessTime: \" + _lastAccessTime);\n\n boolean rc = win32.SetFileTime (hFile, creationTime==null?null:_creationTime, lastAccessTime==null?null:_lastAccessTime, lastWriteTime==null?null:_lastWriteTime);\n if (! rc)\n {\n int iLastError = win32.GetLastError();\n System.out.print (\"设置文件时间失败,错误码:\" + iLastError + \" \" + GetWindowsSystemErrorMessage (iLastError));\n }\n win32.CloseHandle (hFile);\n return rc;\n }\n static void ConvertDateToFILETIME (Date date, WinBase.FILETIME ft)\n {\n if (ft != null)\n {\n long iFileTime = 0;\n if (date != null)\n {\n iFileTime = WinBase.FILETIME.dateToFileTime (date);\n ft.dwHighDateTime = (int)((iFileTime >> 32) & 0xFFFFFFFFL);\n ft.dwLowDateTime = (int)(iFileTime & 0xFFFFFFFFL);\n }\n else\n {\n ft.dwHighDateTime = 0;\n ft.dwLowDateTime = 0;\n }\n }\n }\n\n static WinNT.HANDLE OpenFile (String sFileName, int dwDesiredAccess)\n {\n WinNT.HANDLE hFile = win32.CreateFile (\n sFileName,\n dwDesiredAccess,\n 0,\n null,\n WinNT.OPEN_EXISTING,\n 0,\n null\n );\n if (hFile == WinBase.INVALID_HANDLE_VALUE)\n {\n int iLastError = win32.GetLastError();\n System.out.print (\" 打开文件失败,错误码:\" + iLastError + \" \" + GetWindowsSystemErrorMessage (iLastError));\n }\n return hFile;\n }\n static String GetWindowsSystemErrorMessage (int iError)\n {\n char[] buf = new char[255];\n CharBuffer bb = CharBuffer.wrap (buf);\n //bb.clear ();\n //PointerByReference pMsgBuf = new PointerByReference ();\n int iChar = win32.FormatMessage (\n WinBase.FORMAT_MESSAGE_FROM_SYSTEM\n //| WinBase.FORMAT_MESSAGE_IGNORE_INSERTS\n //|WinBase.FORMAT_MESSAGE_ALLOCATE_BUFFER\n ,\n null,\n iError,\n 0x0804,\n bb, buf.length,\n //pMsgBuf, 0,\n null\n );\n //for (int i=0; i<iChar; i++)\n //{\n // System.out.print (\" \");\n // System.out.print (String.format(\"%02X\", buf[i]&0xFFFF));\n //}\n bb.limit (iChar);\n //System.out.print (bb);\n //System.out.print (pMsgBuf.getValue().getString(0));\n //win32.LocalFree (pMsgBuf.getValue());\n return bb.toString ();\n }\n\n public static void main (String[] args) throws Exception\n {\n if (args.length == 0)\n {\n System.out.println (\"获取 Windows 的文件时间(创建时间、最后修改时间、最后访问时间)\");\n System.out.println (\"用法:\");\n System.out.println (\" java -cp .;..;jna.jar;platform.jar WindowsFileTime [文件名1] [文件名2]...\");\n return;\n }\n\n boolean rc;\n java.sql.Timestamp ct = new java.sql.Timestamp(0);\n java.sql.Timestamp wt = new java.sql.Timestamp(0);\n java.sql.Timestamp at = new java.sql.Timestamp(0);\n\n for (String sFileName : args)\n {\n System.out.println (\"文件 \" + sFileName);\n\n rc = GetFileTime (sFileName, ct, wt, at);\n if (rc)\n {\n System.out.println (\" 创建时间:\" + ct);\n System.out.println (\" 修改时间:\" + wt);\n System.out.println (\" 访问时间:\" + at);\n }\n else\n {\n //System.out.println (\"GetFileTime 失败\");\n }\n\n\n //wt.setTime (System.currentTimeMillis());\n wt = java.sql.Timestamp.valueOf(\"2010-07-23 00:00:00\");\n rc = SetFileTime (sFileName, null, wt, null);\n if (rc)\n {\n System.out.println (\"SetFileTime (最后修改时间) 成功\");\n }\n else\n {\n //System.out.println (\"SetFileTime 失败\");\n }\n }\n }\n}\n" }, { "answer_id": 6185263, "author": "Kamal", "author_id": 777363, "author_profile": "https://Stackoverflow.com/users/777363", "pm_score": 2, "selected": false, "text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\n\npublic class CreateDateInJava {\n public static void main(String args[]) {\n try {\n\n // get runtime environment and execute child process\n Runtime systemShell = Runtime.getRuntime();\n BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));\n System.out.println(\"Enter filename: \");\n String fname = (String) br1.readLine();\n Process output = systemShell.exec(\"cmd /c dir \\\"\" + fname + \"\\\" /tc\");\n\n System.out.println(output);\n // open reader to get output from process\n BufferedReader br = new BufferedReader(new InputStreamReader(output.getInputStream()));\n\n String out = \"\";\n String line = null;\n\n int step = 1;\n while ((line = br.readLine()) != null) {\n if (step == 6) {\n out = line;\n }\n step++;\n }\n\n // display process output\n try {\n out = out.replaceAll(\" \", \"\");\n System.out.println(\"CreationDate: \" + out.substring(0, 10));\n System.out.println(\"CreationTime: \" + out.substring(10, 16) + \"m\");\n } catch (StringIndexOutOfBoundsException se) {\n System.out.println(\"File not found\");\n }\n } catch (IOException ioe) {\n System.err.println(ioe);\n } catch (Throwable t) {\n t.printStackTrace();\n }\n }\n}\n\n/**\nD:\\Foldername\\Filename.Extension\n\nEx:\nEnter Filename :\nD:\\Kamal\\Test.txt\nCreationDate: 02/14/2011\nCreationTime: 12:59Pm\n\n*/\n" }, { "answer_id": 14287216, "author": "Peter", "author_id": 777443, "author_profile": "https://Stackoverflow.com/users/777443", "pm_score": 2, "selected": false, "text": "javaxt.io.File file = new javaxt.io.File(\"/temp/file.txt\");\nSystem.out.println(\"Created: \" + file.getCreationTime());\nSystem.out.println(\"Accessed: \" + file.getLastAccessTime());\nSystem.out.println(\"Modified: \" + file.getLastModifiedTime());\n" }, { "answer_id": 16969301, "author": "ajon", "author_id": 1068058, "author_profile": "https://Stackoverflow.com/users/1068058", "pm_score": 4, "selected": false, "text": "Path path = Paths.get(\"path/to/file\");\nBasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);\nFileTime creationTime = attributes.creationTime();\n" }, { "answer_id": 32771938, "author": "Jorgesys", "author_id": 250260, "author_profile": "https://Stackoverflow.com/users/250260", "pm_score": 0, "selected": false, "text": "Java BasicFileAttributes Path path = Paths.get(\"C:\\\\Users\\\\jorgesys\\\\workspaceJava\\\\myfile.txt\");\n BasicFileAttributes attr;\n try {\n attr = Files.readAttributes(path, BasicFileAttributes.class);\n System.out.println(\"File creation time: \" + attr.creationTime());\n } catch (IOException e) {\n System.out.println(\"oops un error! \" + e.getMessage());\n }\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471/" ]
32,598
<p>If you have Subversion installed on your development machine and you don't work in a team, is there any reason why you should use the <em>svn</em> protocol instead of <em>file</em>?</p>
[ { "answer_id": 229642, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 0, "selected": false, "text": "file svn http Svn Http" }, { "answer_id": 44699067, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 0, "selected": false, "text": "file:// https:// svn:// file:// file:///C:\\Repositories\\MyRepo https://svn.example.com/MyRepo" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1670/" ]
32,607
<p>I'd like to rollback a change I made recently in TFS. In Subversion, this was pretty straightforward. However, it seems to be an incredible headache in TFS:</p> <h3>Option 1: Get Prior Version</h3> <ol> <li>Manually get prior version of each file</li> <li>Check out for edit</li> <li>Fail - the checkout (in VS2008) forces me to get the latest version</li> </ol> <h3>Option 2: Get TFS Power Tools</h3> <ol> <li>Download Team Foundation Power Tools</li> <li>Issue rollback command from cmd line</li> <li>Fail - it won't work if there are any other pending changes</li> </ol> <h3>Option 3: Manually Undo Changes</h3> <ol> <li>manually undo my changes, then commit a new changeset</li> </ol> <h3>Question</h3> <p>How do I rollback to a previous changeset in TFS?</p>
[ { "answer_id": 5355837, "author": "Kevin Lo", "author_id": 199043, "author_profile": "https://Stackoverflow.com/users/199043", "pm_score": 4, "selected": false, "text": "TF - Team Foundation Version Control Tool, Version 10.0.30319.1\nCopyright (c) Microsoft Corporation. All rights reserved.\n\nRolls back the changes in a single or a range of changesets:\ntf rollback /changeset:changesetfrom~changesetto [itemspec] [/recursive]\n [/lock:none|checkin|checkout] [/version:versionspec]\n [/keepmergehistory] [/noprompt] [/login:username,[password]]\n\ntf rollback /toversion:versionspec itemspec [/recursive]\n [/lock:none|checkin|checkout] [/version:versionspec]\n [/keepmergehistory] [/noprompt] [/login:username,[password]]\n" }, { "answer_id": 6940494, "author": "Ruslan", "author_id": 115466, "author_profile": "https://Stackoverflow.com/users/115466", "pm_score": 3, "selected": false, "text": "tf rollback /changeset:C12345\n 12345" }, { "answer_id": 7124417, "author": "Ed Blankenship", "author_id": 250290, "author_profile": "https://Stackoverflow.com/users/250290", "pm_score": 4, "selected": false, "text": "tf.exe rollback\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1338/" ]
32,621
<p>I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map.</p> <p>In normal view, VEMap.GetMapView().TopLeftLatLong and .BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses.</p> <p>In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1?</p>
[ { "answer_id": 33238, "author": "MartinHN", "author_id": 2972, "author_profile": "https://Stackoverflow.com/users/2972", "pm_score": 0, "selected": false, "text": "function GetInfo() \n{\n alert('The latitude,longitude at the center of the map is: '+map.GetCenter()); \n}\n" }, { "answer_id": 39986, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 2, "selected": false, "text": "var northWestLL = (new _xy1).Decode(map.GetMapView().TopLeftLatLong);\nvar southEastLL = (new _xy1).Decode(map.GetMapView().BottomRightLatLong);\n" }, { "answer_id": 67303, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 3, "selected": true, "text": "function GetCenterLatLong()\n {\n //Check if in Birdseye or Oblique Map Style\n if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid)\n {\n //IN Birdseye or Oblique Map Style\n\n\n //Get the BirdseyeScene being displayed\n var birdseyeScene = map.GetBirdseyeScene();\n\n\n //Get approximate center coordinate of the map\n var x = birdseyeScene.GetWidth() / 2;\n var y = birdseyeScene.GetHeight() / 2;\n\n // Get the Lat/Long \n var center = birdseyeScene.PixelToLatLong(new VEPixel(x,y), map.GetZoomLevel());\n\n // Convert the BirdseyeScene LatLong to a normal LatLong we can use\n return (new _xy1).Decode(center);\n }\n else\n {\n // NOT in Birdseye or Oblique Map Style\n return map.GetCenter();\n }\n } \n" }, { "answer_id": 860198, "author": "Jason", "author_id": 7391, "author_profile": "https://Stackoverflow.com/users/7391", "pm_score": 2, "selected": false, "text": "function getBirdseyeViewLatLong(vePixel)\n{\n var be = map.GetBirdseyeScene();\n\n var centrePixel = be.LatLongToPixel(map.GetCenter(), map.GetZoomLevel());\n\n var currentPixelWidth = be.GetWidth();\n var currentPixelHeight = be.GetHeight();\n\n var mapDiv = document.getElementById(\"map\");\n var mapDivPixelWidth = mapDiv.offsetWidth;\n var mapDivPixelHeight = mapDiv.offsetHeight;\n\n var xScreenPixel = centrePixel.x - (mapDivPixelWidth / 2) + vePixel.x;\n var yScreenPixel = centrePixel.y - (mapDivPixelHeight / 2) + vePixel.y;\n\n var position = be.PixelToLatLong(new VEPixel(xScreenPixel, yScreenPixel), map.GetZoomLevel())\n return (new _xy1).Decode(position);\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420/" ]
32,633
<p>I can easily set breakpoints in embedded JS functions, but I don't see any way of accessing external JS scripts via Firebug unless I happen to enter them during a debug session. Is there a way to do this without having to 'explore' my way into the script?</p> <p>@Jason: This is a good point, but in my case I do not have easy access to the script. I am specifically talking about the client scripts which are invoked by the ASP.Net Validators that I would like to debug. I can access them during a debug session through entering the function calls, but I could not find a way to access them directly.</p>
[ { "answer_id": 32711, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 5, "selected": false, "text": "debugger;" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
32,637
<p>I am consuming the Twitter API and want to convert all URLs to hyperlinks. </p> <p>What is the most effective way you've come up with to do this?</p> <p>from</p> <pre><code>string myString = "This is my tweet check it out http://tinyurl.com/blah"; </code></pre> <p>to</p> <pre><code>This is my tweet check it out &lt;a href="http://tinyurl.com/blah"&gt;http://tinyurl.com/&gt;blah&lt;/a&gt; </code></pre>
[ { "answer_id": 32648, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 6, "selected": true, "text": "Regex r = new Regex(@\"(https?://[^\\s]+)\");\nmyString = r.Replace(myString, \"<a href=\\\"$1\\\">$1</a>\");\n" }, { "answer_id": 32665, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": false, "text": "http://example.com/.\n I buy all my witty T-shirts from http://example.com/.\n" }, { "answer_id": 32693, "author": "RedWolves", "author_id": 648, "author_profile": "https://Stackoverflow.com/users/648", "pm_score": 3, "selected": false, "text": "String.prototype.linkify = function() {\n return this.replace(/[A-Za-z]+:\\/\\/[A-Za-z0-9-_]+\\.[A-Za-z0-9-_:%&\\?\\/.=]+/, function(m) {\n return m.link(m);\n });\n };\n" }, { "answer_id": 9139800, "author": "herry", "author_id": 932213, "author_profile": "https://Stackoverflow.com/users/932213", "pm_score": 1, "selected": false, "text": "private void ModifyString()\n{\n string input = \"find more on http://www.authorcode.com \";\n Regex regx = new Regex(@\"\\b((http|https|ftp|mailto)://)?(www.)+[\\w-]+(/[\\w- ./?%&=]*)?\");\n string result = regx.Replace(input, new MatchEvaluator(ReplaceURl));\n}\n\nstatic string ReplaceURl(Match m)\n{\n string x = m.ToString();\n x = \"< a href=\\\"\" + x + \"\\\">\" + x + \"</a>\";\n return x;\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2347826/" ]
32,640
<p>So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".</p> <p>I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.</p> <p>I'm using latest version of rhino mocks</p>
[ { "answer_id": 32672, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 7, "selected": true, "text": "var request = new Mock<HttpRequestBase>();\nrequest.Expect(r => r.HttpMethod).Returns(\"GET\");\nvar mockHttpContext = new Mock<HttpContextBase>();\nmockHttpContext.Expect(c => c.Request).Returns(request.Object);\nvar controllerContext = new ControllerContext(mockHttpContext.Object\n, new RouteData(), new Mock<ControllerBase>().Object);\n" }, { "answer_id": 33798, "author": "Dane O'Connor", "author_id": 1946, "author_profile": "https://Stackoverflow.com/users/1946", "pm_score": 4, "selected": false, "text": "// create a fake web context\nvar mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();\nvar mockRequest = MockRepository.GenerateMock<HttpRequestBase>();\nmockHttpContext.Stub(x => x.Request).Return(mockRequest);\n\n// tell the mock to return \"GET\" when HttpMethod is called\nmockRequest.Stub(x => x.HttpMethod).Return(\"GET\"); \n\nvar controller = new AccountController();\n\n// assign the fake context\nvar context = new ControllerContext(mockHttpContext, \n new RouteData(), \n controller);\ncontroller.ControllerContext = context;\n\n// act\n...\n" }, { "answer_id": 220113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public abstract class Specification <C> where C: Controller\n{\n protected C controller;\n\n HttpContextBase mockHttpContext;\n HttpRequestBase mockRequest;\n\n protected Exception ExceptionThrown { get; private set; }\n\n [SetUp]\n public void Setup()\n {\n mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();\n mockRequest = MockRepository.GenerateMock<HttpRequestBase>();\n\n mockHttpContext.Stub(x => x.Request).Return(mockRequest);\n mockRequest.Stub(x => x.HttpMethod).Return(\"GET\");\n\n\n EstablishContext();\n SetHttpContext();\n\n try\n {\n When();\n }\n catch (Exception exc)\n {\n ExceptionThrown = exc;\n }\n }\n\n protected void SetHttpContext()\n {\n var context = new ControllerContext(mockHttpContext, new RouteData(), controller);\n controller.ControllerContext = context;\n }\n\n protected T Mock<T>() where T: class\n {\n return MockRepository.GenerateMock<T>();\n }\n\n protected abstract void EstablishContext();\n protected abstract void When();\n\n [TearDown]\n public virtual void TearDown()\n {\n }\n} \n [TestFixture]\npublic class When_invoking_ManageUsersControllers_Update :Specification <ManageUsersController>\n{\n private IUserRepository userRepository;\n FormCollection form;\n\n ActionResult result;\n User retUser;\n\n protected override void EstablishContext()\n {\n userRepository = Mock<IUserRepository>();\n controller = new ManageUsersController(userRepository);\n\n retUser = new User();\n userRepository.Expect(x => x.GetById(5)).Return(retUser);\n userRepository.Expect(x => x.Update(retUser));\n\n form = new FormCollection();\n form[\"IdUser\"] = 5.ToString();\n form[\"Name\"] = 5.ToString();\n form[\"Surename\"] = 5.ToString();\n form[\"Login\"] = 5.ToString();\n form[\"Password\"] = 5.ToString();\n }\n\n protected override void When()\n {\n result = controller.Edit(5, form);\n }\n\n [Test]\n public void is_retrieved_before_update_original_user()\n {\n userRepository.AssertWasCalled(x => x.GetById(5));\n userRepository.AssertWasCalled(x => x.Update(retUser));\n }\n}\n" }, { "answer_id": 491798, "author": "RoyOsherove", "author_id": 18426, "author_profile": "https://Stackoverflow.com/users/18426", "pm_score": 3, "selected": false, "text": "Isolate.WhenCalled(()=>HttpContext.Request.HttpMethod).WillReturn(\"Get\");\n" }, { "answer_id": 1959077, "author": "Gabe Moothart", "author_id": 13356, "author_profile": "https://Stackoverflow.com/users/13356", "pm_score": 3, "selected": false, "text": "[HttpPost] [HttpGet] request.Headers request.Form request.QueryString X-HTTP-Method-Override var request = new Mock<HttpRequestBase>();\nrequest.Setup(r => r.HttpMethod).Returns(\"POST\");\nrequest.Setup(r => r.Headers).Returns(new NameValueCollection());\nrequest.Setup(r => r.Form).Returns(new NameValueCollection());\nrequest.Setup(r => r.QueryString).Returns(new NameValueCollection());\n\nvar mockHttpContext = new Mock<HttpContextBase>();\nmockHttpContext.Expect(c => c.Request).Returns(request.Object);\nvar controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);\n" }, { "answer_id": 15016922, "author": "Maksym Kozlenko", "author_id": 171847, "author_profile": "https://Stackoverflow.com/users/171847", "pm_score": 5, "selected": false, "text": "[TestClass]\npublic class MyControllerTest\n{\n protected Mock<HttpContextBase> HttpContextBaseMock;\n protected Mock<HttpRequestBase> HttpRequestMock;\n protected Mock<HttpResponseBase> HttpResponseMock;\n\n [TestInitialize]\n public void TestInitialize()\n {\n HttpContextBaseMock = new Mock<HttpContextBase>();\n HttpRequestMock = new Mock<HttpRequestBase>();\n HttpResponseMock = new Mock<HttpResponseBase>();\n HttpContextBaseMock.SetupGet(x => x.Request).Returns(HttpRequestMock.Object);\n HttpContextBaseMock.SetupGet(x => x.Response).Returns(HttpResponseMock.Object);\n }\n\n protected MyController SetupController()\n {\n var routes = new RouteCollection();\n var controller = new MyController();\n controller.ControllerContext = new ControllerContext(HttpContextBaseMock.Object, new RouteData(), controller);\n controller.Url = new UrlHelper(new RequestContext(HttpContextBaseMock.Object, new RouteData()), routes);\n return controller;\n }\n\n [TestMethod]\n public void IndexTest()\n {\n HttpRequestMock.Setup(x => x[\"x\"]).Returns(\"1\");\n HttpResponseMock.Setup(x => x.AddHeader(\"name\", \"value\"));\n\n var controller = SetupController();\n var result = controller.Index();\n Assert.AreEqual(\"1\", result.Content);\n\n HttpRequestMock.VerifyAll();\n HttpResponseMock.VerifyAll();\n }\n}\n\npublic class MyController : Controller\n{\n public ContentResult Index()\n {\n var x = Request[\"x\"];\n Response.AddHeader(\"name\", \"value\");\n return Content(x);\n }\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
32,649
<p>When making changes using <code>SubmitChanges()</code>, LINQ sometimes dies with a <code>ChangeConflictException</code> exception with the error message <code>Row not found or changed</code>, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row.</p> <p>Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?</p> <p>Additionally, does anybody know whether this exception occurs when <em>any</em> data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter?</p>
[ { "answer_id": 32705, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 6, "selected": true, "text": "try\n{\n db.SubmitChanges(ConflictMode.ContinueOnConflict);\n}\ncatch (ChangeConflictException e)\n{\n Console.WriteLine(\"Optimistic concurrency error.\");\n Console.WriteLine(e.Message);\n Console.ReadLine();\n foreach (ObjectChangeConflict occ in db.ChangeConflicts)\n {\n MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType());\n Customer entityInConflict = (Customer)occ.Object;\n Console.WriteLine(\"Table name: {0}\", metatable.TableName);\n Console.Write(\"Customer ID: \");\n Console.WriteLine(entityInConflict.CustomerID);\n foreach (MemberChangeConflict mcc in occ.MemberConflicts)\n {\n object currVal = mcc.CurrentValue;\n object origVal = mcc.OriginalValue;\n object databaseVal = mcc.DatabaseValue;\n MemberInfo mi = mcc.Member;\n Console.WriteLine(\"Member: {0}\", mi.Name);\n Console.WriteLine(\"current value: {0}\", currVal);\n Console.WriteLine(\"original value: {0}\", origVal);\n Console.WriteLine(\"database value: {0}\", databaseVal);\n }\n }\n}\n db.SubmitChanges(ConflictMode.ContinueOnConflict);\n" }, { "answer_id": 32708, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 4, "selected": false, "text": "public void SubmitKeepChanges()\n{\n try\n {\n this.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n catch (ChangeConflictException e)\n {\n foreach (ObjectChangeConflict occ in this.ChangeConflicts)\n {\n //Keep current values that have changed, \n//updates other values with database values\n\n occ.Resolve(RefreshMode.KeepChanges);\n }\n }\n}\n\npublic void SubmitOverwrite()\n{\n try\n {\n this.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n catch (ChangeConflictException e)\n {\n foreach (ObjectChangeConflict occ in this.ChangeConflicts)\n {\n // All database values overwrite current values with \n//values from database\n\n occ.Resolve(RefreshMode.OverwriteCurrentValues);\n }\n }\n}\n\npublic void SubmitKeepCurrent()\n{\n try\n {\n this.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n catch (ChangeConflictException e)\n {\n foreach (ObjectChangeConflict occ in this.ChangeConflicts)\n {\n //Swap the original values with the values retrieved from the database. No current value is modified\n occ.Resolve(RefreshMode.KeepCurrentValues);\n }\n }\n}\n" }, { "answer_id": 33482, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": -1, "selected": false, "text": "db.SubmitChanges(ConflictMode.ContinueOnConflict)\n" }, { "answer_id": 12487195, "author": "Mark", "author_id": 9976, "author_profile": "https://Stackoverflow.com/users/9976", "pm_score": 2, "selected": false, "text": " /// <summary>\n /// Submits changes and, if there are any conflicts, the database changes are auto-merged for \n /// members that client has not modified (client wins, but database changes are preserved if possible)\n /// </summary>\n public void SubmitKeepChanges()\n {\n this.Submit(RefreshMode.KeepChanges);\n }\n\n /// <summary>\n /// Submits changes and, if there are any conflicts, simply overwrites what is in the database (client wins).\n /// </summary>\n public void SubmitOverwriteDatabase()\n {\n this.Submit(RefreshMode.KeepCurrentValues);\n }\n\n /// <summary>\n /// Submits changes and, if there are any conflicts, all database values overwrite\n /// current values (client loses).\n /// </summary>\n public void SubmitUseDatabase()\n {\n this.Submit(RefreshMode.OverwriteCurrentValues);\n }\n\n /// <summary>\n /// Submits the changes using the specified refresh mode.\n /// </summary>\n /// <param name=\"refreshMode\">The refresh mode.</param>\n private void Submit(RefreshMode refreshMode)\n {\n bool moreToSubmit = true;\n do\n {\n try\n {\n this.SubmitChanges(ConflictMode.ContinueOnConflict);\n moreToSubmit = false;\n }\n catch (ChangeConflictException)\n {\n foreach (ObjectChangeConflict occ in this.ChangeConflicts)\n {\n occ.Resolve(refreshMode);\n }\n }\n }\n while (moreToSubmit);\n\n }\n" }, { "answer_id": 54920592, "author": "Herman Van Der Blom", "author_id": 2111313, "author_profile": "https://Stackoverflow.com/users/2111313", "pm_score": 0, "selected": false, "text": "refresh refresh true /// <remarks>\n /// linq has optimistic concurrency, so objects can be changed by other users, while\n /// submitted keep database changes but make sure users changes are also submitted\n /// and refreshed with the changes already made by other users.\n /// </remarks>\n /// <returns>return if a refresh is needed.</returns>\n public bool SubmitKeepChanges()\n {\n // try to submit changes to the database.\n bool refresh = false;\n try\n {\n base.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n\n /* \n * assume a \"row not found or changed\" exception, if thats the case:\n * - keep the database changes already made by other users and make sure\n * - this users changes are also written to the database\n */\n catch (ChangeConflictException)\n {\n // show where the conflicts are in debug mode\n ShowConflicts();\n\n // get database values and combine with user changes \n base.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);\n\n // submit those combined changes again to the database.\n base.SubmitChanges();\n\n // a refresh is needed\n refresh = true;\n }\n\n // return if a refresh is needed.\n return refresh;\n }\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ]
32,664
<p>Can anyone tell me if there is a way with generics to limit a generic type argument <code>T</code> to only:</p> <ul> <li><code>Int16</code></li> <li><code>Int32</code></li> <li><code>Int64</code></li> <li><code>UInt16</code></li> <li><code>UInt32</code></li> <li><code>UInt64</code></li> </ul> <p>I'm aware of the <code>where</code> keyword, but can't find an interface for <strong>only</strong> these types,</p> <p>Something like:</p> <pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : INumeric </code></pre>
[ { "answer_id": 32687, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 7, "selected": false, "text": "static bool GenericFunction<T>(T value) \n where T : operators( +, -, /, * )\n static bool GenericFunction<T>(T value) \n where T : Add, Subtract\n struct class new() INullable<T>" }, { "answer_id": 32690, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 4, "selected": false, "text": "static bool IntegerFunction<T>(T value) where T: struct\n static bool IntegerFunction<T>(T value) where T: struct, IComparable\n, IFormattable, IConvertible, IComparable<T>, IEquatable<T>\n" }, { "answer_id": 32727, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 4, "selected": false, "text": "static bool IntegerFunction<T>(T value) where T : struct {\n if (typeof(T) != typeof(Int16) &&\n typeof(T) != typeof(Int32) &&\n typeof(T) != typeof(Int64) &&\n typeof(T) != typeof(UInt16) &&\n typeof(T) != typeof(UInt32) &&\n typeof(T) != typeof(UInt64)) {\n throw new ArgumentException(\n string.Format(\"Type '{0}' is not valid.\", typeof(T).ToString()));\n }\n\n // Rest of code...\n}\n" }, { "answer_id": 33383, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 1, "selected": false, "text": "static bool IntegerFunction(Int64 value) { }\n static bool IntegerFunction(Int64 value) { }\n...\nstatic bool IntegerFunction(Int16 value) { }\n" }, { "answer_id": 34186, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": false, "text": "INumber<TSelf> INumeric System.Numerics IBinaryInteger<TSelf> IntegerFunction static bool IntegerFunction<T>(T value) where T : IBinaryInteger<T> {\n return value > T.Zero;\n}\n Console.WriteLine(IntegerFunction(5)); // True\nConsole.WriteLine(IntegerFunction((sbyte)-5)); // False\nConsole.WriteLine(IntegerFunction((ulong)5)); // True\n Matrix<T> Matrix T T int double float Matrix Calculator<T> Calculator<T> multiply Matrix Calculator<T> T int double var mat = new Matrix<int>(w, h);\n Calculator DFP var mat = new Matrix<DFP>(DfpCalculator.Instance, w, h);\n DfpCalculator : ICalculator<DFP>" }, { "answer_id": 1268443, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "T Add<T>(T x, T y) DateTime + TimeSpan dynamic dynamic x = ..., y = ...\ndynamic result = x + y; // does what you expect\n" }, { "answer_id": 2065410, "author": "Marc Roussel", "author_id": 250846, "author_profile": "https://Stackoverflow.com/users/250846", "pm_score": 1, "selected": false, "text": "/// <summary>\n/// Generic object copy of the same type\n/// </summary>\n/// <typeparam name=\"T\">The type of object to copy</typeparam>\n/// <param name=\"ObjectSource\">The source object to copy</param>\npublic T CopyObject<T>(T ObjectSource)\n{\n T NewObject = System.Activator.CreateInstance<T>();\n\n foreach (PropertyInfo p in ObjectSource.GetType().GetProperties())\n NewObject.GetType().GetProperty(p.Name).SetValue(NewObject, p.GetValue(ObjectSource, null), null);\n\n return NewObject;\n}\n" }, { "answer_id": 4188702, "author": "pomeroy", "author_id": 141635, "author_profile": "https://Stackoverflow.com/users/141635", "pm_score": 1, "selected": false, "text": "public struct Foo<T>\n{\n public T Value{ get; private set; }\n\n public static Foo<T> operator +(Foo<T> LHS, Foo<T> RHS)\n {\n return new Foo<T> { Value = LHS.Value + RHS.Value; };\n }\n}\n public struct Foo<T>\n{\n public T Value { get; private set; }\n\n public static Foo<T> operator +(Foo<T> LHS, Foo<T> RHS)\n {\n return new Foo<T> { Value = LHS.Value + (dynamic)RHS.Value };\n }\n}\n dynamic" }, { "answer_id": 4834066, "author": "Sergey Shandar", "author_id": 374845, "author_profile": "https://Stackoverflow.com/users/374845", "pm_score": 6, "selected": false, "text": "interface INumericPolicy<T>\n{\n T Zero();\n T Add(T a, T b);\n // add more functions here, such as multiplication etc.\n}\n\nstruct NumericPolicies:\n INumericPolicy<int>,\n INumericPolicy<long>\n // add more INumericPolicy<> for different numeric types.\n{\n int INumericPolicy<int>.Zero() { return 0; }\n long INumericPolicy<long>.Zero() { return 0; }\n int INumericPolicy<int>.Add(int a, int b) { return a + b; }\n long INumericPolicy<long>.Add(long a, long b) { return a + b; }\n // implement all functions from INumericPolicy<> interfaces.\n\n public static NumericPolicies Instance = new NumericPolicies();\n}\n static class Algorithms\n{\n public static T Sum<P, T>(this P p, params T[] a)\n where P: INumericPolicy<T>\n {\n var r = p.Zero();\n foreach(var i in a)\n {\n r = p.Add(r, i);\n }\n return r;\n }\n\n}\n int i = NumericPolicies.Instance.Sum(1, 2, 3, 4, 5);\nlong l = NumericPolicies.Instance.Sum(1L, 2, 3, 4, 5);\nNumericPolicies.Instance.Sum(\"www\", \"\") // compile-time error.\n" }, { "answer_id": 16402309, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "ISignedWholeNumber Int16 Int32 ISignedWholeNumber Int64Converter<T> bool Available {get;}; Int64 GetInt64(T value) T FromInt64(Int64 value) bool TryStoreInt64(Int64 value, ref T dest) T Int64 ToString()" }, { "answer_id": 16481028, "author": "Martin Mulder", "author_id": 2304116, "author_profile": "https://Stackoverflow.com/users/2304116", "pm_score": 2, "selected": false, "text": "public T DifficultCalculation<T>(T a, T b)\n{\n T result = a * b + a; // <== WILL NOT COMPILE!\n return result;\n}\nConsole.WriteLine(DifficultCalculation(2, 3)); // Should result in 8.\n public T DifficultCalculation<T>(Number<T> a, Number<T> b)\n{\n Number<T> result = a * b + a;\n return (T)result;\n}\nConsole.WriteLine(DifficultCalculation(2, 3)); // Results in 8.\n" }, { "answer_id": 22425077, "author": "Jeroen Vannevel", "author_id": 1864167, "author_profile": "https://Stackoverflow.com/users/1864167", "pm_score": 7, "selected": false, "text": "<#@ template language=\"C#\" #>\n<#@ output extension=\".cs\" #>\n<#@ assembly name=\"System.Core\" #>\n\n<# Type[] types = new[] {\n typeof(Int16), typeof(Int32), typeof(Int64),\n typeof(UInt16), typeof(UInt32), typeof(UInt64)\n };\n#>\n\nusing System;\npublic static class MaxMath {\n <# foreach (var type in types) { \n #>\n public static <#= type.Name #> Max (<#= type.Name #> val1, <#= type.Name #> val2) {\n return val1 > val2 ? val1 : val2;\n }\n <#\n } #>\n}\n using System;\npublic static class MaxMath {\n public static Int16 Max (Int16 val1, Int16 val2) {\n return val1 > val2 ? val1 : val2;\n }\n public static Int32 Max (Int32 val1, Int32 val2) {\n return val1 > val2 ? val1 : val2;\n }\n public static Int64 Max (Int64 val1, Int64 val2) {\n return val1 > val2 ? val1 : val2;\n }\n public static UInt16 Max (UInt16 val1, UInt16 val2) {\n return val1 > val2 ? val1 : val2;\n }\n public static UInt32 Max (UInt32 val1, UInt32 val2) {\n return val1 > val2 ? val1 : val2;\n }\n public static UInt64 Max (UInt64 val1, UInt64 val2) {\n return val1 > val2 ? val1 : val2;\n }\n}\n main namespace TTTTTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n long val1 = 5L;\n long val2 = 10L;\n Console.WriteLine(MaxMath.Max(val1, val2));\n Console.Read();\n }\n }\n}\n partial <#@ import namespace=\"TheNameSpaceYouWillUse\" #>\n<#@ assembly name=\"$(TargetPath)\" #>\n" }, { "answer_id": 27627106, "author": "Rob Deary", "author_id": 1977538, "author_profile": "https://Stackoverflow.com/users/1977538", "pm_score": 3, "selected": false, "text": " class Something<TCell>\n {\n internal static TCell Sum(TCell first, TCell second)\n {\n if (typeof(TCell) == typeof(int))\n return (TCell)((object)(((int)((object)first)) + ((int)((object)second))));\n\n if (typeof(TCell) == typeof(double))\n return (TCell)((object)(((double)((object)first)) + ((double)((object)second))));\n\n return second;\n }\n }\n internal static int Sum(int first, int second)\n {\n return first + second;\n }\n" }, { "answer_id": 45775531, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "using System;\npublic class InvalidArgumentException : Exception\n{\n public InvalidArgumentException(string message) : base(message) {}\n}\npublic class InvalidArgumentTypeException : InvalidArgumentException\n{\n public InvalidArgumentTypeException(string message) : base(message) {}\n}\npublic class ArgumentTypeNotIntegerException : InvalidArgumentTypeException\n{\n public ArgumentTypeNotIntegerException(string message) : base(message) {}\n}\npublic static class Program\n{\n private static bool IntegerFunction(dynamic n)\n {\n if (n.GetType() != typeof(Int16) &&\n n.GetType() != typeof(Int32) &&\n n.GetType() != typeof(Int64) &&\n n.GetType() != typeof(UInt16) &&\n n.GetType() != typeof(UInt32) &&\n n.GetType() != typeof(UInt64))\n throw new ArgumentTypeNotIntegerException(\"argument type is not integer type\");\n //code that implements IntegerFunction goes here\n }\n private static void Main()\n {\n Console.WriteLine(\"{0}\",IntegerFunction(0)); //Compiles, no run time error and first line of output buffer is either \"True\" or \"False\" depends on the code that implements \"Program.IntegerFunction\" static method.\n Console.WriteLine(\"{0}\",IntegerFunction(\"string\")); //Also compiles but it is run time error and exception of type \"ArgumentTypeNotIntegerException\" is thrown here.\n Console.WriteLine(\"This is the last Console.WriteLine output\"); //Never reached and executed due the run time error and the exception thrown on the second line of Program.Main static method.\n }\n using System;\npublic struct Integer\n{\n private dynamic value;\n private Integer(dynamic n) { this.value = n; }\n public Integer(Int16 n) { this.value = n; }\n public Integer(Int32 n) { this.value = n; }\n public Integer(Int64 n) { this.value = n; }\n public Integer(UInt16 n) { this.value = n; }\n public Integer(UInt32 n) { this.value = n; }\n public Integer(UInt64 n) { this.value = n; }\n public Integer(Integer n) { this.value = n.value; }\n public static implicit operator Int16(Integer n) { return n.value; }\n public static implicit operator Int32(Integer n) { return n.value; }\n public static implicit operator Int64(Integer n) { return n.value; }\n public static implicit operator UInt16(Integer n) { return n.value; }\n public static implicit operator UInt32(Integer n) { return n.value; }\n public static implicit operator UInt64(Integer n) { return n.value; }\n public static Integer operator +(Integer x, Int16 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, Int32 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, Int64 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, UInt16 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, UInt32 y) { return new Integer(x.value + y); }\n public static Integer operator +(Integer x, UInt64 y) { return new Integer(x.value + y); }\n public static Integer operator -(Integer x, Int16 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, Int32 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, Int64 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, UInt16 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, UInt32 y) { return new Integer(x.value - y); }\n public static Integer operator -(Integer x, UInt64 y) { return new Integer(x.value - y); }\n public static Integer operator *(Integer x, Int16 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, Int32 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, Int64 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, UInt16 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, UInt32 y) { return new Integer(x.value * y); }\n public static Integer operator *(Integer x, UInt64 y) { return new Integer(x.value * y); }\n public static Integer operator /(Integer x, Int16 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, Int32 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, Int64 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, UInt16 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, UInt32 y) { return new Integer(x.value / y); }\n public static Integer operator /(Integer x, UInt64 y) { return new Integer(x.value / y); }\n public static Integer operator %(Integer x, Int16 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, Int32 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, Int64 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, UInt16 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, UInt32 y) { return new Integer(x.value % y); }\n public static Integer operator %(Integer x, UInt64 y) { return new Integer(x.value % y); }\n public static Integer operator +(Integer x, Integer y) { return new Integer(x.value + y.value); }\n public static Integer operator -(Integer x, Integer y) { return new Integer(x.value - y.value); }\n public static Integer operator *(Integer x, Integer y) { return new Integer(x.value * y.value); }\n public static Integer operator /(Integer x, Integer y) { return new Integer(x.value / y.value); }\n public static Integer operator %(Integer x, Integer y) { return new Integer(x.value % y.value); }\n public static bool operator ==(Integer x, Int16 y) { return x.value == y; }\n public static bool operator !=(Integer x, Int16 y) { return x.value != y; }\n public static bool operator ==(Integer x, Int32 y) { return x.value == y; }\n public static bool operator !=(Integer x, Int32 y) { return x.value != y; }\n public static bool operator ==(Integer x, Int64 y) { return x.value == y; }\n public static bool operator !=(Integer x, Int64 y) { return x.value != y; }\n public static bool operator ==(Integer x, UInt16 y) { return x.value == y; }\n public static bool operator !=(Integer x, UInt16 y) { return x.value != y; }\n public static bool operator ==(Integer x, UInt32 y) { return x.value == y; }\n public static bool operator !=(Integer x, UInt32 y) { return x.value != y; }\n public static bool operator ==(Integer x, UInt64 y) { return x.value == y; }\n public static bool operator !=(Integer x, UInt64 y) { return x.value != y; }\n public static bool operator ==(Integer x, Integer y) { return x.value == y.value; }\n public static bool operator !=(Integer x, Integer y) { return x.value != y.value; }\n public override bool Equals(object obj) { return this == (Integer)obj; }\n public override int GetHashCode() { return this.value.GetHashCode(); }\n public override string ToString() { return this.value.ToString(); }\n public static bool operator >(Integer x, Int16 y) { return x.value > y; }\n public static bool operator <(Integer x, Int16 y) { return x.value < y; }\n public static bool operator >(Integer x, Int32 y) { return x.value > y; }\n public static bool operator <(Integer x, Int32 y) { return x.value < y; }\n public static bool operator >(Integer x, Int64 y) { return x.value > y; }\n public static bool operator <(Integer x, Int64 y) { return x.value < y; }\n public static bool operator >(Integer x, UInt16 y) { return x.value > y; }\n public static bool operator <(Integer x, UInt16 y) { return x.value < y; }\n public static bool operator >(Integer x, UInt32 y) { return x.value > y; }\n public static bool operator <(Integer x, UInt32 y) { return x.value < y; }\n public static bool operator >(Integer x, UInt64 y) { return x.value > y; }\n public static bool operator <(Integer x, UInt64 y) { return x.value < y; }\n public static bool operator >(Integer x, Integer y) { return x.value > y.value; }\n public static bool operator <(Integer x, Integer y) { return x.value < y.value; }\n public static bool operator >=(Integer x, Int16 y) { return x.value >= y; }\n public static bool operator <=(Integer x, Int16 y) { return x.value <= y; }\n public static bool operator >=(Integer x, Int32 y) { return x.value >= y; }\n public static bool operator <=(Integer x, Int32 y) { return x.value <= y; }\n public static bool operator >=(Integer x, Int64 y) { return x.value >= y; }\n public static bool operator <=(Integer x, Int64 y) { return x.value <= y; }\n public static bool operator >=(Integer x, UInt16 y) { return x.value >= y; }\n public static bool operator <=(Integer x, UInt16 y) { return x.value <= y; }\n public static bool operator >=(Integer x, UInt32 y) { return x.value >= y; }\n public static bool operator <=(Integer x, UInt32 y) { return x.value <= y; }\n public static bool operator >=(Integer x, UInt64 y) { return x.value >= y; }\n public static bool operator <=(Integer x, UInt64 y) { return x.value <= y; }\n public static bool operator >=(Integer x, Integer y) { return x.value >= y.value; }\n public static bool operator <=(Integer x, Integer y) { return x.value <= y.value; }\n public static Integer operator +(Int16 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(Int32 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(Int64 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(UInt16 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(UInt32 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator +(UInt64 x, Integer y) { return new Integer(x + y.value); }\n public static Integer operator -(Int16 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(Int32 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(Int64 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(UInt16 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(UInt32 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator -(UInt64 x, Integer y) { return new Integer(x - y.value); }\n public static Integer operator *(Int16 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(Int32 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(Int64 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(UInt16 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(UInt32 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator *(UInt64 x, Integer y) { return new Integer(x * y.value); }\n public static Integer operator /(Int16 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(Int32 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(Int64 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(UInt16 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(UInt32 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator /(UInt64 x, Integer y) { return new Integer(x / y.value); }\n public static Integer operator %(Int16 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(Int32 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(Int64 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(UInt16 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(UInt32 x, Integer y) { return new Integer(x % y.value); }\n public static Integer operator %(UInt64 x, Integer y) { return new Integer(x % y.value); }\n public static bool operator ==(Int16 x, Integer y) { return x == y.value; }\n public static bool operator !=(Int16 x, Integer y) { return x != y.value; }\n public static bool operator ==(Int32 x, Integer y) { return x == y.value; }\n public static bool operator !=(Int32 x, Integer y) { return x != y.value; }\n public static bool operator ==(Int64 x, Integer y) { return x == y.value; }\n public static bool operator !=(Int64 x, Integer y) { return x != y.value; }\n public static bool operator ==(UInt16 x, Integer y) { return x == y.value; }\n public static bool operator !=(UInt16 x, Integer y) { return x != y.value; }\n public static bool operator ==(UInt32 x, Integer y) { return x == y.value; }\n public static bool operator !=(UInt32 x, Integer y) { return x != y.value; }\n public static bool operator ==(UInt64 x, Integer y) { return x == y.value; }\n public static bool operator !=(UInt64 x, Integer y) { return x != y.value; }\n public static bool operator >(Int16 x, Integer y) { return x > y.value; }\n public static bool operator <(Int16 x, Integer y) { return x < y.value; }\n public static bool operator >(Int32 x, Integer y) { return x > y.value; }\n public static bool operator <(Int32 x, Integer y) { return x < y.value; }\n public static bool operator >(Int64 x, Integer y) { return x > y.value; }\n public static bool operator <(Int64 x, Integer y) { return x < y.value; }\n public static bool operator >(UInt16 x, Integer y) { return x > y.value; }\n public static bool operator <(UInt16 x, Integer y) { return x < y.value; }\n public static bool operator >(UInt32 x, Integer y) { return x > y.value; }\n public static bool operator <(UInt32 x, Integer y) { return x < y.value; }\n public static bool operator >(UInt64 x, Integer y) { return x > y.value; }\n public static bool operator <(UInt64 x, Integer y) { return x < y.value; }\n public static bool operator >=(Int16 x, Integer y) { return x >= y.value; }\n public static bool operator <=(Int16 x, Integer y) { return x <= y.value; }\n public static bool operator >=(Int32 x, Integer y) { return x >= y.value; }\n public static bool operator <=(Int32 x, Integer y) { return x <= y.value; }\n public static bool operator >=(Int64 x, Integer y) { return x >= y.value; }\n public static bool operator <=(Int64 x, Integer y) { return x <= y.value; }\n public static bool operator >=(UInt16 x, Integer y) { return x >= y.value; }\n public static bool operator <=(UInt16 x, Integer y) { return x <= y.value; }\n public static bool operator >=(UInt32 x, Integer y) { return x >= y.value; }\n public static bool operator <=(UInt32 x, Integer y) { return x <= y.value; }\n public static bool operator >=(UInt64 x, Integer y) { return x >= y.value; }\n public static bool operator <=(UInt64 x, Integer y) { return x <= y.value; }\n}\npublic static class Program\n{\n private static bool IntegerFunction(Integer n)\n {\n //code that implements IntegerFunction goes here\n //note that there is NO code that checks the type of n in rum time, because it is NOT needed anymore \n }\n private static void Main()\n {\n Console.WriteLine(\"{0}\",IntegerFunction(0)); //compile error: there is no overloaded METHOD for objects of type \"int\" and no implicit conversion from any object, including \"int\", to \"Integer\" is known.\n Console.WriteLine(\"{0}\",IntegerFunction(new Integer(0))); //both compiles and no run time error\n Console.WriteLine(\"{0}\",IntegerFunction(\"string\")); //compile error: there is no overloaded METHOD for objects of type \"string\" and no implicit conversion from any object, including \"string\", to \"Integer\" is known.\n Console.WriteLine(\"{0}\",IntegerFunction(new Integer(\"string\"))); //compile error: there is no overloaded CONSTRUCTOR for objects of type \"string\"\n }\n}\n" }, { "answer_id": 53663980, "author": "user276648", "author_id": 276648, "author_profile": "https://Stackoverflow.com/users/276648", "pm_score": 0, "selected": false, "text": "using T ComputeSomething<T>(T value1, T value2) where T : INumeric { ... }\n using MyNumType = System.Double;\nT ComputeSomething<MyNumType>(MyNumType value1, MyNumType value2) { ... }\n double int ComputeSomething double int double int double double int" }, { "answer_id": 53703357, "author": "DrGriff", "author_id": 584714, "author_profile": "https://Stackoverflow.com/users/584714", "pm_score": 2, "selected": false, "text": "public static string DoSomething(this int input, ...) => DoSomethingHelper(input, ...);\npublic static string DoSomething(this decimal input, ...) => DoSomethingHelper(input, ...);\npublic static string DoSomething(this double input, ...) => DoSomethingHelper(input, ...);\npublic static string DoSomething(this string input, ...) => DoSomethingHelper(input, ...);\n\nprivate static string DoSomethingHelper<T>(this T input, ....)\n{\n // complex logic\n}\n" }, { "answer_id": 59991325, "author": "TylerBrinkley", "author_id": 8137269, "author_profile": "https://Stackoverflow.com/users/8137269", "pm_score": 2, "selected": false, "text": "sbyte byte short ushort int uint long ulong float double decimal BigInteger public static T Sum(T[] items)\n{\n T sum = Number.Zero<T>();\n foreach (T item in items)\n {\n sum = Number.Add(sum, item);\n }\n return sum;\n}\n public static T SumAlt(T[] items)\n{\n // implicit conversion to Number<T>\n Number<T> sum = Number.Zero<T>();\n foreach (T item in items)\n {\n // operator support\n sum += item;\n }\n // implicit conversion to T\n return sum;\n}\n" }, { "answer_id": 60022011, "author": "Vlad", "author_id": 1544015, "author_profile": "https://Stackoverflow.com/users/1544015", "pm_score": 5, "selected": false, "text": "class SomeGeneric<T> where T : unmanaged\n{\n//...\n}\n class SomeGeneric<T> where T : unmanaged, IComparable, IEquatable<T>\n {\n //...\n }\n" }, { "answer_id": 62211277, "author": "Arman Ebrahimpour", "author_id": 9212040, "author_profile": "https://Stackoverflow.com/users/9212040", "pm_score": 4, "selected": false, "text": "Discriminated Unions C# 10 static bool IntegerFunction<T>(T value) where T : Int16 | Int32 | Int64 | ...\n" }, { "answer_id": 68753665, "author": "Dan", "author_id": 4601149, "author_profile": "https://Stackoverflow.com/users/4601149", "pm_score": 5, "selected": true, "text": "INumber IFloatingPoint using System.Numerics;\n\nConsole.WriteLine(Sum(1, 2, 3, 4, 5));\nConsole.WriteLine(Sum(10.541, 2.645));\nConsole.WriteLine(Sum(1.55f, 5, 9.41f, 7));\n\nstatic T Sum<T>(params T[] numbers) where T : INumber<T>\n{\n T result = T.Zero;\n\n foreach (T item in numbers)\n {\n result += item;\n }\n\n return result;\n}\n INumber System.Numerics IAdditionOperators IComparisonOperators" }, { "answer_id": 69288660, "author": "lonix", "author_id": 9971404, "author_profile": "https://Stackoverflow.com/users/9971404", "pm_score": 0, "selected": false, "text": "IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable DateTime public static bool IsNumeric<T>(this T value) where T : struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable =>\n typeof(T) != typeof(DateTime);\n public struct Foo : IComparable, IComparable<Foo>, IConvertible, IEquatable<Foo>, IFormattable { /* ... */ }\n public static bool IsNumeric(this Type type) =>\n type == typeof(sbyte) || type == typeof(byte) ||\n type == typeof(short) || type == typeof(ushort) ||\n type == typeof(int) || type == typeof(uint) ||\n type == typeof(long) || type == typeof(ulong) ||\n type == typeof(float) ||\n type == typeof(double) ||\n type == typeof(decimal);\n" }, { "answer_id": 70046713, "author": "asaf92", "author_id": 6104191, "author_profile": "https://Stackoverflow.com/users/6104191", "pm_score": 2, "selected": false, "text": "static T Add<T>(T left, T right)\n where T : INumber<T>\n{\n return left + right;\n}\n INumber IAdditionOperators + + /// <summary>Defines a mechanism for computing the sum of two values.</summary>\n/// <typeparam name=\"TSelf\">The type that implements this interface.</typeparam>\n/// <typeparam name=\"TOther\">The type that will be added to <typeparamref name=\"TSelf\" />.</typeparam>\n/// <typeparam name=\"TResult\">The type that contains the sum of <typeparamref name=\"TSelf\" /> and <typeparamref name=\"TOther\" />.</typeparam>\n[RequiresPreviewFeatures(Number.PreviewFeatureMessage, Url = Number.PreviewFeatureUrl)]\npublic interface IAdditionOperators<TSelf, TOther, TResult>\n where TSelf : IAdditionOperators<TSelf, TOther, TResult>\n{\n /// <summary>Adds two values together to compute their sum.</summary>\n /// <param name=\"left\">The value to which <paramref name=\"right\" /> is added.</param>\n /// <param name=\"right\">The value which is added to <paramref name=\"left\" />.</param>\n /// <returns>The sum of <paramref name=\"left\" /> and <paramref name=\"right\" />.</returns>\n static abstract TResult operator +(TSelf left, TOther right);\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ]
32,668
<p>I don't edit CSS very often, and almost every time I need to go and google the <a href="http://www.w3.org/TR/REC-CSS2/box.html" rel="noreferrer">CSS box model</a> to check whether <code>padding</code> is inside the <code>border</code> and <code>margin</code> outside, or vice versa. (Just checked again and <code>padding</code> is inside).</p> <p>Does anyone have a good way of remembering this? A little mnemonic, a good explanation as to why the names are that way round ...</p>
[ { "answer_id": 32696, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "body body body" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3189/" ]
32,694
<p>I'm trying to use <strong>NIS</strong> for authentication on a st of machines. I had to change one of the user ID numbers for a user account on the NIS server (I changed the userid for <code>username</code> from 500 to 509 to avoid a conflict with a local user account with id 500 on the clients). The problem is that it has not updated properly on the client. </p> <p>In particular, if I do <code>ypcat passwd | grep username</code>, I get the up-to-date info:</p> <pre><code>username:*hidden*:509:509:User Name:/home/username:/bin/bash </code></pre> <p>But if I do, <code>ypmatch username passwd</code>, it says:</p> <pre><code>username:*hidden*:500:500:User Name:/home/username:/bin/bash </code></pre> <p>This means that when the user logs onto one of the clients, it has the wrong userid, which causes all sorts of problems. I've done <code>"cd /var/yp; make"</code> on the server, and <code>"service ypbind restart"</code> on the client, but that hasn't fixed the problem. Does anybody know what would be causing this and how I can somehow force a refresh on the client? (I'm running Fedora 8 on both client and server).</p>
[ { "answer_id": 32770, "author": "Lorin Hochstein", "author_id": 742, "author_profile": "https://Stackoverflow.com/users/742", "pm_score": 1, "selected": false, "text": "\"service ypserv restart\"" }, { "answer_id": 12900738, "author": "Bradley Kreider", "author_id": 268907, "author_profile": "https://Stackoverflow.com/users/268907", "pm_score": 3, "selected": false, "text": "ypserv[]: refused connect from 127.0.0.1 to procedure ypproc_clear (,;0)\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
32,709
<p>Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing <code>Func&lt;T, bool&gt;</code> vs. <code>Predicate&lt;T&gt;</code> </p> <p>I would imagine there is no difference as both take a generic parameter and return bool?</p>
[ { "answer_id": 36872, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 4, "selected": false, "text": "class A {\n static void Main() {\n Func<int, bool> func = i => i > 100;\n Predicate<int> pred = i => i > 100;\n\n Test<int>(pred, 150);\n Test<int>(func, 150); // Error\n }\n\n static void Test<T>(Predicate<T> pred, T val) {\n Console.WriteLine(pred(val) ? \"true\" : \"false\");\n }\n}\n" }, { "answer_id": 1735428, "author": "xyz", "author_id": 82, "author_profile": "https://Stackoverflow.com/users/82", "pm_score": 2, "selected": false, "text": "Func Predicate" }, { "answer_id": 15046050, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 0, "selected": false, "text": "namespace N\n{\n // Represents a method that takes in a string and checks to see\n // if this string has some predicate (i.e. meets some criteria)\n // or not.\n internal delegate bool StringPredicate(string stringToTest);\n\n // Represents a method that takes in a string representing a\n // yes/no or true/false value and returns the boolean value which\n // corresponds to this string\n internal delegate bool BooleanParser(string stringToConvert);\n}\n Predicate<string> Func<string, bool> class Car { string Color; decimal Price; } class Person { string FullName; decimal BodyMassIndex; } string decimal" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993/" ]
32,715
<p>When using the app_offline.htm feature of ASP.NET, it only allows html, but no images. Is there a way to get images to display <strong>without having to point them to a different url on another site</strong>?</p>
[ { "answer_id": 32866, "author": "Ryan Sampson", "author_id": 1375, "author_profile": "https://Stackoverflow.com/users/1375", "pm_score": 2, "selected": false, "text": " public void Application_Start(object sender, EventArgs e)\n {\n Application[\"OfflineMessage\"] = \"This website is offline.\";\n Application[\"IsOffline\"] = false;\n }\n\n\n\n public void Application_OnBeginRequest(object sender, EventArgs e)\n {\n bool offline = Convert.ToBoolean(Application[\"IsOffline\"]);\n\n if (offline) \n {\n\n // TODO: allow access to DisplayOfflineMessage.aspx and ManageOfflineStatus.aspx\n\n // redirct requests to all other pages\n Response.Redirect(\"~/DisplayOfflineMessage.aspx\");\n }\n }\n" }, { "answer_id": 72683838, "author": "Mario Levrero", "author_id": 2686163, "author_profile": "https://Stackoverflow.com/users/2686163", "pm_score": 0, "selected": false, "text": " <html>\n <body>\n <h1>\n Web under maintenance with image in base64\n </h1>\n <img src=\"data:image/png;base64,iVBORw0K...=\">\n </body>\n </html>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/820/" ]
32,717
<p>I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example?</p>
[ { "answer_id": 188237, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 3, "selected": true, "text": "Target Property ItemGroup <Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <PropertyGroup>\n <ProjectName>TheProject</ProjectName>\n <ProjectDepthPath>..\\..\\</ProjectDepthPath>\n <ProjectsLibFolder>..\\..\\lib\\</ProjectsLibFolder>\n\n <LibFolder>$(ProjectsLibFolder)$(ProjectName)\\$(Configuration)\\</LibFolder>\n </PropertyGroup>\n\n <Target Name=\"DeleteLibFiles\">\n <Delete Files=\"@(LibFiles-> '$(ProjectDepthPath)$(LibFolder)%(filename)%(extension)')\" TreatErrorsAsWarnings=\"true\" />\n </Target>\n <Target Name=\"CopyLibFiles\">\n <Copy SourceFiles=\"@(LibFiles)\" DestinationFolder=\"$(ProjectDepthPath)$(LibFolder)\" SkipUnchangedFiles=\"True\" />\n </Target>\n\n <ItemGroup>\n <LibFiles Include=\" \">\n <Visible>false</Visible>\n </LibFiles>\n </ItemGroup>\n</Project>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"3.5\" ... >\n ...\n <Import Project=\"..\\..\\..\\..\\build\\OurBuildTargets.targets\" />\n <ItemGroup>\n <LibFiles Include=\"$(OutputPath)$(AssemblyName).dll\">\n <Visible>false</Visible>\n </LibFiles>\n </ItemGroup>\n <Target Name=\"BeforeClean\" DependsOnTargets=\"DeleteLibFiles\" />\n <Target Name=\"AfterBuild\" DependsOnTargets=\"CopyLibFiles\" />\n</Project>\n LibFiles DeleteLibFiles CopyLibFiles" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
32,744
<p>For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something...</p> <p>The way I understand it, outgoing mail has to make three trips:</p> <ol> <li>Client (gmail user using Thunderbird) to a server (Gmail)</li> <li>First server (Gmail) to second server (Hotmail)</li> <li>Second server (Hotmail) to second client (hotmail user using OS X Mail)</li> </ol> <p>As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server.</p> <p>However, I don't understand how gmail server transfers the message to the hotmail server.</p> <p>For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again).</p> <p>So, the big question is: <strong>when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it?</strong></p> <p>Thank you so much!</p> <p>~Jason</p> <hr> <p>Thanks, that's been helpful so far.</p> <p>As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually).</p> <p>Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy).</p> <p>Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right?</p> <p>Thanks again (especially to dr-jan),</p> <p>Jason</p>
[ { "answer_id": 32776, "author": "dr-jan", "author_id": 2599, "author_profile": "https://Stackoverflow.com/users/2599", "pm_score": 5, "selected": true, "text": "nslookup\n> set type=mx\n> stackoverflow.com\nServer: 158.155.25.16\nAddress: 158.155.25.16#53\n\nNon-authoritative answer:\nstackoverflow.com mail exchanger = 10 aspmx.l.google.com.\nstackoverflow.com mail exchanger = 20 alt1.aspmx.l.google.com.\nstackoverflow.com mail exchanger = 30 alt2.aspmx.l.google.com.\nstackoverflow.com mail exchanger = 40 aspmx2.googlemail.com.\nstackoverflow.com mail exchanger = 50 aspmx3.googlemail.com.\n\nAuthoritative answers can be found from:\naspmx.l.google.com internet address = 64.233.183.114\naspmx.l.google.com internet address = 64.233.183.27\n> \n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
32,747
<p>How do I get today's date in C# in mm/dd/yyyy format?</p> <p>I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time.</p> <p>BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11.</p> <p><em>Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.</em></p> <p><a href="https://stackoverflow.com/questions/32747/how-do-i-get-todays-date-in-c-in-8282008-format#32819" title="kronoz&#39;s answer">kronoz's answer</a></p>
[ { "answer_id": 32749, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 9, "selected": true, "text": "DateTime.Now.ToString(\"M/d/yyyy\");\n" }, { "answer_id": 32751, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 4, "selected": false, "text": "DateTime.Now.ToString(\"dd/MM/yyyy\");\n" }, { "answer_id": 32752, "author": "Josh Mein", "author_id": 2486, "author_profile": "https://Stackoverflow.com/users/2486", "pm_score": 3, "selected": false, "text": "DateTime.Now.Date.ToShortDateString()\n" }, { "answer_id": 32758, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 3, "selected": false, "text": "DateTime.Now.Date.ToShortDateString()\n DateTime.Now.ToString(\"d/MM/yyyy\");\n" }, { "answer_id": 32759, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": false, "text": "DateTime.Now.ToString(\"M/dd\")\n" }, { "answer_id": 32760, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "DateTime.Now.ToString(\"MM/DD\");\n" }, { "answer_id": 32764, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 3, "selected": false, "text": "string today = DateTime.Today.ToString(\"M/d\");\n" }, { "answer_id": 32819, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 5, "selected": false, "text": "using System.Globalization;\nusing System.Threading;\n\n...\n\nvar currentCulture = Thread.CurrentThread.CurrentCulture;\ntry {\n Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(\"en-us\");\n string shortDateString = DateTime.Now.ToShortDateString();\n // Do something with shortDateString...\n} finally {\n Thread.CurrentThread.CurrentCulture = currentCulture;\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
32,750
<p>I have a <code>byte[]</code> array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the <code>BinaryWriter</code> object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object)</p> <p>The problem I'm having is that the commonly accepted code for this task:</p> <pre><code> public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } </code></pre> <p>doesn't work for me. The second line of the above method where it calls the <code>Image.FromStream</code> method dies at runtime, saying</p> <pre><code>Parameter Not Valid </code></pre> <p>I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the <code>FromStream</code> method accept this fact.</p> <p>How do I turn a byte array of a TIFF image into an Image object?</p> <p>Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it.</p>
[ { "answer_id": 32841, "author": "Tim", "author_id": 1970, "author_profile": "https://Stackoverflow.com/users/1970", "pm_score": 3, "selected": true, "text": "MemoryStream ms = new MemoryStream(byteArrayIn);\n ms.Write(byteArrayIn, 0, byteArrayIn.Length);\n" }, { "answer_id": 33101, "author": "Tom Kidd", "author_id": 2577, "author_profile": "https://Stackoverflow.com/users/2577", "pm_score": 2, "selected": false, "text": "Convert.FromBase64String() Image.FromStream()" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
32,777
<p>I've found a few (unfortunately, they are bookmarked at home and I'm at work, so no links), but I was wondering if anyone had any opinions about any of them (love it, hate it, whatever) so I could make a good decision. I think I'm going to use Cygwin for my Unix commands on Windows, but I'm not sure how well that's going to work, so I would love for alternatives and I'm sure there are people out there interested in this who aren't running Cygwin.</p>
[ { "answer_id": 99843, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "fork()" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
32,790
<p>For various reasons calling <code>System.exit</code> is frowned upon when writing <strong>Java Applications</strong>, so how can I notify the calling process that not everything is going according to plan?</p> <p><strong>Edit:</strong> The 1 is a <code>standin</code> for any non-zero exit code.</p>
[ { "answer_id": 32817, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 1, "selected": false, "text": "Exception at thread 'main': FileNotFoundException \"The file 'foo' doesn't exist\"\n" }, { "answer_id": 33007, "author": "joev", "author_id": 3449, "author_profile": "https://Stackoverflow.com/users/3449", "pm_score": 3, "selected": false, "text": "main() System.exit()" }, { "answer_id": 33008, "author": "Gio", "author_id": 3477, "author_profile": "https://Stackoverflow.com/users/3477", "pm_score": 6, "selected": true, "text": "System.exit System.exit System.exit" }, { "answer_id": 19823189, "author": "djechlin", "author_id": 1339987, "author_profile": "https://Stackoverflow.com/users/1339987", "pm_score": 2, "selected": false, "text": "System.exit()" }, { "answer_id": 60826283, "author": "Franz D.", "author_id": 4610114, "author_profile": "https://Stackoverflow.com/users/4610114", "pm_score": 0, "selected": false, "text": "System.exit() System.exit() System.exit() System.halt()" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
32,803
<p>This question comes on the heels of the question asked <a href="https://stackoverflow.com/questions/371/how-do-you-make-sure-email-you-send-programmatically-is-not-automatically-marke">here</a>.</p> <p>The email that comes from our web server comes from an IP address that is different than that for the Exchange server. Is this okay if the SPF and Domain keys are setup properly?</p>
[ { "answer_id": 32817, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 1, "selected": false, "text": "Exception at thread 'main': FileNotFoundException \"The file 'foo' doesn't exist\"\n" }, { "answer_id": 33007, "author": "joev", "author_id": 3449, "author_profile": "https://Stackoverflow.com/users/3449", "pm_score": 3, "selected": false, "text": "main() System.exit()" }, { "answer_id": 33008, "author": "Gio", "author_id": 3477, "author_profile": "https://Stackoverflow.com/users/3477", "pm_score": 6, "selected": true, "text": "System.exit System.exit System.exit" }, { "answer_id": 19823189, "author": "djechlin", "author_id": 1339987, "author_profile": "https://Stackoverflow.com/users/1339987", "pm_score": 2, "selected": false, "text": "System.exit()" }, { "answer_id": 60826283, "author": "Franz D.", "author_id": 4610114, "author_profile": "https://Stackoverflow.com/users/4610114", "pm_score": 0, "selected": false, "text": "System.exit() System.exit() System.exit() System.halt()" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
32,814
<p>I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit?</p>
[ { "answer_id": 107824, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": -1, "selected": false, "text": "Page_ClientValidate(\"validationGroupName\");\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
32,824
<p>While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object.</p> <p>My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed.</p> <p>Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data?</p> <pre><code>using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext ctx) { ctx.Response.Cache.SetCacheability(HttpCacheability.Private); ctx.Response.Cache.SetETag("\"static\""); ctx.Response.ContentType = "text/plain"; ctx.Response.Write("Hello World"); } public bool IsReusable { get { return true; } } } </code></pre> <p>Will return</p> <pre> Cache-Control: private Content-Type: text/plain; charset=utf-8 Content-Length: 11 </pre> <p>But if we change it to public it'll return</p> <pre> Cache-Control: public Content-Type: text/plain; charset=utf-8 Content-Length: 11 Etag: "static" </pre> <p>I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using</p> <pre><code>Response.AppendHeader("ETag", "static") </code></pre> <p><strong>Update</strong>: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline.</p> <p><strong>Clarification</strong>: It's a long question but the core question is this: <strong>why does ASP.NET do this, how can I get around it and should I?</strong></p> <p><strong>Update</strong>: I'm going to accept <a href="https://stackoverflow.com/questions/32824/why-does-httpcacheabilityprivate-suppress-etags#34004">Tony's answer</a> since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache.<a href="http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setomitvarystar.aspx" rel="nofollow noreferrer">SetOmitVaryStar</a>(true) otherwise the cache will add the <strong>Vary: *</strong> header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?)</p>
[ { "answer_id": 33555, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 2, "selected": false, "text": "System.Web.HttpCachePolicy.UpdateCachedHeaders() Last-Modified/If-Modified-Since" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2114/" ]
32,871
<p>I have a swf with loads text into a Sprite that resizes based on the content put into - I'd like though for the ones that are longer than the page to have the browser use its native scroll bars rather than handle it in actionscript (very much like <a href="http://www.nike.com/nikeskateboarding/v3/" rel="noreferrer">http://www.nike.com/nikeskateboarding/v3/</a>...)</p> <p>I did have a look at the stuff nike did but just wasn't able to pull it off. Any idea's?</p>
[ { "answer_id": 34523, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": false, "text": "function resizeFlash( h ) {\n // \"flash-node-id\" is the ID of the embedded Flash movie\n document.getElementById(\"flash-node-id\").style.height = h + \"px\";\n}\n ExternalInterface.call(\"resizeFlash\", 400);\n ExternalInterface.call(\n \"function( id, h ) { document.getElementById(id).style.height = h + 'px'; }\",\n ExternalInterface.objectID,\n 400\n);\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
32,877
<p>I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway.</p> <p>The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all?</p> <p>Thanks.</p>
[ { "answer_id": 33312, "author": "Darryl Braaten", "author_id": 1834, "author_profile": "https://Stackoverflow.com/users/1834", "pm_score": 5, "selected": true, "text": "<configuration>\n <system.diagnostics>\n <switches>\n <add name=\"Remote.Disable\" value=\"1\" />\n </switches>\n </system.diagnostics>\n</configuration> \n" }, { "answer_id": 12289892, "author": "Jesse Chisholm", "author_id": 1456887, "author_profile": "https://Stackoverflow.com/users/1456887", "pm_score": 3, "selected": false, "text": "int limit = request.Headers.Count;\nfor(int i=0; i<limit; ++i)\n{\n if (request.Headers[i].Name.Equals(\"VsDebuggerCausalityData\"))\n {\n request.Headers.RemoveAt(i);\n break;\n }\n}\n" }, { "answer_id": 38570441, "author": "Gone Coding", "author_id": 201078, "author_profile": "https://Stackoverflow.com/users/201078", "pm_score": 4, "selected": false, "text": "@Luiz Felipe var vs = client.Endpoint.EndpointBehaviors.FirstOrDefault((i) => i.GetType().Namespace == \"Microsoft.VisualStudio.Diagnostics.ServiceModelSink\");\nif (vs != null)\n{\n client.Endpoint.Behaviors.Remove(vs);\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ]
32,897
<p>This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build.</p> <pre><code>/* ... some Java code ... ... "... */ ..." ... ... more Java code ... */ </code></pre> <p>Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing.</p>
[ { "answer_id": 32927, "author": "joev", "author_id": 3449, "author_profile": "https://Stackoverflow.com/users/3449", "pm_score": 0, "selected": false, "text": "public class Test {\n public static final void main(String[] args) throws Exception {\n String s = \"This is the original string.\";\n /* This is commented out.\n s = \"This is the end of a comment: */ \";\n */\n System.out.println(s);\n }\n}\n Test.java:5: unclosed string literal\n s = \"This is the end of a comment: */ \";\n" }, { "answer_id": 143915, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "// /* */" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
32,899
<p>I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [[&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;,], [&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;], [&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print &quot;test&quot;, name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
[ { "answer_id": 32939, "author": "Dmitry Mukhin", "author_id": 3448, "author_profile": "https://Stackoverflow.com/users/3448", "pm_score": 9, "selected": true, "text": "from parameterized import parameterized\n\nclass TestSequence(unittest.TestCase):\n @parameterized.expand([\n [\"foo\", \"a\", \"a\",],\n [\"bar\", \"a\", \"b\"],\n [\"lee\", \"b\", \"b\"],\n ])\n def test_sequence(self, name, a, b):\n self.assertEqual(a,b)\n test_sequence_0_foo (__main__.TestSequence) ... ok\ntest_sequence_1_bar (__main__.TestSequence) ... FAIL\ntest_sequence_2_lee (__main__.TestSequence) ... ok\n\n======================================================================\nFAIL: test_sequence_1_bar (__main__.TestSequence)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py\", line 233, in <lambda>\n standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)\n File \"x.py\", line 12, in test_sequence\n self.assertEqual(a,b)\nAssertionError: 'a' != 'b'\n import unittest\n\nl = [[\"foo\", \"a\", \"a\",], [\"bar\", \"a\", \"b\"], [\"lee\", \"b\", \"b\"]]\n\nclass TestSequense(unittest.TestCase):\n pass\n\ndef test_generator(a, b):\n def test(self):\n self.assertEqual(a,b)\n return test\n\nif __name__ == '__main__':\n for t in l:\n test_name = 'test_%s' % t[0]\n test = test_generator(t[1], t[2])\n setattr(TestSequense, test_name, test)\n unittest.main()\n" }, { "answer_id": 34094, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 8, "selected": false, "text": "unittest subTest from unittest import TestCase\n\nparam_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]\n\nclass TestDemonstrateSubtest(TestCase):\n def test_works_as_expected(self):\n for p1, p2 in param_list:\n with self.subTest():\n self.assertEqual(p1, p2)\n subTest() with self.subTest(msg=\"Checking if p1 equals p2\", p1=p1, p2=p2):\n param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]\n\ndef test_generator():\n for params in param_list:\n yield check_em, params[0], params[1]\n\ndef check_em(a, b):\n assert a == b\n > nosetests -v\ntestgen.test_generator('a', 'a') ... ok\ntestgen.test_generator('a', 'b') ... FAIL\ntestgen.test_generator('b', 'b') ... ok\n\n======================================================================\nFAIL: testgen.test_generator('a', 'b')\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py\", line 203, in runTest\n self.test(*self.arg)\n File \"testgen.py\", line 7, in check_em\n assert a == b\nAssertionError\n\n----------------------------------------------------------------------\nRan 3 tests in 0.006s\n\nFAILED (failures=1)\n" }, { "answer_id": 20870875, "author": "Guy", "author_id": 1540037, "author_profile": "https://Stackoverflow.com/users/1540037", "pm_score": 6, "selected": false, "text": "import unittest\n\nl = [[\"foo\", \"a\", \"a\",], [\"bar\", \"a\", \"b\"], [\"lee\", \"b\", \"b\"]]\n\nclass TestSequenceMeta(type):\n def __new__(mcs, name, bases, dict):\n\n def gen_test(a, b):\n def test(self):\n self.assertEqual(a, b)\n return test\n\n for tname, a, b in l:\n test_name = \"test_%s\" % tname\n dict[test_name] = gen_test(a,b)\n return type.__new__(mcs, name, bases, dict)\n\nclass TestSequence(unittest.TestCase):\n __metaclass__ = TestSequenceMeta\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "answer_id": 23508426, "author": "Javier", "author_id": 3339058, "author_profile": "https://Stackoverflow.com/users/3339058", "pm_score": 5, "selected": false, "text": "import unittest\n\nclass GeneralTestCase(unittest.TestCase):\n def __init__(self, methodName, param1=None, param2=None):\n super(GeneralTestCase, self).__init__(methodName)\n\n self.param1 = param1\n self.param2 = param2\n\n def runTest(self):\n pass # Test that depends on param 1 and 2.\n\n\ndef load_tests(loader, tests, pattern):\n test_cases = unittest.TestSuite()\n for p1, p2 in [(1, 2), (3, 4)]:\n test_cases.addTest(GeneralTestCase('runTest', p1, p2))\n return test_cases\n" }, { "answer_id": 25626660, "author": "Sergei Voronezhskii", "author_id": 4000827, "author_profile": "https://Stackoverflow.com/users/4000827", "pm_score": 5, "selected": false, "text": "test_me.py import pytest\n\[email protected]('name, left, right', [['foo', 'a', 'a'],\n ['bar', 'a', 'b'],\n ['baz', 'b', 'b']])\ndef test_me(name, left, right):\n assert left == right, name\n py.test --tb=short test_me.py =========================== test session starts ============================\nplatform darwin -- Python 2.7.6 -- py-1.4.23 -- pytest-2.6.1\ncollected 3 items\n\ntest_me.py .F.\n\n================================= FAILURES =================================\n_____________________________ test_me[bar-a-b] _____________________________\ntest_me.py:8: in test_me\n assert left == right, name\nE AssertionError: bar\n==================== 1 failed, 2 passed in 0.01 seconds ====================\n fixtures mark assert" }, { "answer_id": 27250866, "author": "Maroun", "author_id": 1735406, "author_profile": "https://Stackoverflow.com/users/1735406", "pm_score": 2, "selected": false, "text": "pip install nose-ittr setup @ittr(number=[1, 2, 3, 4])\ndef test_even(self):\n assert_equal(self.number % 2, 0)\n nosetest attrib nosetest -a number=2\n" }, { "answer_id": 28890882, "author": "Matt", "author_id": 452274, "author_profile": "https://Stackoverflow.com/users/452274", "pm_score": 2, "selected": false, "text": "import unittest\nimport paramunittest\n\n\[email protected](\n ('1', '2'),\n #(4, 3), <---- Uncomment to have a failing test\n ('2', '3'),\n (('4', ), {'b': '5'}),\n ((), {'a': 5, 'b': 6}),\n {'a': 5, 'b': 6},\n)\nclass TestBar(TestCase):\n def setParameters(self, a, b):\n self.a = a\n self.b = b\n\n def testLess(self):\n self.assertLess(self.a, self.b)\n" }, { "answer_id": 29384495, "author": "Bernhard", "author_id": 639054, "author_profile": "https://Stackoverflow.com/users/639054", "pm_score": 6, "selected": false, "text": "class NumbersTest(unittest.TestCase):\n\ndef test_even(self):\n \"\"\"\n Test that numbers between 0 and 5 are all even.\n \"\"\"\n for i in range(0, 6):\n with self.subTest(i=i):\n self.assertEqual(i % 2, 0)\n ======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=1)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"subtests.py\", line 32, in test_even\n self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n\n======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=3)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"subtests.py\", line 32, in test_even\n self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n\n======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=5)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"subtests.py\", line 32, in test_even\n self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n" }, { "answer_id": 29766722, "author": "Mykhaylo Kopytonenko", "author_id": 2726783, "author_profile": "https://Stackoverflow.com/users/2726783", "pm_score": 4, "selected": false, "text": "import unittest\nfrom ddt import ddt, data\nfrom mycode import larger_than_two\n\n@ddt\nclass FooTestCase(unittest.TestCase):\n\n @data(3, 4, 12, 23)\n def test_larger_than_two(self, value):\n self.assertTrue(larger_than_two(value))\n\n @data(1, -3, 2, 0)\n def test_not_larger_than_two(self, value):\n self.assertFalse(larger_than_two(value))\n pip nose unittest" }, { "answer_id": 30150971, "author": "sleepycal", "author_id": 1267398, "author_profile": "https://Stackoverflow.com/users/1267398", "pm_score": 1, "selected": false, "text": "class DocTestMeta(type):\n \"\"\"\n Test functions are generated in metaclass due to the way some\n test loaders work. For example, setupClass() won't get called\n unless there are other existing test methods, and will also\n prevent unit test loader logic being called before the test\n methods have been defined.\n \"\"\"\n def __init__(self, name, bases, attrs):\n super(DocTestMeta, self).__init__(name, bases, attrs)\n\n def __new__(cls, name, bases, attrs):\n def func(self):\n \"\"\"Inner test method goes here\"\"\"\n self.assertTrue(1)\n\n func.__name__ = 'test_sample'\n attrs[func.__name__] = func\n return super(DocTestMeta, cls).__new__(cls, name, bases, attrs)\n\nclass ExampleTestCase(TestCase):\n \"\"\"Our example test case, with no methods defined\"\"\"\n __metaclass__ = DocTestMeta\n test_sample (ExampleTestCase) ... OK\n" }, { "answer_id": 31161347, "author": "Kirill Ermolov", "author_id": 4990113, "author_profile": "https://Stackoverflow.com/users/4990113", "pm_score": 2, "selected": false, "text": "import unittest\nfrom python_wrap_cases import wrap_case\n\n\n@wrap_case\nclass TestSequence(unittest.TestCase):\n\n @wrap_case(\"foo\", \"a\", \"a\")\n @wrap_case(\"bar\", \"a\", \"b\")\n @wrap_case(\"lee\", \"b\", \"b\")\n def testsample(self, name, a, b):\n print \"test\", name\n self.assertEqual(a, b)\n testsample_u'bar'_u'a'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test bar\nFAIL\ntestsample_u'foo'_u'a'_u'a' (tests.example.test_stackoverflow.TestSequence) ... test foo\nok\ntestsample_u'lee'_u'b'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test lee\nok\n a__list b__list import unittest\nfrom python_wrap_cases import wrap_case\n\n\n@wrap_case\nclass TestSequence(unittest.TestCase):\n\n @wrap_case(a__list=[\"a\", \"b\"], b__list=[\"a\", \"b\"])\n def testsample(self, a, b):\n self.assertEqual(a, b)\n testsample_a(u'a')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... ok\ntestsample_a(u'a')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... FAIL\ntestsample_a(u'b')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... FAIL\ntestsample_a(u'b')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... ok\n" }, { "answer_id": 34382688, "author": "Max Malysh", "author_id": 1977620, "author_profile": "https://Stackoverflow.com/users/1977620", "pm_score": 1, "selected": false, "text": "TestSuite TestCase import unittest\n\nclass CustomTest(unittest.TestCase):\n def __init__(self, name, a, b):\n super().__init__()\n self.name = name\n self.a = a\n self.b = b\n\n def runTest(self):\n print(\"test\", self.name)\n self.assertEqual(self.a, self.b)\n\nif __name__ == '__main__':\n suite = unittest.TestSuite()\n suite.addTest(CustomTest(\"Foo\", 1337, 1337))\n suite.addTest(CustomTest(\"Bar\", 0xDEAD, 0xC0DE))\n unittest.TextTestRunner().run(suite)\n" }, { "answer_id": 36788233, "author": "Danielle Weisz", "author_id": 6239458, "author_profile": "https://Stackoverflow.com/users/6239458", "pm_score": 1, "selected": false, "text": "import inspect\nimport types\n\ntest_platforms = [\n {'browserName': \"internet explorer\", 'platform': \"Windows 7\", 'version': \"10.0\"},\n {'browserName': \"internet explorer\", 'platform': \"Windows 7\", 'version': \"11.0\"},\n {'browserName': \"firefox\", 'platform': \"Linux\", 'version': \"43.0\"},\n]\n\n\ndef sauce_labs():\n def wrapper(cls):\n return test_on_platforms(cls)\n return wrapper\n\n\ndef test_on_platforms(base_class):\n for name, function in inspect.getmembers(base_class, inspect.isfunction):\n if name.startswith('test_'):\n for platform in test_platforms:\n new_name = '_'.join(list([name, ''.join(platform['browserName'].title().split()), platform['version']]))\n new_function = types.FunctionType(function.__code__, function.__globals__, new_name,\n function.__defaults__, function.__closure__)\n setattr(new_function, 'platform', platform)\n setattr(base_class, new_name, new_function)\n delattr(base_class, name)\n\n return base_class\n" }, { "answer_id": 37470261, "author": "pptime", "author_id": 2590401, "author_profile": "https://Stackoverflow.com/users/2590401", "pm_score": -1, "selected": false, "text": "class Test(unittest.TestCase):\n pass\n\ndef _test(self, file_name):\n open(file_name, 'r') as f:\n self.assertEqual('test result',f.read())\n\ndef _generate_test(file_name):\n def test(self):\n _test(self, file_name)\n return test\n\ndef _generate_tests():\n for file in files:\n file_name = os.path.splitext(os.path.basename(file))[0]\n setattr(Test, 'test_%s' % file_name, _generate_test(file))\n\ntest_cases = (Test,)\n\ndef load_tests(loader, tests, pattern):\n _generate_tests()\n suite = TestSuite()\n for test_class in test_cases:\n tests = loader.loadTestsFromTestCase(test_class)\n suite.addTests(tests)\n return suite\n\nif __name__ == '__main__':\n _generate_tests()\n unittest.main()\n" }, { "answer_id": 38726022, "author": "S.Arora", "author_id": 6665372, "author_profile": "https://Stackoverflow.com/users/6665372", "pm_score": -1, "selected": false, "text": " import unittest\n\n class BaseClass(unittest.TestCase):\n def setUp(self):\n self.param = 2\n self.base = 2\n\n def test_me(self):\n self.assertGreaterEqual(5, self.param+self.base)\n\n def test_me_too(self):\n self.assertLessEqual(3, self.param+self.base)\n\n\n class Child_One(BaseClass):\n def setUp(self):\n BaseClass.setUp(self)\n self.param = 4\n\n\n class Child_Two(BaseClass):\n def setUp(self):\n BaseClass.setUp(self)\n self.param = 1\n" }, { "answer_id": 39350898, "author": "mop", "author_id": 1791024, "author_profile": "https://Stackoverflow.com/users/1791024", "pm_score": 1, "selected": false, "text": "unittest nose #!/usr/bin/env python\nimport unittest\n\ndef make_function(description, a, b):\n def ghost(self):\n self.assertEqual(a, b, description)\n print(description)\n ghost.__name__ = 'test_{0}'.format(description)\n return ghost\n\n\nclass TestsContainer(unittest.TestCase):\n pass\n\ntestsmap = {\n 'foo': [1, 1],\n 'bar': [1, 2],\n 'baz': [5, 5]}\n\ndef generator():\n for name, params in testsmap.iteritems():\n test_func = make_function(name, params[0], params[1])\n setattr(TestsContainer, 'test_{0}'.format(name), test_func)\n\ngenerator()\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "answer_id": 41010565, "author": "Arindam Roychowdhury", "author_id": 1076965, "author_profile": "https://Stackoverflow.com/users/1076965", "pm_score": 2, "selected": false, "text": "import unittest\n\ndef generator(test_class, a, b):\n def test(self):\n self.assertEqual(a, b)\n return test\n\ndef add_test_methods(test_class):\n # The first element of list is variable \"a\", then variable \"b\", then name of test case that will be used as suffix.\n test_list = [[2,3, 'one'], [5,5, 'two'], [0,0, 'three']]\n for case in test_list:\n test = generator(test_class, case[0], case[1])\n setattr(test_class, \"test_%s\" % case[2], test)\n\n\nclass TestAuto(unittest.TestCase):\n def setUp(self):\n print 'Setup'\n pass\n\n def tearDown(self):\n print 'TearDown'\n pass\n\n_add_test_methods(TestAuto) # It's better to start with underscore so it is not detected as a test itself\n\nif __name__ == '__main__':\n unittest.main(verbosity=1)\n >>>\nSetup\nFTearDown\nSetup\nTearDown\n.Setup\nTearDown\n.\n======================================================================\nFAIL: test_one (__main__.TestAuto)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"D:/inchowar/Desktop/PyTrash/test_auto_3.py\", line 5, in test\n self.assertEqual(a, b)\nAssertionError: 2 != 3\n\n----------------------------------------------------------------------\nRan 3 tests in 0.019s\n\nFAILED (failures=1)\n" }, { "answer_id": 43851514, "author": "Patrick Ohly", "author_id": 222305, "author_profile": "https://Stackoverflow.com/users/222305", "pm_score": 0, "selected": false, "text": "__metaclass__ metaclass class ExampleTestCase(TestCase,metaclass=DocTestMeta):\n pass\n" }, { "answer_id": 45570424, "author": "YvesgereY", "author_id": 995896, "author_profile": "https://Stackoverflow.com/users/995896", "pm_score": 1, "selected": false, "text": "import unittest\n\nclass TestSequence(unittest.TestCase):\n\n def _test_complex_property(self, a, b):\n self.assertEqual(a,b)\n\n def test_foo(self):\n self._test_complex_property(\"a\", \"a\")\n def test_bar(self):\n self._test_complex_property(\"a\", \"b\")\n def test_lee(self):\n self._test_complex_property(\"b\", \"b\")\n\nif __name__ == '__main__':\n unittest.main()\n @given(st.text(), st.text())\n def test_complex_property(self, a, b):\n self.assertEqual(a,b)\n @example(\"a\", \"a\")\n @example(\"a\", \"b\")\n @example(\"b\", \"b\")\n @given(st.nothing()) @given(st.just(\"a\"), st.just(\"b\"))\n" }, { "answer_id": 48452127, "author": "hhquark", "author_id": 5932228, "author_profile": "https://Stackoverflow.com/users/5932228", "pm_score": 0, "selected": false, "text": "setUpClass setUpClass import unittest\n\n\nclass GeneralTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n print ''\n print cls.p1\n print cls.p2\n\n def runTest1(self):\n self.assertTrue((self.p2 - self.p1) == 1)\n\n def runTest2(self):\n self.assertFalse((self.p2 - self.p1) == 2)\n\n\ndef load_tests(loader, tests, pattern):\n test_cases = unittest.TestSuite()\n for p1, p2 in [(1, 2), (3, 4)]:\n clsname = 'TestCase_{}_{}'.format(p1, p2)\n dct = {\n 'p1': p1,\n 'p2': p2,\n }\n cls = type(clsname, (GeneralTestCase,), dct)\n test_cases.addTest(cls('runTest1'))\n test_cases.addTest(cls('runTest2'))\n return test_cases\n 1\n2\n..\n3\n4\n..\n----------------------------------------------------------------------\nRan 4 tests in 0.000s\n\nOK\n" }, { "answer_id": 57378023, "author": "bcdan", "author_id": 3325465, "author_profile": "https://Stackoverflow.com/users/3325465", "pm_score": 1, "selected": false, "text": "import unittest\n\ndef rename(newName):\n def renamingFunc(func):\n func.__name__ == newName\n return func\n return renamingFunc\n\nclass TestGenerator(unittest.TestCase):\n\n TEST_DATA = {}\n\n @classmethod\n def generateTests(cls):\n for dataName, dataValue in TestGenerator.TEST_DATA:\n for func in cls.getTests(dataName, dataValue):\n setattr(cls, \"test_{:s}_{:s}\".format(func.__name__, dataName), func)\n\n @classmethod\n def getTests(cls):\n raise(NotImplementedError(\"This must be implemented\"))\n\nclass TestCluster(TestGenerator):\n\n TEST_CASES = []\n\n @staticmethod\n def getTests(dataName, dataValue):\n\n def makeTest(case):\n\n @rename(\"{:s}\".format(case[\"name\"]))\n def test(self):\n # Do things with self, case, data\n pass\n\n return test\n\n return [makeTest(c) for c in TestCluster.TEST_CASES]\n\nTestCluster.generateTests()\n TestGenerator TestCluster TestCluster TestGenerator" }, { "answer_id": 58974546, "author": "thangaraj1980", "author_id": 2707200, "author_profile": "https://Stackoverflow.com/users/2707200", "pm_score": -1, "selected": false, "text": "import unittest\n\ndef generator(test_class, a, b,c,d,name):\n def test(self):\n print('Testexecution=',name)\n print('a=',a)\n print('b=',b)\n print('c=',c)\n print('d=',d)\n\n return test\n\ndef add_test_methods(test_class):\n test_list = [[3,3,5,6, 'one'], [5,5,8,9, 'two'], [0,0,5,6, 'three'],[0,0,2,3,'Four']]\n for case in test_list:\n print('case=',case[0], case[1],case[2],case[3],case[4])\n test = generator(test_class, case[0], case[1],case[2],case[3],case[4])\n setattr(test_class, \"test_%s\" % case[4], test)\n\n\nclass TestAuto(unittest.TestCase):\n def setUp(self):\n print ('Setup')\n pass\n\n def tearDown(self):\n print ('TearDown')\n pass\n\nadd_test_methods(TestAuto)\n\nif __name__ == '__main__':\n unittest.main(verbosity=1)\n" }, { "answer_id": 62476654, "author": "Eric Cousineau", "author_id": 7829525, "author_profile": "https://Stackoverflow.com/users/7829525", "pm_score": 2, "selected": false, "text": "parameterized unittest def sub_test(param_list):\n \"\"\"Decorates a test case to run it as a set of subtests.\"\"\"\n\n def decorator(f):\n\n @functools.wraps(f)\n def wrapped(self):\n for param in param_list:\n with self.subTest(**param):\n f(self, **param)\n\n return wrapped\n\n return decorator\n class TestStuff(unittest.TestCase):\n @sub_test([\n dict(arg1='a', arg2='b'),\n dict(arg1='x', arg2='y'),\n ])\n def test_stuff(self, arg1, arg2):\n ...\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720/" ]
32,937
<p>In C# is there a shorthand way to write this:</p> <pre><code>public static bool IsAllowed(int userID) { return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...); } </code></pre> <p>Like:</p> <pre><code>public static bool IsAllowed(int userID) { return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...); } </code></pre> <p>I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.</p>
[ { "answer_id": 32942, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "List<int> allowedIDs = ...;\n\npublic bool IsAllowed(int userID)\n{\n return allowedIDs.Contains(userID);\n}\n IEnumerable List" }, { "answer_id": 32944, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 2, "selected": false, "text": "public static bool IsAllowed(int userID) {\n List<int> IDs = new List<string> { 1,2,3,4,5 };\n return IDs.Contains(userID);\n}\n" }, { "answer_id": 32950, "author": "Pauly", "author_id": 3460, "author_profile": "https://Stackoverflow.com/users/3460", "pm_score": 1, "selected": false, "text": "class User {\n public UserRole Role{get; set;}\n public string Name {get; set;}\n public int UserId {get; set;}\n}\n\npublic static bool IsAllowed(User user) {\n return user.Role == UserRole.LordEmperor;\n}\n" }, { "answer_id": 33014, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 0, "selected": false, "text": "public static bool IsAllowed(int userID) {\n return new int[] { Personnel.JaneDoe, Personnel.JohnDoe }.Contains(userID);\n}\n public static bool IsAllowed(int userID) {\n return Enum.IsDefined(typeof(Personnel), userID);\n}\n" }, { "answer_id": 33015, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "using System.Linq;\npublic static bool IsAllowed(int userID)\n{\n return new Personnel[]\n { Personnel.JohnDoe, Personnel.JaneDoe }.Contains((Personnel)userID);\n}\n" }, { "answer_id": 33018, "author": "Adam", "author_id": 3142, "author_profile": "https://Stackoverflow.com/users/3142", "pm_score": 0, "selected": false, "text": "return new [] { Personnel.JohnDoe, Personnel.JaneDoe }.Contains(userID);\n" }, { "answer_id": 33024, "author": "Chad Boyer", "author_id": 3135, "author_profile": "https://Stackoverflow.com/users/3135", "pm_score": 0, "selected": false, "text": "public static bool IsAllowed(int userID)\n{\n return (Personnel.Contains(userID))\n}\n\npublic bool Contains(int userID) : extends Personnel (i think that is how it is written)\n{\n foreach (int id in Personnel)\n if (id == userid)\n return true;\n return false;\n}\n" }, { "answer_id": 33234, "author": "Jon Sagara", "author_id": 731, "author_profile": "https://Stackoverflow.com/users/731", "pm_score": 5, "selected": true, "text": "public static class Extensions\n{\n public static bool In<T>(this T testValue, params T[] values)\n {\n return values.Contains(testValue);\n }\n}\n Personnel userId = Personnel.JohnDoe;\n\nif (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))\n{\n // Do something\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1302/" ]
32,986
<p>I know that if you have a loop that modifies the count of the items in the loop, using the NSEnumerator on a set is the best way to make sure your code blows up, however I would like to understand the performance tradeoffs between the NSEnumerator class and just an old school for loop</p>
[ { "answer_id": 33035, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "NSFastEnumeration objectAtIndex:i objectAtIndex:i method for ( Type newVariable in expression ) { \n stmts \n}\n" }, { "answer_id": 33256, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 6, "selected": true, "text": "for (... in ...) NSEnumerator -retain -[NSArray objectAtIndex:] NSEnumerator for (... in ...)" }, { "answer_id": 30720339, "author": "Zsivics Sanel", "author_id": 1600061, "author_profile": "https://Stackoverflow.com/users/1600061", "pm_score": 3, "selected": false, "text": "tmp NSArray - (NSArray *)createArray\n{\n self.tmpArray = [NSMutableArray array];\n for (int i = 0; i < 1000000; i++)\n {\n [self.tmpArray addObject:@(i)];\n }\n return self.tmpArray;\n}\n #import <UIKit/UIKit.h>\n\n@interface ViewController : UIViewController\n\n@property (strong, nonatomic) NSMutableArray *tmpArray;\n- (NSArray *)createArray;\n\n@end\n #import \"ViewController.h\"\n\n@implementation ViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n [self createArray];\n}\n\n- (NSArray *)createArray\n{\n self.tmpArray = [NSMutableArray array];\n for (int i = 0; i < 1000000; i++)\n {\n [self.tmpArray addObject:@(i)];\n }\n return self.tmpArray;\n}\n\n@end\n #import <UIKit/UIKit.h>\n#import <XCTest/XCTest.h>\n\n#import \"ViewController.h\"\n\n@interface TestCaseXcodeTests : XCTestCase\n{\n ViewController *vc;\n NSArray *tmp;\n}\n\n@end\n\n@implementation TestCaseXcodeTests\n\n- (void)setUp {\n [super setUp];\n vc = [[ViewController alloc] init];\n tmp = vc.createArray;\n}\n\n- (void)testPerformanceExample1\n{\n [self measureBlock:^{\n for (int i = 0; i < [tmp count]; i++)\n {\n [tmp objectAtIndex:i];\n }\n }];\n}\n\n- (void)testPerformanceExample2\n{\n [self measureBlock:^{\n [tmp enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL *stop) {\n obj;\n }];\n }];\n}\n\n- (void)testPerformanceExample3\n{\n [self measureBlock:^{\n for (NSNumber *num in tmp)\n {\n num;\n }\n }];\n}\n\n- (void)testPerformanceExample4\n{\n [self measureBlock:^{\n int i = 0;\n while (i < [tmp count])\n {\n [tmp objectAtIndex:i];\n i++;\n }\n }];\n}\n\n@end\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3484/" ]
32,991
<p>The leaving your wireless network open question reminded me of this.</p> <p>I typically share the root drive on my machines across my network, and tie login authorization to the machines NT ID, so there is at least some form of protection.</p> <p>My question, how easy is it to gain access to these drives for ill good? Is the authorization enough, or should I lock things down more?</p>
[ { "answer_id": 32997, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 0, "selected": false, "text": "\\\\yourmachine\\c$\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/32991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
33,048
<p>Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?</p>
[ { "answer_id": 33869, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": false, "text": "should_receive class Person < ActiveRecord::Base\n def set_status( new_status )\n # do whatever\n end\nend\n\nclass PersonObserver < ActiveRecord::Observer\n def after_save(person)\n person.set_status(\"aha!\")\n end\nend\n describe PersonObserver do\n before :each do\n @person = stub_model(Person)\n @observer = PersonObserver.instance\n end\n\n it \"should invoke after_save on the observed object\" do\n @person.should_receive(:set_status).with(\"aha!\")\n @observer.after_save(@person)\n end\nend\n" }, { "answer_id": 130114, "author": "Pete", "author_id": 13472, "author_profile": "https://Stackoverflow.com/users/13472", "pm_score": 6, "selected": true, "text": "describe Person do \n it \"should set status correctly\" do \n @p = Person.new(:status => \"foo\")\n @p.set_status(\"bar\")\n @p.save\n @p.status.should eql(\"bar\")\n end\nend\n describe PersonObserver do\n it \"should clobber the status field\" do \n @p = mock_model(Person, :status => \"foo\")\n @obs = PersonObserver.instance\n @p.should_receive(:set_status).with(\"aha!\")\n @obs.after_save\n end\nend \n describe Person do \n it \"should register a status change with the person observer turned on\" do\n Person.with_observers(:person_observer) do\n lambda { @p = Person.new; @p.save }.should change(@p, :status).to(\"aha!)\n end\n end\nend\n" }, { "answer_id": 5930831, "author": "Sujoy Gupta", "author_id": 634977, "author_profile": "https://Stackoverflow.com/users/634977", "pm_score": 2, "selected": false, "text": "class YourModel < ActiveRecord::Base\n ...\nend\n class YourModelObserver < ActiveRecord::Observer\n def after_create\n ...\n end\n\n def custom_notification\n ...\n end\nend\n before do\n @observer = YourModelObserver.instance\n @model = YourModel.new\nend\n\nit \"acts on the after_create notification\"\n mock(@observer).after_create(@model)\n @model.save!\nend\n\nit \"acts on the custom notification\"\n mock(@observer).custom_notification(@model)\n @model.send(:notify, :custom_notification)\nend\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2569/" ]
33,055
<p>I'm new to SVN and I'd like to know what methods are available for backing up repositories in a Windows environment?</p>
[ { "answer_id": 33064, "author": "Nicolai Reuschling", "author_id": 2569, "author_profile": "https://Stackoverflow.com/users/2569", "pm_score": 8, "selected": true, "text": "svnadmin dump repositorypath | gzip > backupname.svn.gz\n svnadmin dump repositorypath > backupname.svn\n" }, { "answer_id": 33068, "author": "RobotCaleb", "author_id": 1621, "author_profile": "https://Stackoverflow.com/users/1621", "pm_score": 3, "selected": false, "text": "svnadmin dump svnadmin load" }, { "answer_id": 33072, "author": "Adam", "author_id": 3142, "author_profile": "https://Stackoverflow.com/users/3142", "pm_score": 4, "selected": false, "text": "svnadmin hotcopy REPOS_PATH NEW_REPOS_PATH\n" }, { "answer_id": 33088, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 2, "selected": false, "text": "svnadmin hotcopy" }, { "answer_id": 33114, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 7, "selected": false, "text": "svnadmin hotcopy C:\\svn\\repo D:\\backups\\svn\\repo\n" }, { "answer_id": 37554, "author": "quick_dry", "author_id": 3716, "author_profile": "https://Stackoverflow.com/users/3716", "pm_score": 0, "selected": false, "text": "svnadmin hotcopy svnadmin svndump" }, { "answer_id": 717473, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "my $svn_repo = \"/var/svn\"; \nmy $bkup_dir = \"/home/backup_user/backups\";\nmy $bkup_file = \"my_backup-\";\nmy $tmp_dir = \"/home/backup_user/tmp\"; \nmy $bkup_svr = \"my.backup.com\";\nmy $bkup_svr_login = \"backup\";\n\n$bkup_file = $bkup_file . `date +%Y%m%d-%H%M`;\nchomp $bkup_file;\nmy $youngest = `svnlook youngest $svn_repo`;\nchomp $youngest;\n\nmy $dump_command = \"svnadmin -q dump $svn_repo > $bkup_dir/$bkup_file \";\nprint \"\\nDumping Subversion repo $svn_repo to $bkup_file...\\n\";\nprint `$dump_command`;\nprint \"Backing up through revision $youngest... \\n\";\nprint \"\\nCompressing dump file...\\n\";\nprint `gzip -9 $bkup_dir/$bkup_file\\n`;\nchomp $bkup_file;\nmy $zipped_file = $bkup_dir . \"/\" . $bkup_file . \".gz\";\nprint \"\\nCreated $zipped_file\\n\";\nprint `scp $zipped_file $bkup_svr_login\\@$bkup_svr:/home/backup/`;\nprint \"\\n$bkup_file.gz transfered to $bkup_svr\\n\";\n\n#Test Backup\nprint \"\\n---------------------------------------\\n\";\nprint \"Testing Backup\";\nprint \"\\n---------------------------------------\\n\";\nprint \"Downloading $bkup_file.gz from $bkup_svr\\n\";\nprint `scp $bkup_svr_login\\@$bkup_svr:/home/backup/$bkup_file.gz $tmp_dir/`;\nprint \"Unzipping $bkup_file.gz\\n\";\nprint `gunzip $tmp_dir/$bkup_file.gz`;\nprint \"Creating test repository\\n\";\nprint `svnadmin create $tmp_dir/test_repo`;\nprint \"Loading repository\\n\";\nprint `svnadmin -q load $tmp_dir/test_repo < $tmp_dir/$bkup_file`;\nprint \"Checking out repository\\n\";\nprint `svn -q co file://$tmp_dir/test_repo $tmp_dir/test_checkout`;\nprint \"Cleaning up\\n\";\nprint `rm -f $tmp_dir/$bkup_file`;\nprint `rm -rf $tmp_dir/test_checkout`;\nprint `rm -rf $tmp_dir/test_repo`;\n" }, { "answer_id": 6168209, "author": "Nitin Verma", "author_id": 565859, "author_profile": "https://Stackoverflow.com/users/565859", "pm_score": 1, "selected": false, "text": "install svk (http://svk.bestpractical.com/view/SVKWin32)\n\ninstall svn (http://sourceforge.net/projects/win32svn/files/1.6.16/Setup-Subversion-1.6.16.msi/download)\n\nsvk mirror //local <remote repository URL>\n\nsvk sync //local\n C:\\Documents and Settings\\nverma\\.svk\\local /home/user/.svk/local svn checkout \"file:///C:/Documents and Settings\\nverma/.svk/local/\" <local-dir-path-to-checkout-onto>\n Checked out revision N N -r <local-dir-path-to-checkout-onto> C:/Documents and Settings\\nverma/.svk/local/" }, { "answer_id": 8668396, "author": "RoughPlace", "author_id": 468083, "author_profile": "https://Stackoverflow.com/users/468083", "pm_score": 2, "selected": false, "text": "@echo off\nset hour=%time:~0,2%\nif \"%hour:~0,1%\"==\" \" set hour=0%time:~1,1%\nset folder=%date:~6,4%%date:~3,2%%date:~0,2%%hour%%time:~3,2%\n\necho Performing Backup\nmd \"\\\\HOME\\Development\\Backups\\SubVersion\\%folder%\"\n\nsvnadmin dump \"C:\\Users\\Yakyb\\Desktop\\MainRepositary\\Jake\" | \"C:\\Program Files\\7-Zip\\7z.exe\" a \"\\\\HOME\\Development\\Backups\\SubVersion\\%folder%\\Jake.7z\" -sibackupname.svn\n" }, { "answer_id": 11868183, "author": "atx", "author_id": 1585221, "author_profile": "https://Stackoverflow.com/users/1585221", "pm_score": 3, "selected": false, "text": "C:\\Repositories\\ \"STOP_SERVICE\" \"START_SERVICE\"" }, { "answer_id": 20362633, "author": "ajdev8", "author_id": 1610035, "author_profile": "https://Stackoverflow.com/users/1610035", "pm_score": 2, "selected": false, "text": "svnrdump svnadmin dump svnrdump dump /URL/to/remote/repository > myRepository.dump\n svnadmin load /path/to/local/repository < myRepository.dump\n" }, { "answer_id": 27154329, "author": "Aamir Shahzad", "author_id": 2159585, "author_profile": "https://Stackoverflow.com/users/2159585", "pm_score": 0, "selected": false, "text": "svnadmin dump /path/to/reponame > /path/to/reponame.dump\n svnadmin dump /var/www/svn/testrepo > /backups/testrepo.dump\n gzip -9 /path/to/reponame.dump\n gzip -9 /backups/testrepo.dump\n svnadmin dump /path/to/reponame | gzip -9 > /path/to/reponame.dump.gz\n svnadmin dump /var/www/svn/testrepo |Â gzip -9 > /backups/testrepo.dump.gz\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3396/" ]
33,063
<p>I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code.<br> The first step of the parsing process splits the file into individual lines by just using a <code>StreamReader</code> object and calling <code>ReadLine</code> until it's through the file. However, any given line might contain a quoted (in single quotes) literal with embedded newlines. I need to find those newlines and convert them temporarily into some other kind of token or escape sequence until I've split the file into an array of lines..then I can change them back. </p> <p>Example input data: </p> <pre><code>1,2,10,99,'Some text without a newline', true, false, 90 2,1,11,98,'This text has an embedded newline and continues here', true, true, 90 </code></pre> <p>I could write all of the C# code needed to do this by using <code>string.IndexOf</code> to find the quoted sections and look within them for newlines, but I'm thinking a Regex might be a better choice (i.e. <a href="http://regex.info/blog/2006-09-15/247" rel="nofollow noreferrer">now I have two problems</a>)</p>
[ { "answer_id": 33074, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "content = Regex.Replace(content, \"'([^']*)\\n([^']*)'\", \"'\\1TOKEN\\2'\");\n" }, { "answer_id": 33172, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 2, "selected": false, "text": "public class CsvParser\n{\n public char FieldDelimiter { get; set; }\n\n public CsvParser()\n : this(',')\n {\n }\n\n public CsvParser(char fieldDelimiter)\n {\n FieldDelimiter = fieldDelimiter;\n }\n\n public IEnumerable<IEnumerable<string>> Parse(string text)\n {\n return Parse(new StringReader(text));\n }\n public IEnumerable<IEnumerable<string>> Parse(TextReader reader)\n {\n while (reader.Peek() != -1)\n yield return parseLine(reader);\n }\n\n IEnumerable<string> parseLine(TextReader reader)\n {\n bool insideQuotes = false;\n StringBuilder item = new StringBuilder();\n\n while (reader.Peek() != -1)\n {\n char ch = (char)reader.Read();\n char? nextCh = reader.Peek() > -1 ? (char)reader.Peek() : (char?)null;\n\n if (!insideQuotes && ch == FieldDelimiter)\n {\n yield return item.ToString();\n item.Length = 0;\n }\n else if (!insideQuotes && ch == '\\r' && nextCh == '\\n') //CRLF\n {\n reader.Read(); // skip LF\n break;\n }\n else if (!insideQuotes && ch == '\\n') //LF for *nix-style line endings\n break;\n else if (ch == '\"' && nextCh == '\"') // escaped quotes \"\"\n {\n item.Append('\"');\n reader.Read(); // skip next \"\n }\n else if (ch == '\"')\n insideQuotes = !insideQuotes;\n else\n item.Append(ch);\n }\n // last one\n yield return item.ToString();\n }\n\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187/" ]
33,073
<p>How do I make <code>diff</code> ignore temporary files like <code>foo.c~</code>? Is there a configuration file that will make ignoring temporaries the default?</p> <p>More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it...</p> <p>EDIT: OK, the short answer is</p> <pre><code>diff -ruN -x *~ ... </code></pre> <p>Is there a better answer? E.g., can this go in a configuration file?</p>
[ { "answer_id": 33098, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 0, "selected": false, "text": "#!/bin/bash\nolddir=\"/tmp/old\"\nnewdir=\"/tmp/new\"\n\npushd $newdir\nfor files in $(find . -name \\*.c)\ndo\n diff $olddir/$file $newdir/$file\ndone\npopd\n" }, { "answer_id": 1099613, "author": "rnsanchez", "author_id": 72689, "author_profile": "https://Stackoverflow.com/users/72689", "pm_score": 2, "selected": false, "text": "core.*\n*~\n*.o\n*.a\n*.so\n<more file patterns you want to skip>\n diff -X diff -X ignore-file <other diff options you use/need> path1 path2\n" }, { "answer_id": 26330661, "author": "Bret Weinraub", "author_id": 869942, "author_profile": "https://Stackoverflow.com/users/869942", "pm_score": 0, "selected": false, "text": "diff -ruN -x *~ ...\n diff -r -x '*~' dir1 dir2\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
33,080
<p>In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.</p> <p>I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.</p> <p>My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me?</p> <p>Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar).</p>
[ { "answer_id": 33096, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "div {\n position: absolute;\n top: 300px;\n bottom: 0px;\n left: 30px;\n right: 30px;\n}\n overflow:auto;" }, { "answer_id": 33124, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 0, "selected": false, "text": "// the more standards compliant browsers (mozilla/netscape/opera/IE7) use \n// window.innerWidth and window.innerHeight\n\nvar windowHeight;\n\nif (typeof window.innerWidth != 'undefined')\n{\n windowHeight = window.innerHeight;\n}\n// IE6 in standards compliant mode (i.e. with a valid doctype as the first \n// line in the document)\nelse if (typeof document.documentElement != 'undefined'\n && typeof document.documentElement.clientWidth != 'undefined' \n && document.documentElement.clientWidth != 0)\n{\n windowHeight = document.documentElement.clientHeight;\n}\n// older versions of IE\nelse\n{\n windowHeight = document.getElementsByTagName('body')[0].clientHeight;\n}\n\ndocument.getElementById(\"yourDiv\").height = windowHeight - 300 + \"px\";\n" }, { "answer_id": 33129, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 3, "selected": false, "text": "document.getElementById('myDiv').style.height = 500; XMLHttpRequest" }, { "answer_id": 33147, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 6, "selected": true, "text": "function resizeElementHeight(element) {\n var height = 0;\n var body = window.document.body;\n if (window.innerHeight) {\n height = window.innerHeight;\n } else if (body.parentElement.clientHeight) {\n height = body.parentElement.clientHeight;\n } else if (body && body.clientHeight) {\n height = body.clientHeight;\n }\n element.style.height = ((height - element.offsetTop) + \"px\");\n}\n" }, { "answer_id": 1718904, "author": "Shanti", "author_id": 209155, "author_profile": "https://Stackoverflow.com/users/209155", "pm_score": 0, "selected": false, "text": "function rearrange()\n{\nvar windowHeight;\n\nif (typeof window.innerWidth != 'undefined')\n{\n windowHeight = window.innerHeight;\n}\n// IE6 in standards compliant mode (i.e. with a valid doctype as the first\n// line in the document)\nelse if (typeof document.documentElement != 'undefined'\n && typeof document.documentElement.clientWidth != 'undefined'\n && document.documentElement.clientWidth != 0)\n{\n windowHeight = document.documentElement.clientHeight;\n}\n// older versions of IE\nelse\n{\n windowHeight = document.getElementsByTagName('body')[0].clientHeight;\n}\n\ndocument.getElementById(\"foobar\").style.height = (windowHeight - document.getElementById(\"foobar\").offsetTop - 6)+ \"px\";\n}\n" }, { "answer_id": 26062700, "author": "RawBits", "author_id": 2023816, "author_profile": "https://Stackoverflow.com/users/2023816", "pm_score": 0, "selected": false, "text": "function resizeResizeableHeight() {\n $('.resizableHeight').each( function() {\n $(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )\n });\n}\n" }, { "answer_id": 40434747, "author": "mwag", "author_id": 3160967, "author_profile": "https://Stackoverflow.com/users/3160967", "pm_score": 0, "selected": false, "text": "function resizeElementDimension(element, doHeight) {\n dim = (doHeight ? 'Height' : 'Width')\n ref = (doHeight ? 'Top' : 'Left')\n\n var x = 0;\n var body = window.document.body;\n if(window['inner' + dim])\n x = window['inner' + dim]\n else if (body.parentElement['client' + dim])\n x = body.parentElement['client' + dim]\n else if (body && body['client' + dim])\n x = body['client' + dim]\n\n element.style[dim.toLowerCase()] = ((x - element['offset' + ref]) + \"px\");\n}\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226/" ]
33,089
<p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application. It keeps redirecting to a Login.aspx page at the root of my application that does not exist. My login page is within a folder.</p>
[ { "answer_id": 33092, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 1, "selected": false, "text": "<?xml version=\"1.0\"?>\n<configuration>\n <system.web>\n ...\n <!--\n The <authentication> section enables configuration \n of the security authentication mode used by \n ASP.NET to identify an incoming user. \n -->\n <authentication mode=\"Forms\">\n <forms loginUrl=\"~/FolderName/Login.aspx\" />\n </authentication>\n ...\n </system.web>\n ...\n</configuration>\n" }, { "answer_id": 33106, "author": "Ryan Sampson", "author_id": 1375, "author_profile": "https://Stackoverflow.com/users/1375", "pm_score": 4, "selected": true, "text": "<authentication mode=\"Forms\">\n <forms defaultUrl=\"~/Default.aspx\" loginUrl=\"~/login.aspx\" timeout=\"1440\" ></forms>\n</authentication>\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
33,103
<p>I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?</p>
[ { "answer_id": 33130, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 4, "selected": true, "text": "onpaste return false e.preventDefault() onpaste $(document).on(\"paste\",function(e){\n console.log(\"paste\")\n e.preventDefault()\n return false;\n})" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1450/" ]
33,115
<p>Does C# have the notion of private / protected inheritance, and if not, why?</p> <p><strong>C++</strong></p> <pre> <code> class Foo : private Bar { public: ... }; </code> </pre> <p><strong>C#</strong></p> <pre> <code> public abstract NServlet class : private System.Web.UI.Page { // error "type expected" } </code> </pre> <p>I am implementing a "servlet like" concept in an .aspx page and I don't want the concrete class to have the ability to see the internals of the System.Web.UI.Page base.</p>
[ { "answer_id": 33182, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 2, "selected": false, "text": "class Base\n{\n public void F() {}\n}\nclass Derived : Base\n{\n new private void F() {}\n}\n\nBase o = new Derived();\no.F(); // works\n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
33,150
<p>I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form.</p> <p>in vb.net: <code>Parent.FindControl(TargetControlName)</code></p> <p>I would like to pass a method to the control in the ASPX markup. </p> <p>for example: <code>&lt;c:MyCustomerControl runat=server InitializeStuffCallback="InitializeStuff"&gt;</code></p> <p>So, I tried using reflection to access the given method name from the Parent.</p> <p>Something like (in VB)</p> <pre class="lang-vb prettyprint-override"><code>Dim pageType As Type = Page.GetType Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" ) 'Also tried sender.Parent.GetType.GetMethod("MethodName") sender.Parent.Parent.GetType.GetMethod("MethodName") </code></pre> <p>The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar.</p> <hr> <p>I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind.</p>
[ { "answer_id": 33179, "author": "Jesse Dearing", "author_id": 1804, "author_profile": "https://Stackoverflow.com/users/1804", "pm_score": 3, "selected": true, "text": "Browsable <Browsable(True)> Public Event InitializeStuffCallback\n [Browsable(true)]\npublic event EventHandler InitializeStuffCallback;\n" }, { "answer_id": 33187, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 2, "selected": false, "text": "public event EventHandler EventName;\n protected void MyCustomerControl_MethodName(object sender, EventArgs e) { }\n <c:MyCustomerControl id=\"MyCustomerControl\" runat=server OnEventName=\"MyCustomerControl_MethodName\">\n" }, { "answer_id": 33191, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "Page class MyPage : Page\n" }, { "answer_id": 33536, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 0, "selected": false, "text": "[Browsable(true)] \n" } ]
2008/08/28
[ "https://Stackoverflow.com/questions/33150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]