qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
81,272
<p>I know the combination <kbd>Ctrl</kbd>+<kbd>A</kbd> to jump to the beginning of the current command, and <kbd>Ctrl</kbd>+<kbd>E</kbd> to jump to the end. </p> <p>But is there any way to jump word by word, like <kbd>Alt</kbd>+<kbd>&larr;</kbd>/<kbd>&rarr;</kbd> in Cocoa applications does?</p>
[ { "answer_id": 81299, "author": "Fil", "author_id": 12218, "author_profile": "https://Stackoverflow.com/users/12218", "pm_score": 8, "selected": false, "text": "⌥ ← \\033b \\033f" }, { "answer_id": 81333, "author": "Andy Lynch", "author_id": 14338, "author_profile": "https://Stackoverflow.com/users/14338", "pm_score": 3, "selected": false, "text": "bind -p" }, { "answer_id": 81343, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 4, "selected": false, "text": "Use option as meta key ⌥F ⌥B" }, { "answer_id": 87778, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 5, "selected": false, "text": "bind -f ~/.bash_key_bindings\n set meta-flag on\nset input-meta on\nset output-meta on\nset convert-meta off\nset show-all-if-ambiguous on\nset bell-style none\nset print-completions-horizontally off\n \"A\": self-insert\n\"B\": self-insert\n\"C\": self-insert\n\"D\": self-insert\n\"E\": self-insert\n\"F\": self-insert\n\"G\": self-insert\n\"H\": self-insert\n\"I\": self-insert\n\"J\": self-insert\n \"\\C-dW\": kill-word\n\"\\C-dL\": kill-line\n\"\\C-dw\": backward-kill-word\n\"\\C-dl\": backward-kill-line\n\"\\C-da\": kill-line\n \"\\C-f\": forward-word\n\"\\C-b\": backward-word\n" }, { "answer_id": 7033964, "author": "jches", "author_id": 223594, "author_profile": "https://Stackoverflow.com/users/223594", "pm_score": 4, "selected": false, "text": "~/.bashrc set -o vi\n w b" }, { "answer_id": 54001064, "author": "qix", "author_id": 954643, "author_profile": "https://Stackoverflow.com/users/954643", "pm_score": 3, "selected": false, "text": "iterm2 + Send Escape Sequence b f" }, { "answer_id": 56026518, "author": "Dziamid", "author_id": 219931, "author_profile": "https://Stackoverflow.com/users/219931", "pm_score": 5, "selected": false, "text": "^[b ^[f" }, { "answer_id": 57968002, "author": "Chinmay Chhajed", "author_id": 7783417, "author_profile": "https://Stackoverflow.com/users/7783417", "pm_score": 1, "selected": false, "text": "set -o vi ~/.bashrc vi vim .bashrc Ctrl # bindings to move 1 word left/right with ctrl+left/right in terminal, just some apple stuff!\nbind '\"\\e[5C\": forward-word'\nbind '\"\\e[5D\": backward-word'\n# bindings to move 1 word left/right with ctrl+left/right in iTerm2, just some apple stuff!\nbind '\"\\e[1;5C\": forward-word'\nbind '\"\\e[1;5D\": backward-word'\n source ~/.bashrc" }, { "answer_id": 63715149, "author": "ubershmekel", "author_id": 177498, "author_profile": "https://Stackoverflow.com/users/177498", "pm_score": 2, "selected": false, "text": "Option-left = \\033b\nOption-right = \\033e\n option-right \\033f" }, { "answer_id": 69114598, "author": "conny", "author_id": 23023, "author_profile": "https://Stackoverflow.com/users/23023", "pm_score": -1, "selected": false, "text": "B W b w v----v- bash jumps here\n$ vim some-folder/what.txt_<- jump left twice from here\n ^---^- zsh jumps here by default\n # Place in your profile init script, e.g. `~/.zshrc`\nautoload -U select-word-style\nselect-word-style bash\n\n" }, { "answer_id": 73670596, "author": "thiagowfx", "author_id": 1745064, "author_profile": "https://Stackoverflow.com/users/1745064", "pm_score": 1, "selected": false, "text": "bash ~/.inputrc # macOS Option + Left/Right arrow keys to move the cursor wordwise\n\"\\e\\e[C\": forward-word\n\"\\e\\e[D\": backward-word\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
81,280
<p>The question says it all basically. </p> <p>I want in a </p> <pre><code>class MyClass </code></pre> <p>to listen to a routed event. Can it be done ?</p>
[ { "answer_id": 81590, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 2, "selected": true, "text": "EventManager.RegisterClassHandler ( typeof ( MyClass )......\n EventManager.RegisterClassHandler ( typeof ( TheClassThatOwnedTheEvent )\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
81,283
<p>How do people usually detect the MIME type of an uploaded file using ASP.NET?</p>
[ { "answer_id": 81312, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 6, "selected": true, "text": "<asp:FileUpload ID=\"FileUpload1\" runat=\"server\" />\n string contentType = FileUpload1.PostedFile.ContentType\n" }, { "answer_id": 1238450, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "using System.Runtime.InteropServices;\n\n[DllImport(\"urlmon.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]\nstatic extern int FindMimeFromData(IntPtr pBC,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,\n [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,\n int cbSize,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,\n int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved);\n\npublic static string getMimeFromFile(HttpPostedFile file)\n{\n IntPtr mimeout;\n\n int MaxContent = (int)file.ContentLength;\n if (MaxContent > 4096) MaxContent = 4096;\n\n byte[] buf = new byte[MaxContent];\n file.InputStream.Read(buf, 0, MaxContent);\n int result = FindMimeFromData(IntPtr.Zero, file.FileName, buf, MaxContent, null, 0, out mimeout, 0);\n\n if (result != 0)\n {\n Marshal.FreeCoTaskMem(mimeout);\n return \"\";\n }\n\n string mime = Marshal.PtrToStringUni(mimeout);\n Marshal.FreeCoTaskMem(mimeout);\n\n return mime.ToLower();\n}\n" }, { "answer_id": 72055878, "author": "Morten Brudvik", "author_id": 847570, "author_profile": "https://Stackoverflow.com/users/847570", "pm_score": 0, "selected": false, "text": "public string GetMimeType(string filePath)\n{\n var provider = new FileExtensionContentTypeProvider();\n\n if (!provider.TryGetContentType(filePath, out var contentType))\n contentType = \"application/octet-stream\"; // fallback: unknown binary type\n \n return contentType;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15396/" ]
81,285
<p>I re-image one of my machines regularly; and have a script that I run after the OS install completes to configure my machine; such that it works how I like.</p> <p>I happen to have my data on another drive...and I'd like to add code to my script to change the location of the Documents directory from "C:\Users\bryansh\Documents" to "D:\Users\bryansh\Documents".</p> <p>Does anybody have any insight, before I fire up regmon and really roll up my sleeves?</p>
[ { "answer_id": 81312, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 6, "selected": true, "text": "<asp:FileUpload ID=\"FileUpload1\" runat=\"server\" />\n string contentType = FileUpload1.PostedFile.ContentType\n" }, { "answer_id": 1238450, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "using System.Runtime.InteropServices;\n\n[DllImport(\"urlmon.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]\nstatic extern int FindMimeFromData(IntPtr pBC,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,\n [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,\n int cbSize,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,\n int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved);\n\npublic static string getMimeFromFile(HttpPostedFile file)\n{\n IntPtr mimeout;\n\n int MaxContent = (int)file.ContentLength;\n if (MaxContent > 4096) MaxContent = 4096;\n\n byte[] buf = new byte[MaxContent];\n file.InputStream.Read(buf, 0, MaxContent);\n int result = FindMimeFromData(IntPtr.Zero, file.FileName, buf, MaxContent, null, 0, out mimeout, 0);\n\n if (result != 0)\n {\n Marshal.FreeCoTaskMem(mimeout);\n return \"\";\n }\n\n string mime = Marshal.PtrToStringUni(mimeout);\n Marshal.FreeCoTaskMem(mimeout);\n\n return mime.ToLower();\n}\n" }, { "answer_id": 72055878, "author": "Morten Brudvik", "author_id": 847570, "author_profile": "https://Stackoverflow.com/users/847570", "pm_score": 0, "selected": false, "text": "public string GetMimeType(string filePath)\n{\n var provider = new FileExtensionContentTypeProvider();\n\n if (!provider.TryGetContentType(filePath, out var contentType))\n contentType = \"application/octet-stream\"; // fallback: unknown binary type\n \n return contentType;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211367/" ]
81,294
<pre><code>struct foo { unsigned x:1; } f; printf("%d\n", (int)sizeof(f.x = 1)); </code></pre> <p>What is the expected output and why? Taking the size of a bitfield lvalue directly isn't allowed. But by using the assignment operator, it seems we can still take the size of a bitfield type.</p> <p>What is the "size of a bitfield in bytes"? Is it the size of the storage unit holding the bitfield? Is it the number of bits taken up by the bf rounded up to the nearest byte count?</p> <p>Or is the construct undefined behavior because there is nothing in the standard that answers the above questions? Multiple compilers on the same platform are giving me inconsistent results.</p>
[ { "answer_id": 81348, "author": "Jason Dagit", "author_id": 5113, "author_profile": "https://Stackoverflow.com/users/5113", "pm_score": 0, "selected": false, "text": "(f.x = 1)\n sizeof( f.x = 1)\n" }, { "answer_id": 81407, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "sizeof( f.x = 1)\n" }, { "answer_id": 81411, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 1, "selected": false, "text": "sizeof sizeof(f.x = 1) unsigned int unsigned char" }, { "answer_id": 81413, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 0, "selected": false, "text": "(f.x = 1)\n unsigned x:1\n unsigned x:12\n" }, { "answer_id": 81577, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 0, "selected": false, "text": "struct foo { unsigned x:12} f;\n f.x = 1;\n int a, b, c;\na = b = c = 1;\n a = ( b = ( c = 1 ) )\n sizeof ( f.x = 1)\n" }, { "answer_id": 83343, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 2, "selected": false, "text": "sizeof sizeof sizeof _Bool int signed int unsigned int int unsigned int int sizeof(int)" }, { "answer_id": 84202, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "char ch;\nsizeof ch;\n" }, { "answer_id": 84361, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 3, "selected": true, "text": "sizeof" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
81,295
<p>I have a webservice that that uses message layer security with X.509 certificates in WSE 3.0. The service uses a X509v3 policy to sign various elements in the soapheader.</p> <p>I need to do some custom checks on the certificates so I've tried to implement a custom X509SecurityTokenManager and added a section in web.config.</p> <p>When I call the service with my Wseproxy I would expect a error (NotImplementedException) but the call goes trough and, in the example below, "foo" is printed at the console.</p> <p>The question is: What have missed? The binarySecurityTokenManager type in web.config matches the full classname of RDI.Server.X509TokenManager. X509TokenManager inherits from X509SecurityTokenManager (altough methods are just stubs).</p> <pre><code>using System; using System.Xml; using System.Security.Permissions; using System.Security.Cryptography; using Microsoft.Web.Services3; using Microsoft.Web.Services3.Security.Tokens; namespace RDI.Server { [SecurityPermissionAttribute(SecurityAction.Demand,Flags = SecurityPermissionFlag.UnmanagedCode)] public class X509TokenManager : Microsoft.Web.Services3.Security.Tokens.X509SecurityTokenManager { public X509TokenManager() : base() { throw new NotImplementedException("Stub"); } public X509TokenManager(XmlNodeList configData) : base(configData) { throw new NotImplementedException("Stub"); } protected override void AuthenticateToken(X509SecurityToken token) { base.AuthenticateToken(token); throw new NotImplementedException("Stub"); } } } </code></pre> <p>The first few lines of my web.config, edited for brevity</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt;&lt;configSections&gt;&lt;section name="microsoft.web.services3" type="..." /&gt; &lt;/configSections&gt; &lt;microsoft.web.services3&gt; &lt;policy fileName="wse3policyCache.config" /&gt; &lt;security&gt; &lt;binarySecurityTokenManager&gt; &lt;add type="RDI.Server.X509TokenManager" valueType="http://docs.oasis-open.org/..." /&gt; &lt;/binarySecurityTokenManager&gt; &lt;/security&gt; &lt;/microsoft.web.services3&gt;` </code></pre> <p>(Btw, how do one format xml nicely here at stackoverflow?)</p> <pre><code>Administration.AdministrationWse test = new TestConnector.Administration.AdministrationWse(); X509Certificate2 cert = GetCert("RDIDemoUser2"); X509SecurityToken x509Token = new X509SecurityToken(cert); test.SetPolicy("X509"); test.SetClientCredential(x509Token); string message = test.Ping("foo"); Console.WriteLine(message); </code></pre> <p>I'm stuck at .NET 2.0 (VS2005) for the time being so I presume WCF is out of the question, otherwise interoperability isn't a problem, as I will have control of both clients and services in the system.</p>
[ { "answer_id": 92102, "author": "Carl-Johan", "author_id": 15406, "author_profile": "https://Stackoverflow.com/users/15406", "pm_score": 1, "selected": false, "text": " <soapServerProtocolFactory type=\"Microsoft.Web.Services3.WseProtocolFactory, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n <soapExtensionImporterTypes>\n <add type=\"Microsoft.Web.Services3.Description.WseExtensionImporter, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n </soapExtensionImporterTypes>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15406/" ]
81,306
<p>We're currently having a debate whether it's better to throw faults over a WCF channel, versus passing a message indicating the status or the response from a service.</p> <p>Faults come with built-in support from WCF where by you can use the built-in error handlers and react accordingly. This, however, carries overhead as throwing exceptions in .NET can be quite costly.</p> <p>Messages can contain the necessary information to determine what happened with your service call without the overhead of throwing an exception. It does however need several lines of repetitive code to analyze the message and determine actions following its contents.</p> <p>We took a stab at creating a generic message object we could utilize in our services, and this is what we came up with:</p> <pre><code>public class ReturnItemDTO&lt;T&gt; { [DataMember] public bool Success { get; set; } [DataMember] public string ErrorMessage { get; set; } [DataMember] public T Item { get; set; } } </code></pre> <p>If all my service calls return this item, I can consistently check the "Success" property to determine if all went well. I then have an error message string in the event indicating something went wrong, and a generic item containing a Dto if needed.</p> <p>The exception information will have to be logged away to a central logging service and not passed back from the service.</p> <p>Thoughts? Comments? Ideas? Suggestions?</p> <p><strong>Some further clarification on my question</strong></p> <p>An issue I'm having with fault contracts is communicating business rules.</p> <p>Like, if someone logs in, and their account is locked, how do I communicate that? Their login obviously fails, but it fails due to the reason "Account Locked".</p> <p>So do I:</p> <p>A) use a boolean, throw Fault with message account locked</p> <p>B) return AuthenticatedDTO with relevant information</p>
[ { "answer_id": 12576782, "author": "Despertar", "author_id": 1160036, "author_profile": "https://Stackoverflow.com/users/1160036", "pm_score": 3, "selected": false, "text": "result = CallMethod();\nif (!result.Success) handleError();\n\nresult = CallAnotherMethod();\nif (!result.Success) handleError();\n\nresult = NotAgain();\nif (!result.Success) handleError();\n try \n{\n CallMethod();\n CallAnotherMethod();\n NotAgain();\n}\ncatch (Exception e)\n{\n handleError();\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15360/" ]
81,317
<p>I have been making a little toy web application in C# along the lines of Rob Connery's Asp.net MVC storefront.</p> <p>I find that I have a repository interface, call it IFooRepository, with methods, say</p> <pre><code>IQueryable&lt;Foo&gt; GetFoo(); void PersistFoo(Foo foo); </code></pre> <p>And I have three implementations of this: ISqlFooRepository, IFileFooRepostory, and IMockFooRepository.</p> <p>I also have some test cases. What I would like to do, and haven't worked out how to do yet, is to run the same test cases against each of these three implementations, and have a green tick for each test pass on each interface type.</p> <p>e.g.</p> <pre><code>[TestMethod] Public void GetFoo_NotNull_Test() { IFooRepository repository = GetRepository(); var results = repository. GetFoo(); Assert.IsNotNull(results); } </code></pre> <p>I want this test method to be run three times, with some variation in the environment that allows it to get three different kinds of repository. At present I have three cut-and-pasted test classes that differ only in the implementation of the private helper method IFooRepository GetRepository(); Obviously, this is smelly.</p> <p>However, I cannot just remove duplication by consolidating the cut and pasted methods, since they need to be present, public and marked as test for the test to run.</p> <p>I am using the Microsoft testing framework, and would prefer to stay with it if I can. But a suggestion of how to do this in, say, MBUnit would also be of some interest.</p>
[ { "answer_id": 81326, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "[RowTest]\n[Row(new ThisRepository())]\n[Row(new ThatRepository())]\nPublic void GetFoo_NotNull_Test(IFooRepository repository)\n{\n var results = repository.GetFoo();\n Assert.IsNotNull(results);\n}\n" }, { "answer_id": 81395, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 1, "selected": false, "text": "private IRepository GetRepository(RepositoryType repositoryType)\n{\n switch (repositoryType)\n { \n case RepositoryType.Sql:\n // return a SQL repository\n case RepositoryType.Mock:\n // return a mock repository\n // etc\n }\n}\n\nprivate void TestGetFooNotNull(RepositoryType repositoryType)\n{\n IFooRepository repository = GetRepository(repositoryType);\n var results = repository.GetFoo();\n Assert.IsNotNull(results);\n}\n\n[TestMethod]\npublic void GetFoo_NotNull_Sql()\n{\n this.TestGetFooNotNull(RepositoryType.Sql);\n}\n\n[TestMethod]\npublic void GetFoo_NotNull_File()\n{\n this.TestGetFooNotNull(RepositoryType.File);\n}\n\n[TestMethod]\npublic void GetFoo_NotNull_Mock()\n{\n this.TestGetFooNotNull(RepositoryType.Mock);\n}\n" }, { "answer_id": 81810, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 0, "selected": false, "text": "[TestMethod]\npublic void GetFoo_NotNull_Test_ForFile()\n{ \n GetFoo_NotNull(new FileRepository().GetRepository());\n}\n\n[TestMethod]\npublic void GetFoo_NotNull_Test_ForSql()\n{ \n GetFoo_NotNull(new SqlRepository().GetRepository());\n}\n\n\nprivate void GetFoo_NotNull(IFooRepository repository)\n{\n var results = repository. GetFoo(); \n Assert.IsNotNull(results);\n}\n" }, { "answer_id": 82513, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 0, "selected": false, "text": "[RowTest]\n[Row(RepositoryType.Sql)]\n[Row(RepositoryType.Mock)]\npublic void TestGetFooNotNull(RepositoryType repositoryType)\n{\n IFooRepository repository = GetRepository(repositoryType);\n var results = repository.GetFoo();\n Assert.IsNotNull(results);\n}\n public abstract class TestBase\n{\n protected int foo = 0;\n\n [TestMethod]\n public void TestUnderTen()\n {\n Assert.IsTrue(foo < 10);\n }\n\n [TestMethod]\n public void TestOver2()\n {\n Assert.IsTrue(foo > 2);\n }\n}\n\n[TestClass]\npublic class TestA: TestBase\n{\n public TestA()\n {\n foo = 4;\n }\n}\n\n[TestClass]\npublic class TestB: TestBase\n{\n public TestB()\n {\n foo = 6;\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5599/" ]
81,323
<p>Is there a way to change the encoding used by the String(byte[]) constructor ?</p> <p>In my own code I use String(byte[],String) to specify the encoding but I am using an external library that I cannot change.</p> <pre><code>String src = "with accents: é à"; byte[] bytes = src.getBytes("UTF-8"); System.out.println("UTF-8 decoded: "+new String(bytes,"UTF-8")); System.out.println("Default decoded: "+new String(bytes)); </code></pre> <p>The output for this is :</p> <pre>UTF-8 decoded: with accents: é à Default decoded: with accents: é à </pre> <p>I have tried changing the system property <code>file.encoding</code> but it does not work.</p>
[ { "answer_id": 81366, "author": "Mat Mannion", "author_id": 6282, "author_profile": "https://Stackoverflow.com/users/6282", "pm_score": 4, "selected": true, "text": "java -Dfile.encoding=UTF-8 ...\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7198/" ]
81,346
<p>I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times.</p> <p>Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted and the value is an Integer that's incremented each time a token of the word is found.</p> <p>In Perl, incrementing such a value would be trivially easy:</p> <pre><code>$map{$word}++; </code></pre> <p>But in Java, it's much more complicated. Here the way I'm currently doing it:</p> <pre><code>int count = map.containsKey(word) ? map.get(word) : 0; map.put(word, count + 1); </code></pre> <p>Which of course relies on the autoboxing feature in the newer Java versions. I wonder if you can suggest a more efficient way of incrementing such a value. Are there even good performance reasons for eschewing the Collections framework and using a something else instead?</p> <p>Update: I've done a test of several of the answers. See below.</p>
[ { "answer_id": 81401, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "Integer" }, { "answer_id": 81417, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 2, "selected": false, "text": "\n class My{\n String word;\n int count;\n }\n \n\n HashMultiset s = new HashMultiset();\n s.add(\"word\");\n s.add(\"word\");\n System.out.println(\"\"+s.count(\"word\") );\n\n" }, { "answer_id": 81522, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 5, "selected": false, "text": " final ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String, AtomicLong>();\n map.putIfAbsent(\"foo\", new AtomicLong(0));\n map.get(\"foo\").incrementAndGet();\n 1 foo" }, { "answer_id": 81550, "author": "Philip Helger", "author_id": 15254, "author_profile": "https://Stackoverflow.com/users/15254", "pm_score": 4, "selected": false, "text": "class MutableInt {\n int value = 0;\n public void inc () { ++value; }\n public int get () { return value; }\n}\n...\nMap<String,MutableInt> map = new HashMap<String,MutableInt> ();\nMutableInt value = map.get (key);\nif (value == null) {\n value = new MutableInt ();\n map.put (key, value);\n} else {\n value.inc ();\n}\n" }, { "answer_id": 81722, "author": "Glever", "author_id": 15504, "author_profile": "https://Stackoverflow.com/users/15504", "pm_score": 3, "selected": false, "text": " Integer count = map.get(word);\n if(count == null){\n count = 0;\n }\n map.put(word, count + 1);\n" }, { "answer_id": 81765, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 5, "selected": false, "text": "containsKey get get null NullPointerException null HashMap nulls null containsKey get null null Hashtable get final null put 1 final map.put(new Integer(1 + i.getValue()));" }, { "answer_id": 85007, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 3, "selected": false, "text": "static class MutableInt {\n int value = 1;\n void inc() { ++value; }\n int get() { return value; }\n}\n...\nMap<String,MutableInt> map = new HashMap<String,MutableInt>();\nMutableInt value = map.get(key);\nif (value == null) {\n value = new MutableInt();\n map.put(key, value);\n} else {\n value.inc();\n}\n" }, { "answer_id": 85342, "author": "Chris Nokleberg", "author_id": 8902, "author_profile": "https://Stackoverflow.com/users/8902", "pm_score": 5, "selected": false, "text": "Multiset bag = Multisets.newHashMultiset();\nString word = \"foo\";\nbag.add(word);\nbag.add(word);\nSystem.out.println(bag.count(word)); // Prints 2\n HashMap<E, AtomicInteger>" }, { "answer_id": 107987, "author": "gregory", "author_id": 10204, "author_profile": "https://Stackoverflow.com/users/10204", "pm_score": 10, "selected": true, "text": "final import java.util.HashMap;\nimport java.util.Map;\n...\nMap<String, Integer> freq = new HashMap<String, Integer>();\n...\nint count = freq.containsKey(word) ? freq.get(word) : 0;\nfreq.put(word, count + 1);\n import java.util.HashMap;\nimport java.util.Map;\n...\nMap<String, Integer> freq = new HashMap<String, Integer>();\n...\nInteger count = freq.get(word);\nif (count == null) {\n freq.put(word, 1);\n}\nelse {\n freq.put(word, count + 1);\n}\n import java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.atomic.AtomicLong;\n...\nfinal ConcurrentMap<String, AtomicLong> map = \n new ConcurrentHashMap<String, AtomicLong>();\n...\nmap.putIfAbsent(word, new AtomicLong(0));\nmap.get(word).incrementAndGet();\n import gnu.trove.TObjectIntHashMap;\n...\nTObjectIntHashMap<String> freq = new TObjectIntHashMap<String>();\n...\nfreq.adjustOrPutValue(word, 1, 1);\n import java.util.HashMap;\nimport java.util.Map;\n...\nclass MutableInt {\n int value = 1; // note that we start at 1 since we're counting\n public void increment () { ++value; }\n public int get () { return value; }\n}\n...\nMap<String, MutableInt> freq = new HashMap<String, MutableInt>();\n...\nMutableInt count = freq.get(word);\nif (count == null) {\n freq.put(word, new MutableInt());\n}\nelse {\n count.increment();\n}\n" }, { "answer_id": 855154, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 1, "selected": false, "text": "TreeMap update public TreeMap<K, V> update(final K k, final F<V, V> f)\n import static fj.data.TreeMap.empty;\nimport static fj.function.Integers.add;\nimport static fj.pre.Ord.stringOrd;\nimport fj.data.TreeMap;\n\npublic class TreeMap_Update\n {public static void main(String[] a)\n {TreeMap<String, Integer> map = empty(stringOrd);\n map = map.set(\"foo\", 1);\n map = map.update(\"foo\", add.f(1));\n System.out.println(map.get(\"foo\").some());}}\n" }, { "answer_id": 4257986, "author": "the felis leo", "author_id": 517668, "author_profile": "https://Stackoverflow.com/users/517668", "pm_score": 2, "selected": false, "text": "Map map = new HashMap ();\n\nMutableInt newValue = new MutableInt (1); // default = inc\nMutableInt oldValue = map.put (key, newValue);\nif (oldValue != null) {\n newValue.add(oldValue); // old + inc\n}\n Map map = new HashMap ();\n\nMutableInt newValue = new MutableInt (0); // default\nMutableInt oldValue = map.put (key, newValue);\nif (oldValue != null) {\n newValue.setValue(oldValue + 1); // old + inc\n}\n Map map = new HashMap ();\nfinal int defaut = 0;\nfinal int inc = 1;\n\nMutableInt oldValue = new MutableInt (default);\nwhile(true) {\n MutableInt newValue = oldValue;\n\n oldValue = map.put (key, newValue); // insert or...\n if (oldValue != null) {\n newValue.setValue(oldValue + inc); // ...update\n\n oldValue.setValue(default); // reuse\n } else\n oldValue = new MutableInt (default); // renew\n }\n}\n" }, { "answer_id": 4283959, "author": "the felis leo", "author_id": 521173, "author_profile": "https://Stackoverflow.com/users/521173", "pm_score": 2, "selected": false, "text": "Entry<K,V> getOrPut(K); HashSet<Entry> get(K) (new MyHashSet()).get(k).increment();" }, { "answer_id": 11287489, "author": "Eamonn O'Brien-Strain", "author_id": 978525, "author_profile": "https://Stackoverflow.com/users/978525", "pm_score": 2, "selected": false, "text": "Map<String,int[]> map = new HashMap<String,int[]>();\n...\nint[] value = map.get(key);\nif (value == null) \n map.put(key, new int[]{1} );\nelse\n ++value[0];\n TObjectIntHashMap adjustOrPutValue TObjectIntHashMap<String> map = new TObjectIntHashMap<String>();\n...\nmap.adjustOrPutValue(key, 1, 1);\n" }, { "answer_id": 12266382, "author": "H6.", "author_id": 419863, "author_profile": "https://Stackoverflow.com/users/419863", "pm_score": 5, "selected": false, "text": "AtomicLongMap<String> map = AtomicLongMap.create();\n[...]\nmap.getAndIncrement(word);\n map.getAndAdd(word, 112L); \n" }, { "answer_id": 18792535, "author": "Craig P. Motlin", "author_id": 23572, "author_profile": "https://Stackoverflow.com/users/23572", "pm_score": 1, "selected": false, "text": "HashBag HashBag MutableObjectIntMap Counter HashBag Collection MutableBag<String> bag =\n HashBag.newBagWith(\"one\", \"two\", \"two\", \"three\", \"three\", \"three\");\n\nAssert.assertEquals(3, bag.occurrencesOf(\"three\"));\n\nbag.add(\"one\");\nAssert.assertEquals(2, bag.occurrencesOf(\"one\"));\n\nbag.addOccurrences(\"one\", 4);\nAssert.assertEquals(6, bag.occurrencesOf(\"one\"));\n" }, { "answer_id": 25354509, "author": "leventov", "author_id": 648955, "author_profile": "https://Stackoverflow.com/users/648955", "pm_score": 6, "selected": false, "text": " time, ms\nkolobokeCompile 18.8\nkoloboke 19.8\ntrove 20.8\nfastutil 22.7\nmutableInt 24.3\natomicInteger 25.3\neclipse 26.9\nhashMap 28.0\nhppc 33.6\nhppcRt 36.5\n" }, { "answer_id": 33711386, "author": "off99555", "author_id": 2593810, "author_profile": "https://Stackoverflow.com/users/2593810", "pm_score": 6, "selected": false, "text": "Map<String, Integer> map = new HashMap<>();\nString key = \"a random key\";\nint count = map.getOrDefault(key, 0); // ensure count will be one of 0,1,2,3,...\nmap.put(key, count + 1);\n map.merge(key, 1, (a,b) -> a+b);\n" }, { "answer_id": 37296257, "author": "MGoksu", "author_id": 3721429, "author_profile": "https://Stackoverflow.com/users/3721429", "pm_score": 1, "selected": false, "text": "BiFunction public static Map<String, Integer> strInt = new HashMap<String, Integer>();\n\npublic static void main(String[] args) {\n BiFunction<Integer, Integer, Integer> bi = (x,y) -> {\n if(x == null)\n return y;\n return x+y;\n };\n strInt.put(\"abc\", 0);\n\n\n strInt.merge(\"abc\", 1, bi);\n strInt.merge(\"abc\", 1, bi);\n strInt.merge(\"abc\", 1, bi);\n strInt.merge(\"abcd\", 1, bi);\n\n System.out.println(strInt.get(\"abc\"));\n System.out.println(strInt.get(\"abcd\"));\n}\n 3\n1\n" }, { "answer_id": 37439971, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 4, "selected": false, "text": "Map final Map<String,AtomicLong> map = new ConcurrentHashMap<>();\nmap.computeIfAbsent(\"A\", k->new AtomicLong(0)).incrementAndGet();\nmap.computeIfAbsent(\"B\", k->new AtomicLong(0)).incrementAndGet();\nmap.computeIfAbsent(\"A\", k->new AtomicLong(0)).incrementAndGet(); //[A=2, B=1]\n computeIfAbsent AtomicLong" }, { "answer_id": 42648785, "author": "LE GALL Benoît", "author_id": 244911, "author_profile": "https://Stackoverflow.com/users/244911", "pm_score": 9, "selected": false, "text": "Map::merge myMap.merge(key, 1, Integer::sum)\n" }, { "answer_id": 48715920, "author": "Keith", "author_id": 43370, "author_profile": "https://Stackoverflow.com/users/43370", "pm_score": -1, "selected": false, "text": "dev map = new HashMap<String, Integer>()\nmap.put(\"key1\", 3)\n\nmap.merge(\"key1\", 1) {a, b -> a + b}\nmap.merge(\"key2\", 1) {a, b -> a + b}\n" }, { "answer_id": 54507230, "author": "ggaugler", "author_id": 10429757, "author_profile": "https://Stackoverflow.com/users/10429757", "pm_score": -1, "selected": false, "text": "map.put(key, 1)\n map.put(key, map.get(key) + 1)\n" }, { "answer_id": 55341335, "author": "sudoz", "author_id": 4305743, "author_profile": "https://Stackoverflow.com/users/4305743", "pm_score": 3, "selected": false, "text": "Map.java map.put(key, map.getOrDefault(key, 0) + 1);\n" }, { "answer_id": 56712619, "author": "Assaduzzaman Assad", "author_id": 9809339, "author_profile": "https://Stackoverflow.com/users/9809339", "pm_score": -1, "selected": false, "text": "final ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String, AtomicLong>();\n map.computeIfAbsent(\"foo\", key -> new AtomicLong(0)).incrementAndGet();\n" }, { "answer_id": 57838567, "author": "Eugene Chung", "author_id": 968152, "author_profile": "https://Stackoverflow.com/users/968152", "pm_score": 3, "selected": false, "text": "Map.compute(num, (k, v) -> (v == null) ? 1 : v + 1);\n" }, { "answer_id": 68159505, "author": "Sarvar N", "author_id": 2490074, "author_profile": "https://Stackoverflow.com/users/2490074", "pm_score": 1, "selected": false, "text": "getOrDefault String s = \"abcdeff\";\ns.chars().mapToObj(c -> (char) c)\n .forEach(c -> {\n int count = countMap.getOrDefault(c, 0) + 1;\n countMap.put(c, count);\n });\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10204/" ]
81,347
<p>I have an asp.NET webapplication running in our datacenter in which we want the customer to logon with single sign-on. This would be very easy if we could use the IIS integrated security. However we can't do this. We don't have a trust to the domain controller of the customer. ANd we want to website to be available to the general internet. Only when people are connecting from within the clients network they should automatically login.</p> <p>What we have is a list of domain accounts and a way to query the DC via LDAP in asp.net code. When anonymous access is allowed in IIS, IIS never challenges the browser for credentials. And thus our application never gets the users credentials.</p> <p>Is there a way to force the browser into sending the credentials (and thus be able to use single sign-on) with IIS accepting anonymous request.</p> <p><strong>Update:</strong> </p> <p>I tried sending 401: unauthorized, www-authenticate: NTLM headers by myself. What happens next (as Fiddler tells me) is that IIS takes complete control and handles the complete chain of request. As I understand from various sources is that IIS takes the username, sends a challenge back to the browser. The browser returns with encrypted reponse and IIS connects to the domain controller to authenticate the user with this response.</p> <p>However in my scenario IIS is in a different windows domain than the clients and have no way to authenticate the users. For that reason building a seperate site with windows authenticaion enabaled isn't going to work either.</p> <p>For now I have to options left which I'm researching:</p> <ol> <li>Creating a domain trust between our hosting domain and the clients domain (our IT department isn'tto happy with this)</li> <li>Using a NTML proxy to forward the IIS authentication requests to the clients domain controller (we have a VPN connection available to connect via LDAP) </li> </ol>
[ { "answer_id": 84715, "author": "Greg", "author_id": 12601, "author_profile": "https://Stackoverflow.com/users/12601", "pm_score": -1, "selected": false, "text": "protected void Application_EndRequest(object sender, EventArgs e) {\n if (Context.Items[\"Send401\"] != null)\n {\n Response.StatusCode = 401;\n Response.StatusDescription = \"Unauthorized\";\n } }\n Context.Items[\"Send401\"] = true;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11548/" ]
81,350
<p>What are the private IP address ranges?</p>
[ { "answer_id": 81365, "author": "Sargun Dhillon", "author_id": 10432, "author_profile": "https://Stackoverflow.com/users/10432", "pm_score": 6, "selected": true, "text": " 10.0.0.0 - 10.255.255.255 (10/8 prefix)\n 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)\n 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11034/" ]
81,360
<p>I cannot find an elegant way to get the return value from a stored procedure when using TableAdapters.</p> <p>It appears the TableAdapter does not support SQL stored procedure return values when using a non-scalar stored procedure call. You'd expect the return value from the auto-generated function would be the return value from the stored procedure but it isn't (it is actually the number of rows affected). Although possible to use 'out' parameters and pass a variable as a ref to the auto generated functions it isn't a very clean solution.</p> <p>I have seen some ugly hacks on the web to solve this, but no decent solution. Any help would be appreciated.</p>
[ { "answer_id": 156145, "author": "Ty.", "author_id": 8873, "author_profile": "https://Stackoverflow.com/users/8873", "pm_score": 0, "selected": false, "text": "SET ROWCOUNT OFF\n\nBEGIN\n<Procedure Content>\nEND\n\nSET ROWCOUNT ON\n" }, { "answer_id": 158819, "author": "sharvell", "author_id": 23095, "author_profile": "https://Stackoverflow.com/users/23095", "pm_score": 1, "selected": false, "text": "string sql = @\"DECLARE @ret int \n EXEC @ret = SP_DoStuff 'parm1', 'parm2'\n SELECT @ret as ret\";\n\nDataSet ds = GetDatasetFromSQL(sql); //your sql to dataset code here...\n\nint resultCode = -1;\nint.TryParse(ds.Tables[ds.Tables.Count-1].Rows[0][0].ToString(), out resultCode); \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5217/" ]
81,361
<p>I have set up a repository using SVN and uploaded projects. There are multiple users working on these projects. But, not everyone requires access to all projects. I want to set up user permissions for each project.</p> <p>How can I achieve this?</p>
[ { "answer_id": 81457, "author": "Stephen Bailey", "author_id": 15385, "author_profile": "https://Stackoverflow.com/users/15385", "pm_score": 6, "selected": false, "text": "[users]\nUser1=password1\nUser2=password2\n [groups]\nallaccess = user1\nsomeaccess = user2\n [/]\n@allaccess = rw\n [/someproject]\n@someaccess = r\n" }, { "answer_id": 81468, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "[Users]\nusername = password\njohn = johns_password\nsteve = steves_password\n [general]\npassword-db = passwd\nauth-access=read\nauth-access=write\n passwd" }, { "answer_id": 83418, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": false, "text": "authz ###########################################################################\n# The content of this file always precedes the content of the\n# $REPOS/admin/acl_descriptions.txt file.\n# It describes the immutable permissions on main folders.\n###########################################################################\n[groups]\nsvnadmins = xxx,yyy,....\n\n[/]\n@svnadmins = rw\n* = r\n[/admin]\n@svnadmins = rw\n@projadmins = r\n* =\n\n[/admin/acl_descriptions.txt]\n@projadmins = rw\n authz \\conf\\authz authz /admin/acl_descriptions.txt [groups]\nprojadmins = zzzz\n authz authz" }, { "answer_id": 1793965, "author": "Chris Burgess", "author_id": 43034, "author_profile": "https://Stackoverflow.com/users/43034", "pm_score": 5, "selected": false, "text": "[repos:/path/to/dir/] # this won't work\n [repos:/path/to/dir] # this is right\n" }, { "answer_id": 61511926, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 0, "selected": false, "text": "[calc:/branches/calc/bug-142]\nharry = rw\nsally = r\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15425/" ]
81,392
<p>If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte"). </p> <pre><code>byte a = 23; byte b = 34; byte c = a + b; </code></pre> <p>In this example, the compile error is on the third line.</p>
[ { "answer_id": 81446, "author": "David Sykes", "author_id": 3154, "author_profile": "https://Stackoverflow.com/users/3154", "pm_score": 3, "selected": false, "text": "a b int int int int byte" }, { "answer_id": 81728, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "a + b\n (int)a + (int)b\n" }, { "answer_id": 73372404, "author": "Dean", "author_id": 8749628, "author_profile": "https://Stackoverflow.com/users/8749628", "pm_score": 0, "selected": false, "text": "a b int + + int byte" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7732/" ]
81,406
<p>Which parsers are available for parsing C# code?</p> <p>I'm looking for a C# parser that can be used in C# and give me access to line and file informations about each artefact of the analysed code.</p>
[ { "answer_id": 2214810, "author": "Dinis Cruz", "author_id": 262379, "author_profile": "https://Stackoverflow.com/users/262379", "pm_score": 2, "selected": false, "text": " public void updateView(string sourceCode)\n { \n var ast = new Ast_CSharp(sourceCode);\n ast_TreeView.show_Ast(ast);\n types_TreeView.show_List(ast.astDetails.Types, \"Text\");\n usingDeclarations_TreeView.show_List(ast.astDetails.UsingDeclarations,\"Text\");\n methods_TreeView.show_List(ast.astDetails.Methods,\"Text\");\n fields_TreeView.show_List(ast.astDetails.Fields,\"Text\");\n properties_TreeView.show_List(ast.astDetails.Properties,\"Text\");\n comments_TreeView.show_List(ast.astDetails.Comments,\"Text\");\n\n rewritenCSharpCode_SourceCodeEditor.setDocumentContents(ast.astDetails.CSharpCode, \".cs\");\n rewritenVBNet_SourceCodeEditor.setDocumentContents(ast.astDetails.VBNetCode, \".vb\"); \n }\n" }, { "answer_id": 2408671, "author": "zproxy", "author_id": 94411, "author_profile": "https://Stackoverflow.com/users/94411", "pm_score": 3, "selected": false, "text": "var cp = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { \"CompilerVersion\", \"v3.5\" } });\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12248/" ]
81,410
<p>I've got a <a href="http://notebooks.readerville.com/" rel="noreferrer">site</a> that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limitation?</p>
[ { "answer_id": 81505, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 4, "selected": true, "text": "<div style=\"background:url('javascript:alert(this);');\" />\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6478/" ]
81,448
<p>In Oracle, what is the difference between :</p> <pre><code>CREATE TABLE CLIENT ( NAME VARCHAR2(11 BYTE), ID_CLIENT NUMBER ) </code></pre> <p>and</p> <pre><code>CREATE TABLE CLIENT ( NAME VARCHAR2(11 CHAR), -- or even VARCHAR2(11) ID_CLIENT NUMBER ) </code></pre>
[ { "answer_id": 81492, "author": "David Sykes", "author_id": 3154, "author_profile": "https://Stackoverflow.com/users/3154", "pm_score": 9, "selected": true, "text": "VARCHAR2(11 BYTE) VARCHAR2(11 CHAR)" }, { "answer_id": 67398489, "author": "Aman Singh Rajpoot", "author_id": 12937828, "author_profile": "https://Stackoverflow.com/users/12937828", "pm_score": 1, "selected": false, "text": "NAME VARCHAR2(11 BYTE) NAME NAME VARCHAR2(11 CHAR) NAME BYTE BYTE CHAR NAME VARCHAR2(4000 BYTE) NAME BYTES" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
81,449
<p>In a server-side application running on Tomcat, I am generating full HTML pages (with header) based on random user-requested sites pulled down from the Internet. The client-side application uses asynchronous callbacks for requesting processing of a particular web page. Since processing can take a while, I want to inform the user about progress via polling, hence the callbacks.</p> <p>On server-side, after the web page is retrieved, it is processed and an "enhanced" version is created. Then this version has to go back to the user. Displaying the page as part of the page of the client-side application is not an option.</p> <p>Currently, the server generates a temporary file and sends back a link to it. This is clearly suboptimal.</p> <p>The next best solution I can come up with inolves creating a caching-DB that stores the HTML content together with its md5-sums or sha1-ids and then sends back a link to a servlet, with the hash-ID as an argument. The servlet then requests the site from the caching-DB.</p> <p>Is there any better solution? If not, which DB-backend would you propose? I'm thinking of SQLite. Part of the problem to be solved is: how do I push a page <code>&lt;html&gt;</code> to <code>&lt;/html&gt;</code> back to client side?</p>
[ { "answer_id": 81492, "author": "David Sykes", "author_id": 3154, "author_profile": "https://Stackoverflow.com/users/3154", "pm_score": 9, "selected": true, "text": "VARCHAR2(11 BYTE) VARCHAR2(11 CHAR)" }, { "answer_id": 67398489, "author": "Aman Singh Rajpoot", "author_id": 12937828, "author_profile": "https://Stackoverflow.com/users/12937828", "pm_score": 1, "selected": false, "text": "NAME VARCHAR2(11 BYTE) NAME NAME VARCHAR2(11 CHAR) NAME BYTE BYTE CHAR NAME VARCHAR2(4000 BYTE) NAME BYTES" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11797/" ]
81,451
<p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p> <p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
[ { "answer_id": 81479, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 1, "selected": false, "text": "class MyModel(db.Model):\n blob = db.BlobProperty()\n\nobj = MyModel()\nobj.blob = db.Blob( file_contents )\n" }, { "answer_id": 534354, "author": "Joe Petrini", "author_id": 53488, "author_profile": "https://Stackoverflow.com/users/53488", "pm_score": 2, "selected": false, "text": "<form encoding=\"multipart/form-data\" action=\"/upload\">\n <form enctype=\"multipart/form-data\" action=\"/upload\">\n" }, { "answer_id": 1240820, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<form action=\"/testservelet\" method=\"get\" enctype=\"multipart/form-data\">\n <div>\n Myfile:<input type=\"file\" name=\"file\" size=\"50\"/>\n </div>\n\n <div>\n <input type=\"submit\" value=\"Upload file\">\n </div>\n</form>\n" }, { "answer_id": 3050807, "author": "Bili", "author_id": 331191, "author_profile": "https://Stackoverflow.com/users/331191", "pm_score": 3, "selected": false, "text": "<form enctype=\"multipart/form-data\" action=\"/upload\" method=\"post\" > \n<input type=\"file\" name=\"myfile\" /> \n<input type=\"submit\" /> \n</form> \n file_contents = self.request.POST.get('myfile').file.read() \n" }, { "answer_id": 3545032, "author": "Honza Pokorny", "author_id": 244182, "author_profile": "https://Stackoverflow.com/users/244182", "pm_score": 0, "selected": false, "text": "<form method=\"post\" action=\"/upload\" enctype=\"multipart/form-data\">\n <input type=\"file\" name=\"img\" />\n ...\n</form>\n img img_contents = self.request.get('img')\n img_contents str() db.Blob()" }, { "answer_id": 4787543, "author": "101010", "author_id": 451007, "author_profile": "https://Stackoverflow.com/users/451007", "pm_score": 7, "selected": true, "text": "blob_key = str(urllib.unquote(blob_key))\n self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)\n import os\nimport urllib\n\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import blobstore_handlers\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass MainHandler(webapp.RequestHandler):\n def get(self):\n upload_url = blobstore.create_upload_url('/upload')\n self.response.out.write('<html><body>')\n self.response.out.write('<form action=\"%s\" method=\"POST\" enctype=\"multipart/form-data\">' % upload_url)\n self.response.out.write(\"\"\"Upload File: <input type=\"file\" name=\"file\"><br> <input type=\"submit\" name=\"submit\" value=\"Submit\"> </form></body></html>\"\"\")\n\n for b in blobstore.BlobInfo.all():\n self.response.out.write('<li><a href=\"/serve/%s' % str(b.key()) + '\">' + str(b.filename) + '</a>')\n\nclass UploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n upload_files = self.get_uploads('file')\n blob_info = upload_files[0]\n self.redirect('/')\n\nclass ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):\n def get(self, blob_key):\n blob_key = str(urllib.unquote(blob_key))\n if not blobstore.get(blob_key):\n self.error(404)\n else:\n self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)\n\ndef main():\n application = webapp.WSGIApplication(\n [('/', MainHandler),\n ('/upload', UploadHandler),\n ('/serve/([^/]+)?', ServeHandler),\n ], debug=True)\n run_wsgi_app(application)\n\nif __name__ == '__main__':\n main()\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
81,472
<p>I am developing an ASP.NET mobile website using .NET 3.5 and mobile controls that come with the framework. I have a login form where the system will authenticate the user so he/she can access certain restricted pages. </p> <p>In a standard ASP.NET website, I can use a session to store some flag after a user had logined, but I wonder can I do the same for the mobile version? Is session variable (or cookies) being support by those mobile device's browser? Is there any standard pratice also on doing authentication for mobile pages?</p>
[ { "answer_id": 94301, "author": "Shane Breatnach", "author_id": 10264, "author_profile": "https://Stackoverflow.com/users/10264", "pm_score": 0, "selected": false, "text": "<sessionState cookieless=\"true\" />\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14790/" ]
81,491
<p>Has anyone gotten VisualWorks running under OpenBSD? It's not an officially supported platform, but one of the Cincom guys was telling me that it should be able to run under a linux compatibility mode. How did you set it up?</p> <p>I already have Squeak running without a problem, so I'm not looking for an alternative. I specifically need to run VisualWorks's Web Velocity for a project.</p> <p>Thanks,</p>
[ { "answer_id": 82334, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "# sysctl kern.emul.linux=1\n" }, { "answer_id": 959964, "author": "dwc", "author_id": 57301, "author_profile": "https://Stackoverflow.com/users/57301", "pm_score": 3, "selected": true, "text": "kern.emul.linux=1" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2766176/" ]
81,495
<p>I'm writing a J2SE desktop application that requires one of its components to be pluggable. I've already defined the Java interface for this plugin. The user should be able to select at runtime (via the GUI) which implementation of this interface they want to use (e.g. in an initialisation dialog). I envisage each plugin being packaged as a JAR file containing the implementing class plus any helper classes it may require.</p> <p>What's the best technology for doing this type of thing in a desktop Java app?</p>
[ { "answer_id": 81510, "author": "Andrew Swan", "author_id": 10433, "author_profile": "https://Stackoverflow.com/users/10433", "pm_score": 0, "selected": false, "text": "java.util.jar" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10433/" ]
81,497
<p>I need an encoder that can convert mp3 files to he-aac (aka aac+). So far the best one I have found is <a href="http://www.nero.com/eng/down-ndaudio.php" rel="nofollow noreferrer">nero aac encoder</a> . I have two problemes with it : - Only one input format : wav . It is a little bit slow to transform mp3 files to wav and then to he-aac. - a free license for <strong>non commercial</strong> use.</p> <p>Too bad ffmpeg does not support he-aac ... There is a commercial solution, <a href="https://flix.on2.com/" rel="nofollow noreferrer">on2 flix</a>, but it seems to be a golden hammer for the simple task I need to do.</p>
[ { "answer_id": 4600868, "author": "polemon", "author_id": 414121, "author_profile": "https://Stackoverflow.com/users/414121", "pm_score": 2, "selected": false, "text": "neroAacEnc .AAC .MP3 .WAV .WAV .MP3 .FLAC .AAC .FLAC #!/bin/zsh\n\nfor file in ${argv[*]}; do\n flac -d ${file}\n neroAacEnc -q 0.6 -if ${file%%.flac}.wav -of ${file%%.flac}.aac\n rm ${file%%.flac}.wav\ndone\n" }, { "answer_id": 8120392, "author": "freechelmi", "author_id": 1016264, "author_profile": "https://Stackoverflow.com/users/1016264", "pm_score": 2, "selected": false, "text": "accplus" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11897/" ]
81,520
<p>How can you suppress the <code>Terminated</code> message that comes up after you kill a process in a bash script?</p> <p>I tried <code>set +bm</code>, but that doesn't work.</p> <p>I know another solution involves calling <code>exec 2&gt; /dev/null</code>, but is that reliable? How do I reset it back so that I can continue to see stderr?</p>
[ { "answer_id": 81539, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 3, "selected": false, "text": "disown" }, { "answer_id": 81672, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 5, "selected": true, "text": "(script 2> /dev/null)\n exec 3>&2 # 3 is now a copy of 2\nexec 2> /dev/null # 2 now points to /dev/null\nscript # run script with redirected stderr\nexec 2>&3 # restore stderr to saved\nexec 3>&- # close saved version\n" }, { "answer_id": 4849503, "author": "MarcH", "author_id": 317623, "author_profile": "https://Stackoverflow.com/users/317623", "pm_score": 4, "selected": false, "text": "cat > silent.sh <<\"EOF\"\nsleep 100 &\nkill -INT $!\nsleep 1\nEOF\n\nsh silent.sh\n" }, { "answer_id": 5722874, "author": "Mark Edgar", "author_id": 129332, "author_profile": "https://Stackoverflow.com/users/129332", "pm_score": 7, "selected": false, "text": "stderr kill stderr kill wait kill $!\nwait $! 2>/dev/null\n kill wait kill $(jobs -rp)\nwait $(jobs -rp) 2>/dev/null\n" }, { "answer_id": 12198152, "author": "Ralph", "author_id": 1636189, "author_profile": "https://Stackoverflow.com/users/1636189", "pm_score": 2, "selected": false, "text": "$ sleep 3 &\n[1] 234\n<pressing enter a few times....>\n$\n$\n[1]+ Done sleep 3\n$\n $ (set +m; sleep 3 &)\n<again, pressing enter several times....>\n$\n$\n$\n$\n$\n" }, { "answer_id": 13223242, "author": "Coder of Salvation", "author_id": 1659796, "author_profile": "https://Stackoverflow.com/users/1659796", "pm_score": 2, "selected": false, "text": "killall -s SIGINT (yourprogram) \n" }, { "answer_id": 15300185, "author": "phily", "author_id": 2149422, "author_profile": "https://Stackoverflow.com/users/2149422", "pm_score": 0, "selected": false, "text": "sh -c 'cmd &' #!/bin/bash\n# ...\npid=\"`sh -c 'sleep 30 & echo ${!}' | head -1`\"\nkill \"$pid\"\n# ...\n\n# or put several cmds in sh -c '...' construct\nsh -c '\nsleep 30 &\npid=\"${!}\"\nsleep 5 \nkill \"${pid}\"\n'\n" }, { "answer_id": 16424178, "author": "J-o-h-n-", "author_id": 2359158, "author_profile": "https://Stackoverflow.com/users/2359158", "pm_score": 0, "selected": false, "text": "jobs 2>&1 >/dev/null while true; do echo $RANDOM; done | while read line\n do\n echo Random is $line the last jobid is $(jobs -lp)\n jobs 2>&1 >/dev/null\n sleep 3\n done\n" }, { "answer_id": 17257986, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "{ kill $! } 2>/dev/null\n { kill -9 $PID } 2>/dev/null\n" }, { "answer_id": 48726125, "author": "Al Joslin", "author_id": 2912739, "author_profile": "https://Stackoverflow.com/users/2912739", "pm_score": -1, "selected": false, "text": "function killCmd() {\n kill $1\n}\n\nkillCmd $somePID &\n" }, { "answer_id": 66355103, "author": "James Z.M. Gao", "author_id": 7704140, "author_profile": "https://Stackoverflow.com/users/7704140", "pm_score": 2, "selected": false, "text": "Terminated #!/bin/sh\n\n## assume script name is test.sh\n\nfoo() {\n trap 'exit 0' TERM ## here is the key\n while true; do sleep 1; done\n}\n\necho before child\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\nfoo &\npid=$!\n\nsleep 1 # wait trap is done\n\necho before kill\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\nkill $pid ## no need to redirect stdin/stderr\n\nsleep 1 # wait kill is done\n\necho after kill\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14437/" ]
81,521
<p>I have settled a web synchronization between SQLSERVER 2005 as publisher and SQLEXPRESS as suscriber. Web synchro has to be launched manually through IE interface (menu tools/synchronize) and to be selected among available synchronizations.</p> <p>Everything is working fine except that I did not find a way to automate the synchro, which I still have to launch manually. Any idea?</p> <p>I have no idea if this synchro can be launched from SQLEXPRESS by running a specific T-SQL code (in this case my problem could be solved indirectly).</p>
[ { "answer_id": 81539, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 3, "selected": false, "text": "disown" }, { "answer_id": 81672, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 5, "selected": true, "text": "(script 2> /dev/null)\n exec 3>&2 # 3 is now a copy of 2\nexec 2> /dev/null # 2 now points to /dev/null\nscript # run script with redirected stderr\nexec 2>&3 # restore stderr to saved\nexec 3>&- # close saved version\n" }, { "answer_id": 4849503, "author": "MarcH", "author_id": 317623, "author_profile": "https://Stackoverflow.com/users/317623", "pm_score": 4, "selected": false, "text": "cat > silent.sh <<\"EOF\"\nsleep 100 &\nkill -INT $!\nsleep 1\nEOF\n\nsh silent.sh\n" }, { "answer_id": 5722874, "author": "Mark Edgar", "author_id": 129332, "author_profile": "https://Stackoverflow.com/users/129332", "pm_score": 7, "selected": false, "text": "stderr kill stderr kill wait kill $!\nwait $! 2>/dev/null\n kill wait kill $(jobs -rp)\nwait $(jobs -rp) 2>/dev/null\n" }, { "answer_id": 12198152, "author": "Ralph", "author_id": 1636189, "author_profile": "https://Stackoverflow.com/users/1636189", "pm_score": 2, "selected": false, "text": "$ sleep 3 &\n[1] 234\n<pressing enter a few times....>\n$\n$\n[1]+ Done sleep 3\n$\n $ (set +m; sleep 3 &)\n<again, pressing enter several times....>\n$\n$\n$\n$\n$\n" }, { "answer_id": 13223242, "author": "Coder of Salvation", "author_id": 1659796, "author_profile": "https://Stackoverflow.com/users/1659796", "pm_score": 2, "selected": false, "text": "killall -s SIGINT (yourprogram) \n" }, { "answer_id": 15300185, "author": "phily", "author_id": 2149422, "author_profile": "https://Stackoverflow.com/users/2149422", "pm_score": 0, "selected": false, "text": "sh -c 'cmd &' #!/bin/bash\n# ...\npid=\"`sh -c 'sleep 30 & echo ${!}' | head -1`\"\nkill \"$pid\"\n# ...\n\n# or put several cmds in sh -c '...' construct\nsh -c '\nsleep 30 &\npid=\"${!}\"\nsleep 5 \nkill \"${pid}\"\n'\n" }, { "answer_id": 16424178, "author": "J-o-h-n-", "author_id": 2359158, "author_profile": "https://Stackoverflow.com/users/2359158", "pm_score": 0, "selected": false, "text": "jobs 2>&1 >/dev/null while true; do echo $RANDOM; done | while read line\n do\n echo Random is $line the last jobid is $(jobs -lp)\n jobs 2>&1 >/dev/null\n sleep 3\n done\n" }, { "answer_id": 17257986, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "{ kill $! } 2>/dev/null\n { kill -9 $PID } 2>/dev/null\n" }, { "answer_id": 48726125, "author": "Al Joslin", "author_id": 2912739, "author_profile": "https://Stackoverflow.com/users/2912739", "pm_score": -1, "selected": false, "text": "function killCmd() {\n kill $1\n}\n\nkillCmd $somePID &\n" }, { "answer_id": 66355103, "author": "James Z.M. Gao", "author_id": 7704140, "author_profile": "https://Stackoverflow.com/users/7704140", "pm_score": 2, "selected": false, "text": "Terminated #!/bin/sh\n\n## assume script name is test.sh\n\nfoo() {\n trap 'exit 0' TERM ## here is the key\n while true; do sleep 1; done\n}\n\necho before child\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\nfoo &\npid=$!\n\nsleep 1 # wait trap is done\n\necho before kill\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\nkill $pid ## no need to redirect stdin/stderr\n\nsleep 1 # wait kill is done\n\necho after kill\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11436/" ]
81,533
<p>I'm currently trying to improve the design of a legacy db and I have the following situation</p> <p>Currently I have a table SalesLead in which we store the the LeadSource.</p> <pre><code>Create Table SalesLead( .... LeadSource varchar(20) .... ) </code></pre> <p>The Lead Sources are helpfully stored in a table.</p> <pre><code>Create Table LeadSource ( LeadSourceId int, /*the PK*/ LeadSource varchar(20) ) </code></pre> <p>And so I just want to Create a foreign key from one to the other and drop the non-normalized column.</p> <p>All standard stuff, I hope.</p> <p>Here is my problem. I can't seem to get away from the issue that instead of writing</p> <pre><code> SELECT * FROM SalesLead Where LeadSource = 'foo' </code></pre> <p>Which is totally unambiguous I now have to write </p> <pre><code>SELECT * FROM SalesLead where FK_LeadSourceID = 1 </code></pre> <p>or </p> <pre><code>SELECT * FROM SalesLead INNER JOIN LeadSource ON SalesLead.FK_LeadSourceID = LeadSource.LeadSourceId where LeadSource.LeadSource = "foo" </code></pre> <p>Which breaks if we ever alter the content of the LeadSource field.</p> <p>In my application when ever I want to alter the value of SalesLead's LeadSource I don't want to update from 1 to 2 (for example) as I don't want to have developers having to remember these <strong>magic numbers</strong>. The ids are arbitrary and should be kept so.</p> <p><strong><em>How do I remove or negate the dependency on them in my app's code?</em></strong></p> <p><strong>Edit</strong> Languages my solution will have to support</p> <ul> <li>.NET 2.0 + 3 (for what its worth asp.net, vb.net and c#)</li> <li>vba (access)</li> <li>db (MSSQL 2000)</li> </ul> <p><strong>Edit 2.0</strong> The join is fine is just that 'foo' may change on request to 'foobar' and I don't want to haul through the queries.</p>
[ { "answer_id": 81565, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 2, "selected": false, "text": "SELECT * FROM SALESLEAD WHERE LeadSouce = (int) EnmLeadSource.Foo; //pseudocode\n public enum EnmLeadSource \n{\n Foo = 1,\n Bar = 2\n}\n public void GiveMeSalesLeadGiven( EnmLeadSource thisLeadSource )\n{\n // Construct your string using the value of thisLeadSource \n}\n" }, { "answer_id": 81570, "author": "pilif", "author_id": 5083, "author_profile": "https://Stackoverflow.com/users/5083", "pm_score": 0, "selected": false, "text": "SELECT * FROM SalesLead where FK_LeadSourceID = \n (SELECT LeadSourceID from LeadSource WHERE LeadSource = 'foo')\n" }, { "answer_id": 82185, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "SELECT * FROM SalesLead \nINNER JOIN LeadSource ON SalesLead.FK_LeadSourceID = LeadSource.LeadSourceId \nwhere LeadSource.LeadSource = \"foo\"\n SELECT * FROM SalesLead Where LeadSource = 'foo'\n foo foobar foo foobar" }, { "answer_id": 82628, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "LeadSource LeadSource SalesLead LeadSource" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
81,548
<p>I am running blazeds on the server side. I would like to filter http requests using an http header. My goal is to send extra parameters to the server without changing the signatures of my blazeds services.</p> <p>On the client side, I am using Flex <strong>RemoteObject</strong> methods. </p> <p>With Flex WebService components, it is possible to set an http header using the property <strong>httpHeaders</strong>. I have not found anything similar on the RemoteObject class...</p>
[ { "answer_id": 133095, "author": "Verdant", "author_id": 450527, "author_profile": "https://Stackoverflow.com/users/450527", "pm_score": 1, "selected": false, "text": "setCredentials(username,password) setCredentials" }, { "answer_id": 3156087, "author": "Radek", "author_id": 380861, "author_profile": "https://Stackoverflow.com/users/380861", "pm_score": 1, "selected": false, "text": "document.cookie=\"clientVersion=1.0;expires=2100-01-01;path=/\";\n" }, { "answer_id": 3178195, "author": "hongo", "author_id": 383503, "author_profile": "https://Stackoverflow.com/users/383503", "pm_score": 2, "selected": false, "text": "mx.messaging.messages.IMessage RemoteObject flex.messaging.services.remoting.adapters.JavaAdapter mx.rpc.AsyncRequest mx.rpc.remoting.mxml.RemoteObject AsyncRequest setHeaders AsyncRequest com.asfusion.mate.actions.builders.RemoteObjectInvoker RemoteObjectInvoker RemoteObject" }, { "answer_id": 15371118, "author": "Marcelo Rodovalho", "author_id": 1213594, "author_profile": "https://Stackoverflow.com/users/1213594", "pm_score": -1, "selected": false, "text": "$GLOBALS['HTTP_RAW_POST_DATA'];\n file_get_contents('php://input');\n" }, { "answer_id": 26745792, "author": "yiotix", "author_id": 2435139, "author_profile": "https://Stackoverflow.com/users/2435139", "pm_score": 0, "selected": false, "text": "var operation:AbstractOperation = _remoteSession.getOperation('myRemoteOperation');\nvar async:AsyncRequest = operation.mx_internal::asyncRequest;\nasync.defaultHeaders = {my_header:'my_value'};\n" }, { "answer_id": 29437014, "author": "Ronny Shibley", "author_id": 3040886, "author_profile": "https://Stackoverflow.com/users/3040886", "pm_score": 2, "selected": false, "text": "use namespace mx_internal;\n\nvar service:RemoteObject = new RemoteObject(destination);\nvar operation:Operation = service[functionName];\noperation.asyncRequest.defaultHeaders = {company:'company'};\n\nvar token:AsyncToken = operation.send();\n public class FlexJavaCustomAdapter extends JavaAdapter{\n @Override\n public Object invoke(Message message) {\n String locale = (String) message.getHeader(\"com.foo.locale\"); \n return super.invoke(message);\n } \n}\n <bean id=\"customAdapter\" class=\"org.springframework.flex.core.ManageableComponentFactoryBean\">\n <constructor-arg value=\"com.codefish.model.flex.FlexJavaCustomAdapter\"/>\n </bean> \n\n <flex:message-broker id=\"_messageBroker\" services-config-path=\"classpath*:/com/codefish/resources/spring/services-config.xml\" > \n <flex:remoting-service default-adapter-id=\"customAdapter\" \n default-channels=\"my-amf, my-secure-amf\" />\n </flex:message-broker>\n</bean>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11897/" ]
81,552
<p>There doesn't seem to be a dictionary.AddRange() method. Does anyone know a better way to copy the items to another dictionary without using a foreach loop. </p> <p>I'm using the System.Collections.Generic.Dictionary. This is for .NET 2.0. </p>
[ { "answer_id": 81579, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 5, "selected": false, "text": "Dictionary Dictionary IDictionary Add() KeyValuePair<TKey, TValue>" }, { "answer_id": 84308, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 2, "selected": false, "text": "public static Dictionary<TKey, TValue> DeepCopy<TKey,TValue>(this Dictionary<TKey, TValue> dictionary)\n {\n Dictionary<TKey, TValue> d2 = new Dictionary<TKey, TValue>();\n\n bool keyIsCloneable = default(TKey) is ICloneable;\n bool valueIsCloneable = default(TValue) is ICloneable;\n\n foreach (KeyValuePair<TKey, TValue> kvp in dictionary)\n {\n TKey key = default(TKey);\n TValue value = default(TValue);\n if (keyIsCloneable)\n {\n key = (TKey)((ICloneable)(kvp.Key)).Clone();\n }\n\n else\n {\n key = kvp.Key;\n }\n\n if (valueIsCloneable)\n {\n value = (TValue)((ICloneable)(kvp.Value)).Clone();\n }\n\n else\n {\n value = kvp.Value;\n }\n\n d2.Add(key, value);\n }\n\n return d2;\n }\n" }, { "answer_id": 45593250, "author": "Mahendra Thorat", "author_id": 7305904, "author_profile": "https://Stackoverflow.com/users/7305904", "pm_score": 4, "selected": false, "text": "var Animal = new Dictionary<string, string>();\n Dictionary<string, string> NewAnimals = new Dictionary<string, string>(Animal);\n" }, { "answer_id": 60526164, "author": "Marcello", "author_id": 6366781, "author_profile": "https://Stackoverflow.com/users/6366781", "pm_score": 0, "selected": false, "text": "public void runIntDictionary()\n{\n Dictionary<int, int> myIntegerDict = new Dictionary<int, int>() { { 0, 0 }, { 1, 1 }, { 2, 2 } };\n Dictionary<int, int> cloneIntegerDict = new Dictionary<int, int>();\n cloneIntegerDict = myIntegerDict.Select(x => x.Key).ToList().ToDictionary<int, int>(x => x, y => myIntegerDict[y]);\n}\n public void runObjectDictionary()\n{\n Dictionary<int, number> myDict = new Dictionary<int, number>() { { 3, new number(3) }, { 4, new number(4) }, { 5, new number(5) } };\n Dictionary<int, number> cloneDict = new Dictionary<int, number>();\n cloneDict = myDict.Select(x => x.Key).ToList().ToDictionary<int, number>(x => x, y => myDict[y].Clone());\n}\n\npublic class number : ICloneable\n{\n public number()\n {\n }\n public number(int newNumber)\n {\n nr = newnumber;\n }\n public int nr;\n\n public object Clone()\n {\n return new number() { nr = nr };\n }\n public override string ToString()\n {\n return nr.ToString();\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13028/" ]
81,560
<p>I feel like I have a very basic/stupid question, yet I never saw/read/heard anything in this direction.</p> <p>Say I have a table <em>users(userId, name)</em> and a table <em>preferences(id, userId, language)</em>. The example is trivial but could be extended to a situation with multi-level relations and way more tables..<br> When my UI requests to delete a user I first want to show a warning stating that also its preferences will be deleted. If at some point the database gets extended with more tables and relationships, but the software isn't adapted accordingly (the client didn't update) a generic message should be shown.</p> <p>How can I implement this? The UI cannot know about the whole data structure and should not be bothered to walk down all the relations to manually delete all the depending records. </p> <p>I would think this would be with constraints.<br> The constraint would be <em>no action</em> at first so the constraint will throw an error that can be caught by the UI. After the UI receives a confirmation, the constraint should become a <em>cascade</em>.</p> <p>Somehow I'm feeling like I'm getting this all wrong..</p>
[ { "answer_id": 81665, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 0, "selected": false, "text": "marked_for_deletion" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
81,567
<p>How do you ensure, that you can checkout the code into Eclipse or NetBeans and work there with it?</p> <p>Edit: If you not checking in ide-related files, you have to reconfigure buildpath, includes and all this stuff, each time you checkout the project. I don't know, if ant (especially an ant buildfile which is created/exported from eclipse) will work with an other ide seamlessly.</p>
[ { "answer_id": 84958, "author": "Jay R.", "author_id": 5074, "author_profile": "https://Stackoverflow.com/users/5074", "pm_score": 3, "selected": false, "text": "sample-project \n+ bin\n+ launches \n+ lib \n+ logs\n+ nbproject \n+ src \n + java\n.classpath\n.project\nbuild.xml\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5751/" ]
81,587
<p>We have in the process of upgrading our application to full Unicode comptibility as we have recently got Delphi 2009 which provides this out of the box. I am looking for anyone who has experience of upgrading an application to accept Unicode characters. Specifically answers to any of the following questions.</p> <ul> <li>We need to change VarChars to NVarchar, Char to NChar. Are there any gotchas here.</li> <li>We need to update all sql statements to include N in front of any sql strings. So Update tbl_Customer set Name = 'Smith' must become Update tbl_Customer set Name = <strong>N</strong>'Smith' . Is there any way to default to this for certain Fields. It seems extraordinary this is still required.</li> <li>Is it possible to get any defaults set up in SQLServer that will make this simpler?</li> </ul> <p>ps We also need to upgrade our Oracle code</p>
[ { "answer_id": 81895, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": true, "text": "nvarchar varchar2 ' N'" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6244/" ]
81,589
<p>My workplace has sales people using a 3rd party desktop application that connects directly the a Sql Server and the software is leaving hundreds of sleeping connections for each user. Is there anyway to clear these connection programmatically?</p>
[ { "answer_id": 83416, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "declare @spid int\n , @cmd varchar(200)\ndeclare Mycurs cursor for\nselect spid\n from master..sysprocesses\n where status = 'sleeping'\n and last_batch > dateadd( s, -1, getdate())\nopen mycurs\nfetch next from mycurs into @spid\nwhile @@fetch_status = 0\n begin\n select @cmd = 'kill ' + cast(@spid as varchar)\n exec(@cmd )\n fetch next from mycurs into @spid\n end\ndeallocate MyCurs\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802/" ]
81,597
<p>How can I find and delete unused references in my projects? </p> <p>I know you can easily remove the using statements in vs 2008, but this doesn't remove the actual reference in your projects. The referenced dll will still be copied in your bin/setup package.</p>
[ { "answer_id": 32232580, "author": "toddmo", "author_id": 1045881, "author_profile": "https://Stackoverflow.com/users/1045881", "pm_score": 2, "selected": false, "text": "References" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
81,627
<p>I am using Qt Dialogs in one of my application. I need to hide/delete the help button. But i am not able to locate where exactly I get the handle to his help button. Not sure if its a particular flag on the Qt window.</p>
[ { "answer_id": 81927, "author": "amos", "author_id": 15429, "author_profile": "https://Stackoverflow.com/users/15429", "pm_score": 7, "selected": true, "text": "QDialog *d = new QDialog(0, Qt::WindowSystemMenuHint | Qt::WindowTitleHint);\nd->exec();\n from PyQt4 import QtGui, QtCore\napp = QtGui.QApplication([])\nd = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)\nd.exec_()\n" }, { "answer_id": 82303, "author": "AMM", "author_id": 11212, "author_profile": "https://Stackoverflow.com/users/11212", "pm_score": 5, "selected": false, "text": "Qt::WindowFlags flags = windowFlags()\n\nQt::WindowFlags helpFlag =\nQt::WindowContextHelpButtonHint;\n\nflags = flags & (~helpFlag); \nsetWindowFlags(flags);\n QIcon icon = windowIcon();\n\nQt::WindowFlags flags = windowFlags();\n\nQt::WindowFlags helpFlag =\nQt::WindowContextHelpButtonHint;\n\nflags = flags & (~helpFlag); \n\nsetWindowFlags(flags);\n\nsetWindowIcon(icon);\n" }, { "answer_id": 358270, "author": "Michael Bishop", "author_id": 45114, "author_profile": "https://Stackoverflow.com/users/45114", "pm_score": 2, "selected": false, "text": "$QTDIR/examples/widgets/windowflags" }, { "answer_id": 3817398, "author": "brandoneggar", "author_id": 461134, "author_profile": "https://Stackoverflow.com/users/461134", "pm_score": 0, "selected": false, "text": "winEvent #if defined(Q_WS_WIN)\nbool MyWizard::winEvent(MSG * msg, long * result)\n{\n switch (msg->message)\n {\n case WM_NCLBUTTONDOWN:\n if (msg->wParam == HTHELP)\n {\n\n }\n break;\n default:\n break;\n }\n return QWizard::winEvent(msg, result);\n}\n#endif\n" }, { "answer_id": 30934930, "author": "Jens A. Koch", "author_id": 1163786, "author_profile": "https://Stackoverflow.com/users/1163786", "pm_score": 6, "selected": false, "text": "// remove question mark from the title bar\nsetWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);\n" }, { "answer_id": 45939311, "author": "Predelnik", "author_id": 1269661, "author_profile": "https://Stackoverflow.com/users/1269661", "pm_score": 2, "selected": false, "text": "QApplication bool eventFilter (QObject *watched, QEvent *event) override\n {\n if (event->type () == QEvent::Create)\n {\n if (watched->isWidgetType ())\n {\n auto w = static_cast<QWidget *> (watched);\n w->setWindowFlags (w->windowFlags () & (~Qt::WindowContextHelpButtonHint));\n }\n }\n return QObject::eventFilter (watched, event);\n }\n" }, { "answer_id": 49905954, "author": "Parker Coates", "author_id": 4757, "author_profile": "https://Stackoverflow.com/users/4757", "pm_score": 5, "selected": false, "text": "QApplication QApplication::setAttribute(Qt::AA_DisableWindowContextHelpButton);\n" }, { "answer_id": 70467468, "author": "Pascal Vallaster", "author_id": 15889585, "author_profile": "https://Stackoverflow.com/users/15889585", "pm_score": 2, "selected": false, "text": "class window(QDialog):\n def __init__(self):\n super(window, self).__init__()\n loadUi(\"window.ui\", self)\n self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint,False) # This removes it\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11212/" ]
81,628
<p>I'd like to build a query string based on values taken from 5 groups of radio buttons.</p> <p>Selecting any of the groups is optional so you could pick set A or B or both. How would I build the querystring based on this? I'm using VB.NET 1.1</p> <p>The asp:Radiobuttonlist control does not like null values so I'm resorting to normal html radio buttons. My question is how do I string up the selected values into a querystring</p> <p>I have something like this right now:</p> <p>HTML:</p> <pre><code>&lt;input type="radio" name="apBoat" id="Apb1" value="1" /&gt; detail1 &lt;input type="radio" name="apBoat" id="Apb2" value="2" /&gt; detail2 &lt;input type="radio" name="cBoat" id="Cb1" value="1" /&gt; detail1 &lt;input type="radio" name="cBoat" id="Cb2" value="2" /&gt; detail2 </code></pre> <p>VB.NET</p> <pre><code>Public Sub btnSubmit_click(ByVal sender As Object, ByVal e As System.EventArgs) Dim queryString As String = "nextpage.aspx?" Dim aBoat, bBoat, cBoat bas String aBoat = "apb=" &amp; Request("aBoat") bBoat = "bBoat=" &amp; Request("bBoat") cBoat = "cBoat=" &amp; Request("cBoat ") queryString += aBoat &amp; bBoat &amp; cBoat Response.Redirect(queryString) End Sub </code></pre> <p>Is this the best way to build the query string or should I take a different approach altogether? Appreciate all the help I can get. Thanks much.</p>
[ { "answer_id": 81704, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 2, "selected": true, "text": "<form action=\"...\" method=\"get\">\n <input type=\"radio\" name=\"apBoat\" id=\"Apb1\" value=\"1\" /> <label for=\"Apb1\">detail1</label>\n <input type=\"radio\" name=\"apBoat\" id=\"Apb2\" value=\"2\" /> <label for=\"Apb2\">detail2</label>\n\n <input type=\"radio\" name=\"cBoat\" id=\"Cb1\" value=\"1\" /> <label for=\"Cb1\">detail1</label>\n <input type=\"radio\" name=\"cBoat\" id=\"Cb2\" value=\"2\" /> <label for=\"Cb2\">detail2</label>\n</form>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12232/" ]
81,631
<p>I want: all links which not contained filename (not .html, .jpg, .png, .css) redirect with state 301 to directory, for example: <a href="http://mysite.com/article" rel="nofollow noreferrer">http://mysite.com/article</a> -> <a href="http://mysite.com/article/" rel="nofollow noreferrer">http://mysite.com/article/</a> But <a href="http://mysite.com/article/article-15.html" rel="nofollow noreferrer">http://mysite.com/article/article-15.html</a> not redirects. What regulat expression I must write to .htaccess for adding slash to virtual directories?</p>
[ { "answer_id": 81760, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 3, "selected": true, "text": "RewriteEngine on \nRewriteCond %{REQUEST_URI} ^/[^\\.]+[^/]$\nRewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [R=301,L]\n" }, { "answer_id": 193294, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "/a RewriteRule ^(([^\\/]+\\/)*[^\\/\\.]+)$ http://%{HTTP_HOST}/$1/ [R=301,L]\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13427/" ]
81,656
<p>For many questions the answer seems to be found in "the standard". However, where do we find that? Preferably online.</p> <p>Googling can sometimes feel futile, again especially for the C standards, since they are drowned in the flood of discussions on programming forums.</p> <p>To get this started, since these are the ones I am searching for right now, where are there good online resources for:</p> <ul> <li>C89</li> <li>C99</li> <li>C11</li> <li>C++98</li> <li>C++03</li> <li>C++11</li> <li>C++14</li> <li>C++17</li> </ul>
[ { "answer_id": 83763, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 10, "selected": true, "text": "off_t <aio.h> clock_gettime() _POSIX_C_SOURCE -std=c99 _POSIX_C_SOURCE" }, { "answer_id": 27359265, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "-std=c94" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15514/" ]
81,657
<p>What is the most efficient, secure way to pipe the contents of a postgresSQL database into a compressed tarfile, then copy to another machine?</p> <p>This would be used for localhosting development, or backing up to a remote server, using *nix based machines at both ends.</p>
[ { "answer_id": 81679, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "BACKUP=\"/backup/$NOW\"\nPFILE=\"$(hostname).$(date +'%T').pg.sql.gz\"\nPGSQLUSER=\"vivek\"\nPGDUMP=\"/usr/bin/pg_dump\"\n\n$PGDUMP -x -D -U${PGSQLUSER} | $GZIP -c > ${BACKUP}/${PFILE}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15479/" ]
81,671
<p>I would like to display an RTF document in an SWT (actually Eclipse RCP) application.</p> <p>I know there is a Swing widget for displaying and editing RTF text, but it is Swing and quite alien in look and feel when used in the otherwise platform (not to mention that to the last of my knowledge it did not display images and had only limited support for formatting)</p> <p>Other options is to use COM interface on windows, but that works only on the windows platform and requires that an ActiveX RichEdit contol be installed on the customer machine... which can make the deployment of the application quite horrendous...</p> <p>What are the other options for displaying rich documents inside Eclipse/SWT application?</p>
[ { "answer_id": 170079, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 1, "selected": false, "text": "String rtf = \"whatever\";\nBufferedReader input = new BufferedReader(new StringReader(rtf));\n\nRTFEditorKit rtfKit = new RTFEditorKit();\nStyledDocument doc = (StyledDocument) rtfKit.createDefaultDocument();\nrtfEdtrKt.read( input, doc, 0 );\ninput.close();\n\nHTMLEditorKit htmlKit = new HTMLEditorKit(); \nStringWriter output = new StringWriter();\nhtmlKit.write( output, doc, 0, doc.getLength());\n\nString html = output.toString();\n" }, { "answer_id": 269138, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 1, "selected": false, "text": "package ooswtviewer;\n\nimport java.awt.Panel;\n\nimport com.sun.star.awt.XView;\nimport com.sun.star.beans.Property;\nimport com.sun.star.beans.UnknownPropertyException;\nimport com.sun.star.beans.XPropertySet;\nimport com.sun.star.comp.beans.Frame;\nimport com.sun.star.comp.beans.NoConnectionException;\nimport com.sun.star.comp.beans.OOoBean;\nimport com.sun.star.comp.beans.OfficeDocument;\nimport com.sun.star.drawing.XDrawView;\nimport com.sun.star.frame.XController;\nimport com.sun.star.frame.XDesktop;\nimport com.sun.star.frame.XFrame;\nimport com.sun.star.frame.XFramesSupplier;\nimport com.sun.star.frame.XLayoutManager;\nimport com.sun.star.frame.XModel;\nimport com.sun.star.lang.WrappedTargetException;\nimport com.sun.star.ui.XUIElement;\nimport com.sun.star.uno.Any;\nimport com.sun.star.uno.UnoRuntime;\nimport com.sun.star.uno.XInterface;\nimport com.sun.star.view.XViewSettingsSupplier;\n\n/**\n * Code based on example from http://www.eclipsezone.com/eclipse/forums/t48966.html\n * \n * @author Aaron digulla\n */\npublic class OOoSwtViewer extends Panel\n{\n private static final String RESOURCE_TOOLBAR_TEXTOBJECTBAR = \"private:resource/toolbar/textobjectbar\";\n private static final String RESOURCE_TOOLBAR_STANDARDBAR = \"private:resource/toolbar/standardbar\";\n private static final String RESOURCE_MENUBAR = \"private:resource/menubar/menubar\";\n\n private static final long serialVersionUID = -1408623115735065822L;\n\n private OOoBean aBean;\n\n public OOoSwtViewer()\n {\n super();\n aBean = new OOoBean();\n setLayout(new java.awt.BorderLayout());\n add(aBean, java.awt.BorderLayout.CENTER);\n\n aBean.setAllBarsVisible (false);\n }\n\n public XPropertySet getXPropertySet ()\n {\n return getXPropertySet (getFrame ());\n }\n\n public XPropertySet getXPropertySet (Object o)\n {\n return (XPropertySet)UnoRuntime.queryInterface (XPropertySet.class, o);\n }\n\n public Frame getFrame ()\n {\n try\n {\n return aBean.getFrame ();\n }\n catch (NoConnectionException e)\n {\n throw new OOException (\"Error getting frame from bean\", e);\n }\n }\n\n public XLayoutManager getXLayoutManager ()\n {\n try\n {\n return (XLayoutManager)UnoRuntime.queryInterface (XLayoutManager.class, getXPropertySet ().getPropertyValue (\"LayoutManager\"));\n }\n catch (Exception e)\n {\n throw new OOException (\"Error getting LayoutManager from bean's properties\", e);\n } \n }\n\n public void setMenuBarVisible (boolean visible)\n {\n if (visible)\n getXLayoutManager ().showElement (RESOURCE_MENUBAR);\n else\n getXLayoutManager ().hideElement (RESOURCE_MENUBAR);\n }\n\n public void setStandardBarVisible (boolean visible)\n {\n if (visible)\n getXLayoutManager ().showElement (RESOURCE_TOOLBAR_STANDARDBAR);\n else\n getXLayoutManager ().hideElement (RESOURCE_TOOLBAR_STANDARDBAR);\n }\n\n public void setTextObjectBarVisible (boolean visible)\n {\n if (visible)\n getXLayoutManager ().showElement (RESOURCE_TOOLBAR_TEXTOBJECTBAR);\n else\n getXLayoutManager ().hideElement (RESOURCE_TOOLBAR_TEXTOBJECTBAR);\n }\n\n\n private Thread loadThread;\n private Exception loadException;\n\n public void setDocument(final String url)\n {\n loadThread = new Thread () {\n public void run() {\n try\n {\n aBean.loadFromURL(url, null);\n aBean.aquireSystemWindow();\n\n setTextObjectBarVisible (false);\n\n// for (XUIElement e: getXLayoutManager ().getElements ())\n// {\n// XInterface i = (XInterface)e.getRealInterface ();\n// System.out.println (e);\n// System.out.println (i);\n// printProperties (getXPropertySet (e));\n// }\n\n /*\n System.out.println (\"frame:\");\n printProperties (getXPropertySet ());\n\nframe:\nTitle=test - OpenOffice.org Writer \nIndicatorInterception=Any[Type[com.sun.star.task.XStatusIndicator], null]\nLayoutManager=Any[Type[com.sun.star.frame.XLayoutManager], [Proxy:26506390,717ea70;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.frame.XLayoutManager]]]\nDispatchRecorderSupplier=Any[Type[com.sun.star.frame.XDispatchRecorderSupplier], null]\nIsHidden=false\n */\n\n XController controller = aBean.getDocument ().getCurrentController ();\n /*\n System.out.println (\"controller:\");\n printProperties (getXPropertySet (controller));\n\ncontroller:\nIsConstantSpellcheck=true\nIsHideSpellMarks=false\nLineCount=1\nPageCount=1\n */\n\n /*\n System.out.println (\"layoutManager:\");\n printProperties (getXPropertySet (getXLayoutManager ()));\n\nlayoutManager:\nAutomaticToolbars=true\nHideCurrentUI=false\nLockCount=0\nMenuBarCloser=true\nRefreshContextToolbarVisibility=false\n */\n\n /*\n System.out.println (\"document:\");\n printProperties (getXPropertySet (aBean.getDocument ()));\n OfficeDocument doc = aBean.getDocument ();\nApplyFormDesignMode=false\nApplyWorkaroundForB6375613=false\nAutomaticControlFocus=false\nBasicLibraries=Any[Type[com.sun.star.script.XLibraryContainer], [Proxy:14806696,73ca178;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.script.XLibraryContainer]]]\nBuildId=680$9310\nCharFontCharSet=1\nCharFontCharSetAsian=1\nCharFontCharSetComplex=1\nCharFontFamily=3\nCharFontFamilyAsian=6\nCharFontFamilyComplex=6\nCharFontName=Times New Roman\nCharFontNameAsian=Arial Unicode MS\nCharFontNameComplex=Tahoma\nCharFontPitch=2\nCharFontPitchAsian=2\nCharFontPitchComplex=2\nCharFontStyleName=\nCharFontStyleNameAsian=\nCharFontStyleNameComplex=\nCharLocale=com.sun.star.lang.Locale@fb6354\nCharacterCount=20\nDialogLibraries=Any[Type[com.sun.star.script.XLibraryContainer], [Proxy:3556929,73a39c0;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.script.XLibraryContainer]]]\nForbiddenCharacters=Any[Type[com.sun.star.i18n.XForbiddenCharacters], [Proxy:11544872,7669148;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.i18n.XForbiddenCharacters]]]\nHasValidSignatures=false\nHideFieldTips=false\nIndexAutoMarkFileURL=\nLockUpdates=false\nParagraphCount=1\nRecordChanges=false\nRedlineDisplayType=2\nRedlineProtectionKey=[B@f593af\nRuntimeUID=10\nShowChanges=true\nTwoDigitYear=1930\nWordCount=5\nWordSeparator=() \n */\n\n// System.out.println (\"viewData:\");\n// printProperties (getXPropertySet (controller.getFrame ().getContainerWindow ()));\n\n XViewSettingsSupplier settingsSupplier = (XViewSettingsSupplier)UnoRuntime.queryInterface (XViewSettingsSupplier.class, controller);\n// System.out.println (\"settingsSupplier:\");\n// printProperties (settingsSupplier.getViewSettings ());\n settingsSupplier.getViewSettings ().setPropertyValue (\"ShowVertRuler\", Boolean.FALSE);\n settingsSupplier.getViewSettings ().setPropertyValue (\"ShowHoriRuler\", Boolean.FALSE);\n // Switch to Web Layout. This layout mode comes without gray border and the page borders automatically adujst to the frame\n settingsSupplier.getViewSettings ().setPropertyValue (\"ShowOnlineLayout\", Boolean.TRUE);\n// settingsSupplier.getViewSettings ().setPropertyValue (\"ShowTextBoundaries\", Boolean.TRUE);\n\n// XView view = (XView)UnoRuntime.queryInterface (XView.class, getFrame ());\n// System.out.println (\"drawView=\"+view);\n// printProperties (getXPropertySet (view));\n\n /*\n XModel model = (XModel)UnoRuntime.queryInterface (XModel.class, doc);\n printProperties (\"model\", model);\n\n Same as getDocument()\n */\n\n /*\n System.out.println (\"Interfaces implemented by aBean.getDocument():\");\n for (Class c: OOoInspector.queryInterface (aBean.getDocument ()))\n System.out.println (\" \"+c.getName ());\n com.sun.star.datatransfer.XTransferable\n com.sun.star.document.XDocumentInfoSupplier\n com.sun.star.document.XDocumentLanguages\n com.sun.star.document.XDocumentSubStorageSupplier\n com.sun.star.document.XEmbeddedScripts\n com.sun.star.document.XEventBroadcaster\n com.sun.star.document.XEventsSupplier\n com.sun.star.document.XLinkTargetSupplier\n com.sun.star.document.XRedlinesSupplier\n com.sun.star.document.XStorageBasedDocument\n com.sun.star.document.XViewDataSupplier\n com.sun.star.drawing.XDrawPageSupplier\n com.sun.star.embed.XVisualObject\n com.sun.star.frame.XLoadable\n com.sun.star.frame.XModel\n com.sun.star.frame.XModel2\n com.sun.star.frame.XModule\n com.sun.star.frame.XStorable\n com.sun.star.frame.XStorable2\n com.sun.star.script.provider.XScriptProviderSupplier\n com.sun.star.style.XAutoStylesSupplier\n com.sun.star.style.XStyleFamiliesSupplier\n com.sun.star.text.XBookmarksSupplier\n com.sun.star.text.XChapterNumberingSupplier\n com.sun.star.text.XDocumentIndexesSupplier\n com.sun.star.text.XEndnotesSupplier\n com.sun.star.text.XFootnotesSupplier\n com.sun.star.text.XLineNumberingProperties\n com.sun.star.text.XNumberingRulesSupplier\n com.sun.star.text.XPagePrintable\n com.sun.star.text.XReferenceMarksSupplier\n com.sun.star.text.XTextDocument\n com.sun.star.text.XTextEmbeddedObjectsSupplier\n com.sun.star.text.XTextFieldsSupplier\n com.sun.star.text.XTextFramesSupplier\n com.sun.star.text.XTextGraphicObjectsSupplier\n com.sun.star.text.XTextSectionsSupplier\n com.sun.star.text.XTextTablesSupplier\n com.sun.star.ui.XUIConfigurationManagerSupplier\n com.sun.star.util.XCloseable\n com.sun.star.util.XCloseBroadcaster\n com.sun.star.util.XLinkUpdate\n com.sun.star.util.XModifiable\n com.sun.star.util.XModifiable2\n com.sun.star.util.XModifyBroadcaster\n com.sun.star.util.XNumberFormatsSupplier\n com.sun.star.util.XRefreshable\n com.sun.star.util.XReplaceable\n com.sun.star.util.XSearchable\n com.sun.star.view.XPrintable\n com.sun.star.view.XPrintJobBroadcaster\n com.sun.star.view.XRenderable\n com.sun.star.xforms.XFormsSupplier\n */\n\n /*\n System.out.println (\"Interfaces implemented by controller:\");\n for (Class c: OOoInspector.queryInterface (controller))\n System.out.println (\" \"+c.getName ());\n\n com.sun.star.awt.XUserInputInterception\n com.sun.star.datatransfer.XTransferableSupplier\n com.sun.star.frame.XController\n com.sun.star.frame.XControllerBorder\n com.sun.star.frame.XDispatchInformationProvider\n com.sun.star.frame.XDispatchProvider\n com.sun.star.task.XStatusIndicatorSupplier\n com.sun.star.text.XRubySelection\n com.sun.star.text.XTextViewCursorSupplier\n com.sun.star.ui.XContextMenuInterception\n com.sun.star.view.XControlAccess\n com.sun.star.view.XFormLayerAccess\n com.sun.star.view.XSelectionSupplier\n com.sun.star.view.XViewSettingsSupplier\n */\n\n /*\n System.out.println (\"Interfaces implemented by frame:\");\n for (Class c: OOoInspector.queryInterface (getFrame ()))\n System.out.println (\" \"+c.getName ());\n\n com.sun.star.awt.XFocusListener\n com.sun.star.awt.XTopWindowListener\n com.sun.star.awt.XWindowListener\n com.sun.star.document.XActionLockable\n com.sun.star.frame.XComponentLoader\n com.sun.star.frame.XDispatchInformationProvider\n com.sun.star.frame.XDispatchProvider\n com.sun.star.frame.XDispatchProviderInterception\n com.sun.star.frame.XFrame\n com.sun.star.frame.XFramesSupplier\n com.sun.star.task.XStatusIndicatorFactory\n com.sun.star.util.XCloseable\n com.sun.star.util.XCloseBroadcaster\n */\n\n /*\n XFramesSupplier frames = OOoInspector.queryInterface (XFramesSupplier.class, getFrame ());\n printProperties (\"frames\", frames);\n\n for (int i=0; i<frames.getFrames ().getCount (); i++)\n {\n XFrame frame = (XFrame)frames.getFrames ().getByIndex (i);\n printProperties (\"Frame \"+i, frame);\n }\n\nframes=[Proxy:16382237,6ace84c;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.frame.XFramesSupplier]]\nTitle=test - OpenOffice.org Writer \nIndicatorInterception=Any[Type[com.sun.star.task.XStatusIndicator], null]\nLayoutManager=Any[Type[com.sun.star.frame.XLayoutManager], [Proxy:22149392,76bd794;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.frame.XLayoutManager]]]\nDispatchRecorderSupplier=Any[Type[com.sun.star.frame.XDispatchRecorderSupplier], null]\nIsHidden=false\n */\n XPropertySet p = getXPropertySet (getFrame ());\n Any any = (Any)p.getPropertyValue (\"LayoutManager\");\n System.out.println (any);\n System.out.println (any.getClass ().getName ());\n XLayoutManager layoutManager = (XLayoutManager)any.getObject ();\n printProperties (\"layoutManager\", layoutManager);\n\n\n /*\n printProperties (\"containerWindow\", getFrame ().getContainerWindow ());\n\ncontainerWindow=[Proxy:11970262,6d33e60;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.awt.XWindow]]\nnull\n */\n\n /*\n printProperties (\"componentWindow\", getFrame ().getComponentWindow ());\n\ncomponentWindow=[Proxy:25380515,8657cc4;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.awt.XWindow]]\nnull\n */\n }\n catch (Exception e)\n {\n e.printStackTrace ();\n }\n }\n };\n if (1 == 1)\n loadThread.start ();\n else\n loadThread.run ();\n }\n\n /** closes the bean viewer and tries to terminate OOo.\n */\n public void terminate() throws NoConnectionException {\n setVisible(false);\n XDesktop xDesktop = null;\n xDesktop = aBean.getOOoDesktop();\n aBean.stopOOoConnection();\n if (xDesktop != null)\n xDesktop.terminate();\n }\n\n /** closes the bean viewer, leaves OOo running.\n */\n public void close() {\n setVisible(false);\n aBean.stopOOoConnection();\n }\n\n public void printProperties (String name, Object obj)\n {\n System.out.println (name+\"=\"+obj);\n if (obj != null)\n printProperties (getXPropertySet (obj));\n }\n\n public void printProperties (XPropertySet set)\n {\n if (set == null)\n {\n System.out.println (\"null\");\n return;\n }\n\n for (Property p: set.getPropertySetInfo ().getProperties ())\n {\n try\n {\n System.out.println (p.Name+\"=\"+set.getPropertyValue (p.Name));\n }\n catch (Exception e)\n {\n throw new OOException (\"Error getting value of property \"+p.Name, e);\n }\n }\n }\n\n}\n package ooswtviewer;\n\nimport java.awt.BorderLayout;\nimport java.awt.Frame;\nimport java.awt.Panel;\nimport java.io.File;\n\nimport javax.swing.JRootPane;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.awt.SWT_AWT;\nimport org.eclipse.swt.events.DisposeEvent;\nimport org.eclipse.swt.events.DisposeListener;\nimport org.eclipse.swt.layout.FillLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Shell;\n\n/**\n * Code based on example from http://www.eclipsezone.com/eclipse/forums/t48966.html\n * \n * @author Aaron Digulla\n */\npublic class OOoSwtSnippet {\n public static void main(String[] args) {\n OOoSwtSnippet obj = new OOoSwtSnippet ();\n try\n {\n obj.run (args);\n }\n catch (Exception e)\n {\n e.printStackTrace ();\n }\n }\n\n public void run (String[] args) throws Exception\n {\n final Display display = new Display();\n final Shell shell = new Shell(display);\n shell.setLayout(new FillLayout());\n\n Composite composite = new Composite(shell, SWT.NO_BACKGROUND\n | SWT.EMBEDDED);\n\n System.setProperty(\"sun.awt.noerasebackground\", \"true\");\n\n /* Create and setting up frame */\n Frame frame = SWT_AWT.new_Frame(composite);\n Panel panel = new Panel(new BorderLayout()) {\n public void update(java.awt.Graphics g) {\n paint(g);\n }\n };\n frame.add(panel);\n JRootPane root = new JRootPane();\n panel.add(root);\n java.awt.Container contentPane = root.getContentPane();\n\n shell.setSize(800, 600);\n final OOoSwtViewer viewer = new OOoSwtViewer();\n contentPane.add(viewer);\n\n // viewer.setDocument(NEW_WRITTER_DOCUMENT);\n File document = new File (\"test.odt\");\n String url = document.getAbsoluteFile ().toURL ().toString ();\n url = \"file:///\" + url.substring (6);\n System.out.println (\"Loading \"+url);\n viewer.setDocument(url);\n\n shell.setText (\"OOoSwtSnippet\");\n shell.open();\n shell.addDisposeListener(new DisposeListener() {\n public void widgetDisposed(DisposeEvent e) {\n try {\n viewer.close();\n } catch (RuntimeException exception) {\n exception.printStackTrace();\n }\n }\n\n });\n while (!shell.isDisposed()) {\n if (!display.readAndDispatch())\n display.sleep();\n }\n display.dispose();\n }\n\n}\n package ooswtviewer;\n\n/**\n * Wrapper for all OO exceptions to keep throws clauses in check\n * \n * @author Aaron Digulla\n */\npublic class OOException extends RuntimeException\n{\n\n public OOException ()\n {\n super ();\n }\n\n public OOException (String message, Throwable cause)\n {\n super (message, cause);\n }\n\n public OOException (String message)\n {\n super (message);\n }\n\n public OOException (Throwable cause)\n {\n super (cause);\n }\n\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1712/" ]
81,674
<p>I am looking for an easy way to check if an object in C# is serializable.</p> <p>As we know you make an object serializable by either implementing the <em>ISerializable</em> interface or by placing the <em>[Serializable]</em> at the top of the class.</p> <p>What I am looking for is a quick way to check this without having to reflect the class to get it's attributes. The interface would be quick using an <em>is</em> statement.</p> <p>Using @Flard's suggestion this is the code that I have come up with, scream is there is a better way.</p> <pre><code>private static bool IsSerializable(T obj) { return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute)))); } </code></pre> <p>Or even better just get the type of the object and then use the IsSerializable property on the type:</p> <pre><code>typeof(T).IsSerializable </code></pre> <p>Remember though this this seems to only just the class that we are dealing with if the class contains other classes you probably want to check them all or try and serialize and wait for errors as @pb pointed out.</p>
[ { "answer_id": 81705, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": 3, "selected": false, "text": "Attribute.IsDefined(typeof (YourClass), typeof (SerializableAttribute));\n" }, { "answer_id": 81718, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 5, "selected": false, "text": "[Serializable]\npublic class A\n{\n public B B = new B();\n}\n\npublic class B\n{\n public string a = \"b\";\n}\n\n[Serializable]\npublic class C\n{\n public D D = new D();\n}\n\n[Serializable]\npublic class D\n{\n public string d = \"D\";\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n\n var a = typeof(A);\n\n var aa = new A();\n\n Console.WriteLine(\"A: {0}\", a.IsSerializable); // true (WRONG!)\n\n var c = typeof(C);\n\n Console.WriteLine(\"C: {0}\", c.IsSerializable); //true\n\n var form = new BinaryFormatter();\n // throws\n form.Serialize(new MemoryStream(), aa);\n }\n}\n" }, { "answer_id": 81762, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 8, "selected": true, "text": "Type IsSerializable" }, { "answer_id": 81833, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 3, "selected": false, "text": "public static bool IsSerializable(this object obj)\n{\n if (obj is ISerializable)\n return true;\n return Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute));\n}\n" }, { "answer_id": 82260, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "[Serializable]\npublic class MyClass\n{\n public Exception TheException; // serializable\n}\n\npublic class MyNonSerializableException : Exception\n{\n...\n}\n\n...\nMyClass myClass = new MyClass();\nmyClass.TheException = new MyNonSerializableException();\n// myClass now has a non-serializable member\n" }, { "answer_id": 4037838, "author": "Mike_G", "author_id": 52051, "author_profile": "https://Stackoverflow.com/users/52051", "pm_score": 4, "selected": false, "text": "public static bool IsSerializable(this object obj)\n{\n Type t = obj.GetType();\n\n return Attribute.IsDefined(t, typeof(DataContractAttribute)) || t.IsSerializable || (obj is IXmlSerializable)\n\n}\n" }, { "answer_id": 5913032, "author": "Eric", "author_id": 741895, "author_profile": "https://Stackoverflow.com/users/741895", "pm_score": 0, "selected": false, "text": "// Check if the exception is serializable and also the specific ones if generic\nvar exceptionType = ex.GetType();\nvar allSerializable = exceptionType.IsSerializable;\nif (exceptionType.IsGenericType)\n {\n Type[] typeArguments = exceptionType.GetGenericArguments();\n allSerializable = typeArguments.Aggregate(allSerializable, (current, tParam) => current & tParam.IsSerializable);\n }\n if (!allSerializable)\n {\n // Create a new Exception for not serializable exceptions!\n ex = new Exception(ex.Message);\n }\n" }, { "answer_id": 13054478, "author": "sewershingle", "author_id": 496047, "author_profile": "https://Stackoverflow.com/users/496047", "pm_score": 2, "selected": false, "text": " private static void NonSerializableTypesOfParentType(Type type, List<string> nonSerializableTypes)\n {\n // base case\n if (type.IsValueType || type == typeof(string)) return;\n\n if (!IsSerializable(type))\n nonSerializableTypes.Add(type.Name);\n\n foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))\n {\n if (propertyInfo.PropertyType.IsGenericType)\n {\n foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())\n {\n if (genericArgument == type) continue; // base case for circularly referenced properties\n NonSerializableTypesOfParentType(genericArgument, nonSerializableTypes);\n }\n }\n else if (propertyInfo.GetType() != type) // base case for circularly referenced properties\n NonSerializableTypesOfParentType(propertyInfo.PropertyType, nonSerializableTypes);\n }\n }\n\n private static bool IsSerializable(Type type)\n {\n return (Attribute.IsDefined(type, typeof(SerializableAttribute)));\n //return ((type is ISerializable) || (Attribute.IsDefined(type, typeof(SerializableAttribute))));\n }\n List<string> nonSerializableTypes = new List<string>();\n NonSerializableTypesOfParentType(aType, nonSerializableTypes);\n" }, { "answer_id": 25096555, "author": "ElektroStudios", "author_id": 1248295, "author_profile": "https://Stackoverflow.com/users/1248295", "pm_score": 1, "selected": false, "text": "''' <summary>\n''' Determines whether an object can be serialized.\n''' </summary>\n''' <param name=\"Object\">The object.</param>\n''' <returns><c>true</c> if object can be serialized; otherwise, <c>false</c>.</returns>\nPrivate Function IsObjectSerializable(ByVal [Object] As Object,\n Optional ByVal SerializationFormat As SerializationFormat =\n SerializationFormat.Xml) As Boolean\n\n Dim Serializer As Object\n\n Using fs As New IO.MemoryStream\n\n Select Case SerializationFormat\n\n Case Data.SerializationFormat.Binary\n Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter()\n\n Case Data.SerializationFormat.Xml\n Serializer = New Xml.Serialization.XmlSerializer([Object].GetType)\n\n Case Else\n Throw New ArgumentException(\"Invalid SerializationFormat\", SerializationFormat)\n\n End Select\n\n Try\n Serializer.Serialize(fs, [Object])\n Return True\n\n Catch ex As InvalidOperationException\n Return False\n\n End Try\n\n End Using ' fs As New MemoryStream\n\nEnd Function\n ''' <summary>\n''' Determines whether a Type can be serialized.\n''' </summary>\n''' <typeparam name=\"T\"></typeparam>\n''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>\nPrivate Function IsTypeSerializable(Of T)() As Boolean\n\n Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))\n\nEnd Function\n\n''' <summary>\n''' Determines whether a Type can be serialized.\n''' </summary>\n''' <typeparam name=\"T\"></typeparam>\n''' <param name=\"Type\">The Type.</param>\n''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>\nPrivate Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean\n\n Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))\n\nEnd Function\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231/" ]
81,686
<p>We have a NET app that gets installed to the Program Files folder. The app itself writes some files and creates some directories to its app folder. But when a normal windows user tries to use our application it crashes because that user does not have permission to write to app folder. Is there any folder in both WinXP and WinVista to which all users have writing permissions by default? All User folder or something like that?</p>
[ { "answer_id": 81738, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 0, "selected": false, "text": "<User>\\Application Data" }, { "answer_id": 81779, "author": "pilif", "author_id": 5083, "author_profile": "https://Stackoverflow.com/users/5083", "pm_score": 3, "selected": true, "text": "[Dirs]\nName: {code:getDBPath}; Flags: uninsalwaysuninstall; Permissions: authusers-modify\n\n[Code]\n\n\nfunction getDBPath(Param: String): String;\nvar\n Version: TWindowsVersion;\nbegin\n Result := ExpandConstant('{app}\\data');\n GetWindowsVersionEx(Version);\n if (Version.Major >= 5) then begin\n Result := ExpandConstant('{commonappdata}\\myprog');\n end;\nend;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15528/" ]
81,698
<p>Are the any task tracking systems with command-line interface? </p> <p>Here is a list of features I'm interested in:</p> <ul> <li>Simple task template<br> Something like plain-text file with property:type pairs, for example:</li> </ul> <blockquote> <pre><code>description:string some-property:integer required </code></pre> </blockquote> <ul> <li>command line interface<br> for example: </li> </ul> <blockquote> <pre><code>// Creates task &lt;task tracker&gt;.exe -create {description: "Foo", some-property: 1} // Search for tasks with description field starting from F &lt;task tracker&gt;.exe -find { description: "F*" } </code></pre> </blockquote> <ul> <li><p>XCopy deployment<br> It should not require to install heavy DBMS</p></li> <li><p>Multiple users support<br> So it's not just a to-do list for a single person</p></li> </ul>
[ { "answer_id": 248713, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 1, "selected": false, "text": "cal calendar" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
81,716
<p>I am trying to use MinGW to compile a C program under Windows XP. The gcc.exe gives the following error:</p> <p><strong>stdio.h : No such file or directory</strong></p> <p>The code (hello.c) looks like this:</p> <pre><code>#include &lt; stdio.h &gt; void main() { printf("\nHello World\n"); } </code></pre> <p>I use a batch file to call gcc. The batch file looks like this:</p> <pre><code>@echo off set OLDPATH=%PATH% set path=C:\devtools\MinGW\bin;%PATH% set LIBRARY_PATH=C:\devtools\MinGW\lib set C_INCLUDE_PATH=C:\devtools\MinGW\include gcc.exe hello.c set path=%OLDPATH% </code></pre> <p>I have tried the option <strong>-I</strong> without effect. What do I do wrong?</p>
[ { "answer_id": 81731, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 4, "selected": true, "text": "#include <stdio.h>\n" }, { "answer_id": 89036, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "int main(void)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565/" ]
81,723
<p>I have the concept of <code>NodeType</code>s and <code>Node</code>s. A <code>NodeType</code> is a bunch of meta-data which you can create <code>Node</code> instances from (a lot like the whole Class / Object relationship).</p> <p>I have various <code>NodeType</code> implementations and various Node implementations. </p> <p>In my AbstractNodeType (top level for NodeTypes) I have ab abstract <code>createInstance()</code> method that will, once implemented by the subclass, creates the correct Node instance:</p> <pre><code>public abstract class AbstractNodeType { // .. public abstract &lt;T extends AbstractNode&gt; T createInstance(); } </code></pre> <p>In my <code>NodeType</code> implementations I implement the method like this:</p> <pre><code>public class ThingType { // .. public Thing createInstance() { return new Thing(/* .. */); } } // FYI public class Thing extends AbstractNode { /* .. */ } </code></pre> <p>This is all well and good, but <code>public Thing createInstance()</code> creates a warning about type safety. Specifically:</p> <blockquote> <p>Type safety: The return type Thing for createInstance() from the type ThingType needs unchecked conversion to conform to T from the type AbstractNodeType</p> </blockquote> <p><strong>What am I doing wrong to cause such a warning?</strong></p> <p><strong>How can I re-factor my code to fix this?</strong></p> <p><em><code>@SuppressWarnings("unchecked")</code> is not good, I wish to fix this by coding it correctly, not ignoring the problem!</em></p>
[ { "answer_id": 81742, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": true, "text": "<T extends AbstractNode> T AbstractNode Java 5" }, { "answer_id": 81796, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 1, "selected": false, "text": "interface Node{\n}\ninterface NodeType<T extends Node>{\n T createInstance();\n}\nclass Thing implements Node{}\nclass ThingType implements NodeType<Thing>{\n public Thing createInstance() {\n return new Thing();\n }\n}\nclass UberThing extends Thing{}\nclass UberThingType extends ThingType{\n @Override\n public UberThing createInstance() {\n return new UberThing();\n }\n}\n" }, { "answer_id": 81825, "author": "UlfJack", "author_id": 15551, "author_profile": "https://Stackoverflow.com/users/15551", "pm_score": 2, "selected": false, "text": "public abstract class AbstractNodeType<T extends AbstractNode> {\n public abstract T createInstance();\n}\npublic class ThingType<Thing> {\n public Thing createInstance() {\n return new Thing(...);\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
81,730
<p>In .NET, after this code, what mechanism stops the <code>Thread</code> object from being garbage collected?</p> <pre><code>new Thread(Foo).Start(); GC.Collect(); </code></pre> <p>Yes, it's safe to assume <strong>something</strong> has a reference to the thread, I was just wandering what exactly. For some reason Reflector doesn't show me <code>System.Threading</code>, so I can't dig it myself (I know MS released the source code for the .NET framework, I just don't have it handy).</p>
[ { "answer_id": 81755, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": -1, "selected": false, "text": "class YourClass\n{\n Thread thread;\n\n void Start()\n {\n thread = new Thread(Foo);\n thread.Start();\n GC.Collect();\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
81,732
<p>I've got a virtual machine running on a server that I can't stop or reboot - I can't log onto it anymore and I can't stop it using the VMware server console. There are other VM's running so rebooting the host is out of the question. Is there any other way of forcing one machine to stop?</p>
[ { "answer_id": 81761, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 4, "selected": false, "text": "ps axuw | grep vmware-vmx\n" }, { "answer_id": 7330794, "author": "Daniel Tallentire", "author_id": 502968, "author_profile": "https://Stackoverflow.com/users/502968", "pm_score": 2, "selected": false, "text": "WMIC /OUTPUT:C:\\ProcessList.txt PROCESS get Caption,Commandline,Processid\n" }, { "answer_id": 7355916, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 2, "selected": false, "text": "ps -c | grep -i \"machine name\"\n kill" }, { "answer_id": 18872792, "author": "Jocelyn", "author_id": 1926197, "author_profile": "https://Stackoverflow.com/users/1926197", "pm_score": 2, "selected": false, "text": "You cannot power off an ESXi hosted virtual machine.\nA virtual machine is not responsive and cannot be stopped or killed.\n Open a console session where the esxcli tool is available, either in the ESXi Shell, the vSphere Management Assistant (vMA), or the location where the vSphere Command-Line Interface (vCLI) is installed.\n\nGet a list of running virtual machines, identified by World ID, UUID, Display Name, and path to the .vmx configuration file, using this command:\n\nesxcli vm process list\n\nPower off one of the virtual machines from the list using this command:\n\nesxcli vm process kill --type=[soft,hard,force] --world-id=WorldNumber\n\nNotes:\nThree power-off methods are available. Soft is the most graceful, hard performs an immediate shutdown, and force should be used as a last resort.\nAlternate power off command syntax is: esxcli vm process kill -t [soft,hard,force] -w WorldNumber\n\nRepeat Step 2 and validate that the virtual machine is no longer running.\n Get a list of running virtual machines, identified by World ID, UUID, Display Name, and path to the .vmx configuration file, using this command:\n\nesxcli vms vm list\n\nPower off one of the virtual machines from the list using this command:\n\nesxcli vms vm kill --type=[soft,hard,force] --world-id=WorldNumber\"\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271/" ]
81,784
<p>How do you usually go about <strong>separating your codebase and associated unit tests</strong>? I know people who create a separate project for unit tests, which I personally find confusing and difficult to maintain. On the other hand, if you mix up code and its tests in a single project, you end up with binaries related to your unit test framework (be it NUnit, MbUnit or whatever else) and your own binaries side by side.</p> <p>This is fine for debugging, but once I build a <strong>release version</strong>, I really do not want my code to <strong>reference the unit testing framework</strong> any more.</p> <p>One solution I found is to enclose all your unit tests within #if DEBUG -- #endif directives: when no code references an unit testing assembly, the compiler is clever enough to omit the reference in the compiled code.</p> <p>Are there any other (possibly more comfortable) options to achieve a similar goal?</p>
[ { "answer_id": 81881, "author": "Morten Christiansen", "author_id": 4055, "author_profile": "https://Stackoverflow.com/users/4055", "pm_score": 4, "selected": false, "text": "[assembly: InternalsVisibleTo(\"UnitTestProjectName\")]\n" }, { "answer_id": 81922, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 0, "selected": false, "text": "#if TEST\n#endif\n" }, { "answer_id": 121090, "author": "user21114", "author_id": 21114, "author_profile": "https://Stackoverflow.com/users/21114", "pm_score": 3, "selected": false, "text": "<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n\n ...\n\n <Reference Include=\"nunit.framework\" Condition=\" '$(Configuration)'=='Debug' \">\n <SpecificVersion>False</SpecificVersion>\n <HintPath>..\\..\\debug\\nunit.framework.dll</HintPath>\n </Reference>\n\n ...\n\n <Compile Include=\"Test\\ClassTest.cs\" Condition=\" '$(Configuration)'=='Debug' \" />\n\n ...\n</Project>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15497/" ]
81,786
<p>I'd like to add a method <code>AddDefaultNamespace()</code> to the String class in Java so that I can type <code>"myString".AddDefaultNamespace()</code> instead of <code>DEFAULTNAMESPACE + "myString"</code>, to obtain something like <code>"MyDefaultNameSpace.myString"</code>. I don't want to add another derived class either (<code>PrefixedString</code> for example).</p> <p>Maybe the approach is not good for you but I personally hate using <code>+</code>. But, anyway, is it possible to add new methods to the String class in Java?</p> <p>Thanks and regards.</p>
[ { "answer_id": 81803, "author": "GustyWind", "author_id": 11114, "author_profile": "https://Stackoverflow.com/users/11114", "pm_score": 7, "selected": true, "text": "String" }, { "answer_id": 81871, "author": "Carl-Johan", "author_id": 15406, "author_profile": "https://Stackoverflow.com/users/15406", "pm_score": 2, "selected": false, "text": "public final class String\n private String someMethod(String s)\n{\n return s.substring(0,1);\n\n}\n\nvoid main(String[] args)\n{\n String s1 = \"hello\";\n String s2 = s1.someMethod();\n System.out.println(s2);\n\n}\n" }, { "answer_id": 81946, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 2, "selected": false, "text": "public final class NamespaceUtil {\n\n // private constructor cos this class only has a static method.\n private NamespaceUtil() {}\n\n public static String getDefaultNamespacedString(\n final String afterDotString) {\n return DEFAULT_NAMESPACE + \".\" + afterDotString;\n }\n\n}\n public final class NamespacedStringFactory {\n\n private final String namespace;\n\n public NamespacedStringFactory(final String namespace) {\n this.namespace = namespace;\n }\n\n public String getNamespacedString(final String afterDotString) {\n return namespace + \".\" + afterDotString;\n }\n\n}\n" }, { "answer_id": 2077551, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "object Snippet {\n class MyString(s:String) {\n def addDefaultNamespace = println(\"AddDefaultNamespace called\")\n }\n implicit def wrapIt(s:String) = new MyString(s)\n\n /** test driver */\n def main(args:Array[String]):Unit = {\n \"any java.io.String\".addDefaultNamespace // !!! THAT is IT! OR?\n }\n" }, { "answer_id": 6806424, "author": "Aldo Barreras", "author_id": 860157, "author_profile": "https://Stackoverflow.com/users/860157", "pm_score": 5, "selected": false, "text": "class MyString{\n public String str;\n public MyString(String str){\n this.str = str;\n }\n // Your methods.\n}\n MyString StringOne = new MyString(\"Stringy stuff\");\n StringOne.str.equals(\"\");\n" }, { "answer_id": 37406295, "author": "Drunken Daddy", "author_id": 2067264, "author_profile": "https://Stackoverflow.com/users/2067264", "pm_score": 2, "selected": false, "text": "public class ObjectMap extends HashMap<String, Object> {\n\n public Map<String, Object> map;\n\n public ObjectMap(Map<String, Object> map){\n this.map = map;\n }\n\n public int getInt(String K) {\n return Integer.valueOf(map.get(K).toString());\n }\n\n public String getString(String K) {\n return String.valueOf(map.get(K));\n }\n\n public boolean getBoolean(String K) {\n return Boolean.valueOf(map.get(K).toString());\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<String> getListOfStrings(String K) {\n return (List<String>) map.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<Integer> getListOfIntegers(String K) {\n return (List<Integer>) map.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<Map<String, String>> getListOfMapString(String K) {\n return (List<Map<String, String>>) map.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<Map<String, Object>> getListOfMapObject(String K) {\n return (List<Map<String, Object>>) map.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public Map<String, Object> getMapOfObjects(String K) {\n return (Map<String, Object>) map.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public Map<String, String> getMapOfStrings(String K) {\n return (Map<String, String>) map.get(K);\n }\n}\n ObjectMap objectMap = new ObjectMap(new HashMap<String, Object>();\n objectMap.getInt(\"KEY\");\n objectMap.map.get(\"KEY\");\n public class ObjectMap extends HashMap<String, Object> {\n\n public ObjectMap() {\n\n }\n\n public ObjectMap(Map<String, Object> map){\n this.putAll(map);\n }\n\n public int getInt(String K) {\n return Integer.valueOf(this.get(K).toString());\n }\n\n public String getString(String K) {\n return String.valueOf(this.get(K));\n }\n\n public boolean getBoolean(String K) {\n return Boolean.valueOf(this.get(K).toString());\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<String> getListOfStrings(String K) {\n return (List<String>) this.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<Integer> getListOfIntegers(String K) {\n return (List<Integer>) this.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<Map<String, String>> getListOfMapString(String K) {\n return (List<Map<String, String>>) this.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<Map<String, Object>> getListOfMapObject(String K) {\n return (List<Map<String, Object>>) this.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public Map<String, Object> getMapOfObjects(String K) {\n return (Map<String, Object>) this.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public Map<String, String> getMapOfStrings(String K) {\n return (Map<String, String>) this.get(K);\n }\n\n @SuppressWarnings(\"unchecked\")\n public boolean getBooleanForInt(String K) {\n return Integer.valueOf(this.get(K).toString()) == 1 ? true : false;\n }\n}\n objectMap.map.get(\"KEY\");\n objectMap.get(\"KEY\");\n" }, { "answer_id": 50412907, "author": "PaulB", "author_id": 5335776, "author_profile": "https://Stackoverflow.com/users/5335776", "pm_score": 2, "selected": false, "text": "String i = \"This is my String\";\ni.numberOfCapitalCharacters(); // = 2\n compileOnly 'org.projectlombok:lombok:1.16.20' \"Settings > Build > Compiler > Annotation Processors\" public class Extension {\n public static String appendSize(String i){\n return i + \" \" + i.length();\n }\n}\n import lombok.experimental.ExtensionMethod;\n\n@ExtensionMethod({Extension.class})\npublic class Main {\n public static void main(String[] args) {\n String i = \"This is a String!\";\n System.out.println(i.appendSize());\n }\n}\n .appendSize()" }, { "answer_id": 74656039, "author": "Ogün", "author_id": 10480017, "author_profile": "https://Stackoverflow.com/users/10480017", "pm_score": 0, "selected": false, "text": "@file:JvmName(\"StringUtil\")\npackage com.example\n\nfun main() {\nval x: String = \"xxx\"\nprintln(x.customMethod())\n}\n\nfun String.customMethod(): String = this + \" ZZZZ\"\n package com.example;\n\npublic class AppStringCustomMethod {\n\npublic static void main(String[] args) {\n String kotlinResponse = StringUtil.customMethod(\"ffff\");\n System.out.println(kotlinResponse);\n}\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15546/" ]
81,788
<p>I couldn't find a decent ThreadPool implementation for Ruby, so I wrote mine (based partly on code from here: <a href="http://web.archive.org/web/20081204101031/http://snippets.dzone.com:80/posts/show/3276" rel="nofollow noreferrer">http://web.archive.org/web/20081204101031/http://snippets.dzone.com:80/posts/show/3276</a> , but changed to wait/signal and other implementation for ThreadPool shutdown. However after some time of running (having 100 threads and handling about 1300 tasks), it dies with deadlock on line 25 - it waits for a new job there. Any ideas, why it might happen?</p> <pre><code>require 'thread' begin require 'fastthread' rescue LoadError $stderr.puts "Using the ruby-core thread implementation" end class ThreadPool class Worker def initialize(callback) @mutex = Mutex.new @cv = ConditionVariable.new @callback = callback @mutex.synchronize {@running = true} @thread = Thread.new do while @mutex.synchronize {@running} block = get_block if block block.call reset_block # Signal the ThreadPool that this worker is ready for another job @callback.signal else # Wait for a new job @mutex.synchronize {@cv.wait(@mutex)} # &lt;=== Is this line 25? end end end end def name @thread.inspect end def get_block @mutex.synchronize {@block} end def set_block(block) @mutex.synchronize do raise RuntimeError, "Thread already busy." if @block @block = block # Signal the thread in this class, that there's a job to be done @cv.signal end end def reset_block @mutex.synchronize {@block = nil} end def busy? @mutex.synchronize {[email protected]?} end def stop @mutex.synchronize {@running = false} # Signal the thread not to wait for a new job @cv.signal @thread.join end end attr_accessor :max_size def initialize(max_size = 10) @max_size = max_size @workers = [] @mutex = Mutex.new @cv = ConditionVariable.new end def size @mutex.synchronize {@workers.size} end def busy? @mutex.synchronize {@workers.any? {|w| w.busy?}} end def shutdown @mutex.synchronize {@workers.each {|w| w.stop}} end alias :join :shutdown def process(block=nil,&amp;blk) block = blk if block_given? while true @mutex.synchronize do worker = get_worker if worker return worker.set_block(block) else # Wait for a free worker @cv.wait(@mutex) end end end end # Used by workers to report ready status def signal @cv.signal end private def get_worker free_worker || create_worker end def free_worker @workers.each {|w| return w unless w.busy?}; nil end def create_worker return nil if @workers.size &gt;= @max_size worker = Worker.new(self) @workers &lt;&lt; worker worker end end </code></pre>
[ { "answer_id": 82061, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 1, "selected": false, "text": "def signal\n @mutex.synchronize { @cv.signal }\nend\n def initialize(callback)\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @callback = callback\n @mutex.synchronize {@running = true}\n @thread = Thread.new do\n @mutex.synchronize do\n while @running\n block = get_block\n if block\n @mutex.unlock\n block.call\n @mutex.lock\n reset_block\n # Signal the ThreadPool that this worker is ready for another job\n @callback.signal\n else\n # Wait for a new job\n @cv.wait(@mutex)\n end\n end\n end\n end\nend\n" }, { "answer_id": 82777, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 5, "selected": true, "text": "require 'thread'\nbegin\n require 'fasttread'\nrescue LoadError\n $stderr.puts \"Using the ruby-core thread implementation\"\nend\n\nclass ThreadPool\n class Worker\n def initialize(thread_queue)\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @queue = thread_queue\n @running = true\n @thread = Thread.new do\n @mutex.synchronize do\n while @running\n @cv.wait(@mutex)\n block = get_block\n if block\n @mutex.unlock\n block.call\n @mutex.lock\n reset_block\n end\n @queue << self\n end\n end\n end\n end\n\n def name\n @thread.inspect\n end\n\n def get_block\n @block\n end\n\n def set_block(block)\n @mutex.synchronize do\n raise RuntimeError, \"Thread already busy.\" if @block\n @block = block\n # Signal the thread in this class, that there's a job to be done\n @cv.signal\n end\n end\n\n def reset_block\n @block = nil\n end\n\n def busy?\n @mutex.synchronize { [email protected]? }\n end\n\n def stop\n @mutex.synchronize do\n @running = false\n @cv.signal\n end\n @thread.join\n end\n end\n\n attr_accessor :max_size\n\n def initialize(max_size = 10)\n @max_size = max_size\n @queue = Queue.new\n @workers = []\n end\n\n def size\n @workers.size\n end\n\n def busy?\n @queue.size < @workers.size\n end\n\n def shutdown\n @workers.each { |w| w.stop }\n @workers = []\n end\n\n alias :join :shutdown\n\n def process(block=nil,&blk)\n block = blk if block_given?\n worker = get_worker\n worker.set_block(block)\n end\n\n private\n\n def get_worker\n if [email protected]? or @workers.size == @max_size\n return @queue.pop\n else\n worker = Worker.new(@queue)\n @workers << worker\n worker\n end\n end\n\nend\n tp = ThreadPool.new 500\n(1..1000).each { |i| tp.process { (2..10).inject(1) { |memo,val| sleep(0.1); memo*val }; print \"Computation #{i} done. Nb of tasks: #{tp.size}\\n\" } }\ntp.shutdown\n" }, { "answer_id": 51769759, "author": "bking", "author_id": 7915982, "author_profile": "https://Stackoverflow.com/users/7915982", "pm_score": 1, "selected": false, "text": "# Usage:\n#\n# Thread.abort_on_exception = true # help localize errors while debugging\n# pool = ThreadPool.new(thread_pool_size)\n# 50.times {|i|\n# pool.process { ... }\n# or\n# pool.process {|id| ... } # worker identifies itself as id\n# }\n# pool.shutdown()\n\nclass ThreadPool\n\n require 'thread'\n\n class ThreadPoolWorker\n\n attr_accessor :id\n\n def initialize(thread_queue, id)\n @id = id # worker id is exposed thru tp.process {|id| ... }\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @idle_queue = thread_queue\n @running = true\n @block = nil\n @thread = Thread.new {\n @mutex.synchronize {\n while @running\n @cv.wait(@mutex) # block until there is work to do\n if @block\n @mutex.unlock\n begin\n @block.call(@id)\n ensure\n @mutex.lock\n end\n @block = nil\n end\n @idle_queue << self\n end\n }\n }\n end\n\n def set_block(block)\n @mutex.synchronize {\n raise RuntimeError, \"Thread is busy.\" if @block\n @block = block\n @cv.signal # notify thread in this class, there is work to be done\n }\n end\n\n def busy?\n @mutex.synchronize { ! @block.nil? }\n end\n\n def stop\n @mutex.synchronize {\n @running = false\n @cv.signal\n }\n @thread.join\n end\n\n def name\n @thread.inspect\n end\n end\n\n\n attr_accessor :max_size, :queue\n\n def initialize(max_size = 10)\n @process_mutex = Mutex.new\n @max_size = max_size\n @queue = Queue.new # of idle workers\n @workers = [] # array to hold workers\n\n # construct workers\n @max_size.times {|i| @workers << ThreadPoolWorker.new(@queue, i) }\n\n # queue up workers (workers in queue are idle and available to\n # work). queue blocks if no workers are available.\n @max_size.times {|i| @queue << @workers[i] }\n\n sleep 1 # important to give threads a chance to initialize\n end\n\n def size\n @workers.size\n end\n\n def idle\n @queue.size\n end\n\n # are any threads idle\n\n def busy?\n # @queue.size < @workers.size\n @queue.size == 0 && @workers.size == @max_size\n end\n\n # block until all threads finish\n\n def shutdown\n @workers.each {|w| w.stop }\n @workers = []\n end\n\n alias :join :shutdown\n\n def process(block = nil, &blk)\n @process_mutex.synchronize {\n block = blk if block_given?\n worker = @queue.pop # assign to next worker; block until one is ready\n worker.set_block(block) # give code block to worker and tell it to start\n }\n end\n\n\nend\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12695/" ]
81,830
<p>Grails vs Rails. Which has better support? And which one is a better choice to develop medium size apps with? Most importantly which one has more plug-ins?</p>
[ { "answer_id": 1194141, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "gem install mysql" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15476/" ]
81,862
<p>I'd like to encourage our users of our RCP application to send the problem details to our support department. To this end, I've added a "Contact support" widget to our standard error dialogue.</p> <p>I've managed to use URI headers to send a stacktrace using Java 6's JDIC call: <a href="http://java.sun.com/javase/6/docs/api/java/net/URI.html" rel="nofollow noreferrer"><code>Desktop.getDesktop().mail(java.net.URI)</code></a>. This will fire up the user's mail client, ready for them to add their comments, and hit send. </p> <p>I like firing up the email client, because it's what the user is used to, it tells support a whole lot about the user (sigs, contact details etc) and I don't really want <a href="http://www.catb.org/~esr/jargon/html/Z/Zawinskis-Law.html" rel="nofollow noreferrer">to ship with Java Mail</a>.</p> <p>What I'd like to do is attach the log file and the stacktrace as a file, so there is no maximum length requirement, and the user sees a nice clean looking email, and the support department has a lot more information to work with.</p> <p>Can I do this with the approach I'm taking? Or is there a better way?</p> <p><strong>Edit</strong>: I'm in an OSGi context, so bundling JDIC would be necessary. If possible, I'd like to ship with as few dependencies as possible, and bundling up the JDIC for multiple platforms does not sound fun, especially for such a small feature.</p> <p>JavaMail may be suitable, but for the fact that this will be on desktops of our corporate clients. The <strong>setup/discovery of configuration</strong> would have to be transparent, automatic and reliable. Regarding JavaMail, configuration seems to be manual only. Is this the case?</p> <p>The answer I like most is using the <code>Desktop.open()</code> for an *.eml file. Unfortunately <strong>Outlook Express (rather than Outlook) opens eml files</strong>. I have no idea if this is usual or default to have Windows configured for to open EML files like this. Is this usual? Or is there another text based format that a) is easy to generate, b) opens by default in the same email client as users would be using already?</p>
[ { "answer_id": 81882, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 0, "selected": false, "text": "mailto:[email protected]?SUBJECT=Support mail&BODY=This is a support mail\n" }, { "answer_id": 4014528, "author": "Joeky", "author_id": 486406, "author_profile": "https://Stackoverflow.com/users/486406", "pm_score": 0, "selected": false, "text": "import java.awt.Desktop;\nimport java.io.File;\nimport java.net.URI;\n\n\npublic class TestMail {\n\n public static void main(String[] args) {\n try { \n Runtime.getRuntime().exec(\n new String[] {\"rundll32\", \"url.dll,FileProtocolHandler\",\n \"mailto:[email protected]?subject=someSubject&[email protected]&[email protected]&body=someBodyText&Attach=c:\\\\test\\\\test.doc\"}, null\n );\n\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737/" ]
81,870
<p>For example:</p> <pre><code>int a = 12; cout &lt;&lt; typeof(a) &lt;&lt; endl; </code></pre> <p>Expected output:</p> <pre><code>int </code></pre>
[ { "answer_id": 81886, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": false, "text": "#include <typeinfo>\n\n// …\nstd::cout << typeid(a).name() << '\\n';\n" }, { "answer_id": 81913, "author": "mdec", "author_id": 15534, "author_profile": "https://Stackoverflow.com/users/15534", "pm_score": 6, "selected": false, "text": "<typeinfo> #include <iostream>\n#include <typeinfo>\n\nusing namespace std;\n\nint main() {\n int i;\n cout << typeid(i).name();\n return 0;\n}\n" }, { "answer_id": 81939, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\ntemplate <typename T> class type_name {\npublic:\n static const char *name;\n};\n\n#define DECLARE_TYPE_NAME(x) template<> const char *type_name<x>::name = #x;\n#define GET_TYPE_NAME(x) (type_name<typeof(x)>::name)\n\nDECLARE_TYPE_NAME(int);\n\nint main()\n{\n int a = 12;\n cout << GET_TYPE_NAME(a) << endl;\n}\n DECLARE_TYPE_NAME typeid typeid long long" }, { "answer_id": 81956, "author": "Nick", "author_id": 3233, "author_profile": "https://Stackoverflow.com/users/3233", "pm_score": 5, "selected": false, "text": "template <typename T> const char* typeof(T&) { return \"unknown\"; } // default\ntemplate<> const char* typeof(int&) { return \"int\"; }\ntemplate<> const char* typeof(float&) { return \"float\"; }\n" }, { "answer_id": 82102, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": false, "text": "MyNamespace::CMyContainer<int, test_MyNamespace::CMyObject>\n // MSVC 2003:\nclass MyNamespace::CMyContainer[int,class test_MyNamespace::CMyObject]\n// G++ 4.2:\nN8MyNamespace8CMyContainerIiN13test_MyNamespace9CMyObjectEEE\n" }, { "answer_id": 82144, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 3, "selected": false, "text": "template <typename T> struct type_as_string;\n\n// declare your Wibble type (probably with definition of Wibble)\ntemplate <>\nstruct type_as_string<Wibble>\n{\n static const char* const value = \"Wibble\";\n};\n template <typename T>\nconst char* get_type_as_string(const T&)\n{\n return type_as_string<T>::value;\n}\n" }, { "answer_id": 14617848, "author": "NickV", "author_id": 1617892, "author_profile": "https://Stackoverflow.com/users/1617892", "pm_score": 7, "selected": false, "text": "auto testVar = std::make_tuple(1, 1.0, \"abc\");\ndecltype(testVar)::foo= 1;\n Compilation finished with errors:\nsource.cpp: In function 'int main()':\nsource.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'\n" }, { "answer_id": 14633413, "author": "ipapadop", "author_id": 487362, "author_profile": "https://Stackoverflow.com/users/487362", "pm_score": 5, "selected": false, "text": "typeid().name() #include <cxxabi.h>\n#include <iostream>\n#include <typeinfo>\n#include <cstdlib>\n\nnamespace some_namespace { namespace another_namespace {\n\n class my_class { };\n\n} }\n\nint main() {\n typedef some_namespace::another_namespace::my_class my_type;\n // mangled\n std::cout << typeid(my_type).name() << std::endl;\n\n // unmangled\n int status = 0;\n char* demangled = abi::__cxa_demangle(typeid(my_type).name(), 0, 0, &status);\n\n switch (status) {\n case -1: {\n // could not allocate memory\n std::cout << \"Could not allocate memory\" << std::endl;\n return -1;\n } break;\n case -2: {\n // invalid name under the C++ ABI mangling rules\n std::cout << \"Invalid name\" << std::endl;\n return -1;\n } break;\n case -3: {\n // invalid argument\n std::cout << \"Invalid argument to demangle()\" << std::endl;\n return -1;\n } break;\n }\n std::cout << demangled << std::endl;\n\n free(demangled);\n\n return 0;\n" }, { "answer_id": 20170989, "author": "Howard Hinnant", "author_id": 576911, "author_profile": "https://Stackoverflow.com/users/576911", "pm_score": 11, "selected": true, "text": "typeid(a).name() a decltype(x) decltype() decltype(a) decltype((a)) typeid(a).name() typeid(a).name() typeid(a).name() typeid(a).name()\n const int ci = 0;\nstd::cout << typeid(ci).name() << '\\n';\n i\n int\n const template <typename T> std::string type_name();\n const int ci = 0;\nstd::cout << type_name<decltype(ci)>() << '\\n';\n int const\n <disclaimer> </disclaimer> __cxa_demangle typeid #include <type_traits>\n#include <typeinfo>\n#ifndef _MSC_VER\n# include <cxxabi.h>\n#endif\n#include <memory>\n#include <string>\n#include <cstdlib>\n\ntemplate <class T>\nstd::string\ntype_name()\n{\n typedef typename std::remove_reference<T>::type TR;\n std::unique_ptr<char, void(*)(void*)> own\n (\n#ifndef _MSC_VER\n abi::__cxa_demangle(typeid(TR).name(), nullptr,\n nullptr, nullptr),\n#else\n nullptr,\n#endif\n std::free\n );\n std::string r = own != nullptr ? own.get() : typeid(TR).name();\n if (std::is_const<TR>::value)\n r += \" const\";\n if (std::is_volatile<TR>::value)\n r += \" volatile\";\n if (std::is_lvalue_reference<T>::value)\n r += \"&\";\n else if (std::is_rvalue_reference<T>::value)\n r += \"&&\";\n return r;\n}\n int& foo_lref();\nint&& foo_rref();\nint foo_value();\n\nint\nmain()\n{\n int i = 0;\n const int ci = 0;\n std::cout << \"decltype(i) is \" << type_name<decltype(i)>() << '\\n';\n std::cout << \"decltype((i)) is \" << type_name<decltype((i))>() << '\\n';\n std::cout << \"decltype(ci) is \" << type_name<decltype(ci)>() << '\\n';\n std::cout << \"decltype((ci)) is \" << type_name<decltype((ci))>() << '\\n';\n std::cout << \"decltype(static_cast<int&>(i)) is \" << type_name<decltype(static_cast<int&>(i))>() << '\\n';\n std::cout << \"decltype(static_cast<int&&>(i)) is \" << type_name<decltype(static_cast<int&&>(i))>() << '\\n';\n std::cout << \"decltype(static_cast<int>(i)) is \" << type_name<decltype(static_cast<int>(i))>() << '\\n';\n std::cout << \"decltype(foo_lref()) is \" << type_name<decltype(foo_lref())>() << '\\n';\n std::cout << \"decltype(foo_rref()) is \" << type_name<decltype(foo_rref())>() << '\\n';\n std::cout << \"decltype(foo_value()) is \" << type_name<decltype(foo_value())>() << '\\n';\n}\n decltype(i) is int\ndecltype((i)) is int&\ndecltype(ci) is int const\ndecltype((ci)) is int const&\ndecltype(static_cast<int&>(i)) is int&\ndecltype(static_cast<int&&>(i)) is int&&\ndecltype(static_cast<int>(i)) is int\ndecltype(foo_lref()) is int&\ndecltype(foo_rref()) is int&&\ndecltype(foo_value()) is int\n decltype(i) decltype((i)) i i decltype decltype typeid(a).name() decltype(i) is int\ndecltype((i)) is int\ndecltype(ci) is int\ndecltype((ci)) is int\ndecltype(static_cast<int&>(i)) is int\ndecltype(static_cast<int&&>(i)) is int\ndecltype(static_cast<int>(i)) is int\ndecltype(foo_lref()) is int\ndecltype(foo_rref()) is int\ndecltype(foo_value()) is int\n #include <cstddef>\n#include <stdexcept>\n#include <cstring>\n#include <ostream>\n\n#ifndef _MSC_VER\n# if __cplusplus < 201103\n# define CONSTEXPR11_TN\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN\n# elif __cplusplus < 201402\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN noexcept\n# else\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN constexpr\n# define NOEXCEPT_TN noexcept\n# endif\n#else // _MSC_VER\n# if _MSC_VER < 1900\n# define CONSTEXPR11_TN\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN\n# elif _MSC_VER < 2000\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN noexcept\n# else\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN constexpr\n# define NOEXCEPT_TN noexcept\n# endif\n#endif // _MSC_VER\n\nclass static_string\n{\n const char* const p_;\n const std::size_t sz_;\n\npublic:\n typedef const char* const_iterator;\n\n template <std::size_t N>\n CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN\n : p_(a)\n , sz_(N-1)\n {}\n\n CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN\n : p_(p)\n , sz_(N)\n {}\n\n CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;}\n CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;}\n\n CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;}\n CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN {return p_ + sz_;}\n\n CONSTEXPR11_TN char operator[](std::size_t n) const\n {\n return n < sz_ ? p_[n] : throw std::out_of_range(\"static_string\");\n }\n};\n\ninline\nstd::ostream&\noperator<<(std::ostream& os, static_string const& s)\n{\n return os.write(s.data(), s.size());\n}\n\ntemplate <class T>\nCONSTEXPR14_TN\nstatic_string\ntype_name()\n{\n#ifdef __clang__\n static_string p = __PRETTY_FUNCTION__;\n return static_string(p.data() + 31, p.size() - 31 - 1);\n#elif defined(__GNUC__)\n static_string p = __PRETTY_FUNCTION__;\n# if __cplusplus < 201402\n return static_string(p.data() + 36, p.size() - 36 - 1);\n# else\n return static_string(p.data() + 46, p.size() - 46 - 1);\n# endif\n#elif defined(_MSC_VER)\n static_string p = __FUNCSIG__;\n return static_string(p.data() + 38, p.size() - 38 - 7);\n#endif\n}\n constexpr noexcept std::string_view static_string template <class T>\nconstexpr\nstd::string_view\ntype_name()\n{\n using namespace std;\n#ifdef __clang__\n string_view p = __PRETTY_FUNCTION__;\n return string_view(p.data() + 34, p.size() - 34 - 1);\n#elif defined(__GNUC__)\n string_view p = __PRETTY_FUNCTION__;\n# if __cplusplus < 201402\n return string_view(p.data() + 36, p.size() - 36 - 1);\n# else\n return string_view(p.data() + 49, p.find(';', 49) - 49);\n# endif\n#elif defined(_MSC_VER)\n string_view p = __FUNCSIG__;\n return string_view(p.data() + 84, p.size() - 84 - 7);\n#endif\n}\n" }, { "answer_id": 29040615, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 3, "selected": false, "text": "template <typename T> const char* typeof(T&) { return \"unknown\"; } // default\ntemplate<> const char* typeof(int&) { return \"int\"; }\ntemplate<> const char* typeof(short&) { return \"short\"; }\ntemplate<> const char* typeof(long&) { return \"long\"; }\ntemplate<> const char* typeof(unsigned&) { return \"unsigned\"; }\ntemplate<> const char* typeof(unsigned short&) { return \"unsigned short\"; }\ntemplate<> const char* typeof(unsigned long&) { return \"unsigned long\"; }\ntemplate<> const char* typeof(float&) { return \"float\"; }\ntemplate<> const char* typeof(double&) { return \"double\"; }\ntemplate<> const char* typeof(long double&) { return \"long double\"; }\ntemplate<> const char* typeof(std::string&) { return \"String\"; }\ntemplate<> const char* typeof(char&) { return \"char\"; }\ntemplate<> const char* typeof(signed char&) { return \"signed char\"; }\ntemplate<> const char* typeof(unsigned char&) { return \"unsigned char\"; }\ntemplate<> const char* typeof(char*&) { return \"char*\"; }\ntemplate<> const char* typeof(signed char*&) { return \"signed char*\"; }\ntemplate<> const char* typeof(unsigned char*&) { return \"unsigned char*\"; }\n" }, { "answer_id": 29043884, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 3, "selected": false, "text": "template<typename T>\nstd::string TypeOf(T){\n std::string Type=\"unknown\";\n if(std::is_same<T,int>::value) Type=\"int\";\n if(std::is_same<T,std::string>::value) Type=\"String\";\n if(std::is_same<T,MyClass>::value) Type=\"MyClass\";\n\n return Type;}\n #include <iostream>\n\n\n\nclass MyClass{};\n\n\ntemplate<typename T>\nstd::string TypeOf(T){\n std::string Type=\"unknown\";\n if(std::is_same<T,int>::value) Type=\"int\";\n if(std::is_same<T,std::string>::value) Type=\"String\";\n if(std::is_same<T,MyClass>::value) Type=\"MyClass\";\n return Type;}\n\n\nint main(){;\n int a=0;\n std::string s=\"\";\n MyClass my;\n std::cout<<TypeOf(a)<<std::endl;\n std::cout<<TypeOf(s)<<std::endl;\n std::cout<<TypeOf(my)<<std::endl;\n\n return 0;}\n int\nString\nMyClass\n" }, { "answer_id": 35703301, "author": "Alan", "author_id": 1691719, "author_profile": "https://Stackoverflow.com/users/1691719", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <typeinfo>\n#include <string>\n\nusing namespace std;\n\nint main() {\n auto x = 1;\n string my_type = typeid(x).name();\n system((\"echo \" + my_type + \" | c++filt -t\").c_str());\n return 0;\n}\n" }, { "answer_id": 39937286, "author": "abodeofcode", "author_id": 6942726, "author_profile": "https://Stackoverflow.com/users/6942726", "pm_score": 4, "selected": false, "text": "type_id_with_cvr #include <iostream>\n#include <boost/type_index.hpp>\n\nusing namespace std;\nusing boost::typeindex::type_id_with_cvr;\n\nint main() {\n int i = 0;\n const int ci = 0;\n cout << \"decltype(i) is \" << type_id_with_cvr<decltype(i)>().pretty_name() << '\\n';\n cout << \"decltype((i)) is \" << type_id_with_cvr<decltype((i))>().pretty_name() << '\\n';\n cout << \"decltype(ci) is \" << type_id_with_cvr<decltype(ci)>().pretty_name() << '\\n';\n cout << \"decltype((ci)) is \" << type_id_with_cvr<decltype((ci))>().pretty_name() << '\\n';\n cout << \"decltype(std::move(i)) is \" << type_id_with_cvr<decltype(std::move(i))>().pretty_name() << '\\n';\n cout << \"decltype(std::static_cast<int&&>(i)) is \" << type_id_with_cvr<decltype(static_cast<int&&>(i))>().pretty_name() << '\\n';\n return 0;\n}\n" }, { "answer_id": 45457278, "author": "Graywolf", "author_id": 7138477, "author_profile": "https://Stackoverflow.com/users/7138477", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <typeinfo>\nusing namespace std;\n#define show_type_name(_t) \\\n system((\"echo \" + string(typeid(_t).name()) + \" | c++filt -t\").c_str())\n\nint main() {\n auto a = {\"one\", \"two\", \"three\"};\n cout << \"Type of a: \" << typeid(a).name() << endl;\n cout << \"Real type of a:\\n\";\n show_type_name(a);\n for (auto s : a) {\n if (string(s) == \"one\") {\n cout << \"Type of s: \" << typeid(s).name() << endl;\n cout << \"Real type of s:\\n\";\n show_type_name(s);\n }\n cout << s << endl;\n }\n\n int i = 5;\n cout << \"Type of i: \" << typeid(i).name() << endl;\n cout << \"Real type of i:\\n\";\n show_type_name(i);\n return 0;\n}\n Type of a: St16initializer_listIPKcE\nReal type of a:\nstd::initializer_list<char const*>\nType of s: PKc\nReal type of s:\nchar const*\none\ntwo\nthree\nType of i: i\nReal type of i:\nint\n" }, { "answer_id": 45743053, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 3, "selected": false, "text": "typeid(T).name() TYPE_NAME(int)\nTYPE_NAME(void)\n// You probably should list all primitive types here.\n\nTYPE_NAME(std::string)\n\nint main()\n{\n // A simple case\n std::cout << type_name<void(*)(int)> << '\\n';\n // -> `void (*)(int)`\n\n // Ugly mess case\n // Note that compiler removes cv-qualifiers from parameters and replaces arrays with pointers.\n std::cout << type_name<void (std::string::*(int[3],const int, void (*)(std::string)))(volatile int*const*)> << '\\n';\n // -> `void (std::string::*(int *,int,void (*)(std::string)))(volatile int *const*)`\n\n // A case with undefined types\n // If a type wasn't TYPE_NAME'd, it's replaced by a placeholder, one of `class?`, `union?`, `enum?` or `??`.\n std::cout << type_name<std::ostream (*)(int, short)> << '\\n';\n // -> `class? (*)(int,??)`\n // With appropriate TYPE_NAME's, the output would be `std::string (*)(int,short)`.\n}\n #include <type_traits>\n#include <utility>\n\nstatic constexpr std::size_t max_str_lit_len = 256;\n\ntemplate <std::size_t I, std::size_t N> constexpr char sl_at(const char (&str)[N])\n{\n if constexpr(I < N)\n return str[I];\n else\n return '\\0';\n}\n\nconstexpr std::size_t sl_len(const char *str)\n{\n for (std::size_t i = 0; i < max_str_lit_len; i++)\n if (str[i] == '\\0')\n return i;\n return 0;\n}\n\ntemplate <char ...C> struct str_lit\n{\n static constexpr char value[] {C..., '\\0'};\n static constexpr int size = sl_len(value);\n\n template <typename F, typename ...P> struct concat_impl {using type = typename concat_impl<F>::type::template concat_impl<P...>::type;};\n template <char ...CC> struct concat_impl<str_lit<CC...>> {using type = str_lit<C..., CC...>;};\n template <typename ...P> using concat = typename concat_impl<P...>::type;\n};\n\ntemplate <typename, const char *> struct trim_str_lit_impl;\ntemplate <std::size_t ...I, const char *S> struct trim_str_lit_impl<std::index_sequence<I...>, S>\n{\n using type = str_lit<S[I]...>;\n};\ntemplate <std::size_t N, const char *S> using trim_str_lit = typename trim_str_lit_impl<std::make_index_sequence<N>, S>::type;\n\n#define STR_LIT(str) ::trim_str_lit<::sl_len(str), ::str_lit<STR_TO_VA(str)>::value>\n#define STR_TO_VA(str) STR_TO_VA_16(str,0),STR_TO_VA_16(str,16),STR_TO_VA_16(str,32),STR_TO_VA_16(str,48)\n#define STR_TO_VA_16(str,off) STR_TO_VA_4(str,0+off),STR_TO_VA_4(str,4+off),STR_TO_VA_4(str,8+off),STR_TO_VA_4(str,12+off)\n#define STR_TO_VA_4(str,off) ::sl_at<off+0>(str),::sl_at<off+1>(str),::sl_at<off+2>(str),::sl_at<off+3>(str)\n\ntemplate <char ...C> constexpr str_lit<C...> make_str_lit(str_lit<C...>) {return {};}\ntemplate <std::size_t N> constexpr auto make_str_lit(const char (&str)[N])\n{\n return trim_str_lit<sl_len((const char (&)[N])str), str>{};\n}\n\ntemplate <std::size_t A, std::size_t B> struct cexpr_pow {static constexpr std::size_t value = A * cexpr_pow<A,B-1>::value;};\ntemplate <std::size_t A> struct cexpr_pow<A,0> {static constexpr std::size_t value = 1;};\ntemplate <std::size_t N, std::size_t X, typename = std::make_index_sequence<X>> struct num_to_str_lit_impl;\ntemplate <std::size_t N, std::size_t X, std::size_t ...Seq> struct num_to_str_lit_impl<N, X, std::index_sequence<Seq...>>\n{\n static constexpr auto func()\n {\n if constexpr (N >= cexpr_pow<10,X>::value)\n return num_to_str_lit_impl<N, X+1>::func();\n else\n return str_lit<(N / cexpr_pow<10,X-1-Seq>::value % 10 + '0')...>{};\n }\n};\ntemplate <std::size_t N> using num_to_str_lit = decltype(num_to_str_lit_impl<N,1>::func());\n\n\nusing spa = str_lit<' '>;\nusing lpa = str_lit<'('>;\nusing rpa = str_lit<')'>;\nusing lbr = str_lit<'['>;\nusing rbr = str_lit<']'>;\nusing ast = str_lit<'*'>;\nusing amp = str_lit<'&'>;\nusing con = str_lit<'c','o','n','s','t'>;\nusing vol = str_lit<'v','o','l','a','t','i','l','e'>;\nusing con_vol = con::concat<spa, vol>;\nusing nsp = str_lit<':',':'>;\nusing com = str_lit<','>;\nusing unk = str_lit<'?','?'>;\n\nusing c_cla = str_lit<'c','l','a','s','s','?'>;\nusing c_uni = str_lit<'u','n','i','o','n','?'>;\nusing c_enu = str_lit<'e','n','u','m','?'>;\n\ntemplate <typename T> inline constexpr bool ptr_or_ref = std::is_pointer_v<T> || std::is_reference_v<T> || std::is_member_pointer_v<T>;\ntemplate <typename T> inline constexpr bool func_or_arr = std::is_function_v<T> || std::is_array_v<T>;\n\ntemplate <typename T> struct primitive_type_name {using value = unk;};\n\ntemplate <typename T, typename = std::enable_if_t<std::is_class_v<T>>> using enable_if_class = T;\ntemplate <typename T, typename = std::enable_if_t<std::is_union_v<T>>> using enable_if_union = T;\ntemplate <typename T, typename = std::enable_if_t<std::is_enum_v <T>>> using enable_if_enum = T;\ntemplate <typename T> struct primitive_type_name<enable_if_class<T>> {using value = c_cla;};\ntemplate <typename T> struct primitive_type_name<enable_if_union<T>> {using value = c_uni;};\ntemplate <typename T> struct primitive_type_name<enable_if_enum <T>> {using value = c_enu;};\n\ntemplate <typename T> struct type_name_impl;\n\ntemplate <typename T> using type_name_lit = std::conditional_t<std::is_same_v<typename primitive_type_name<T>::value::template concat<spa>,\n typename type_name_impl<T>::l::template concat<typename type_name_impl<T>::r>>,\n typename primitive_type_name<T>::value,\n typename type_name_impl<T>::l::template concat<typename type_name_impl<T>::r>>;\ntemplate <typename T> inline constexpr const char *type_name = type_name_lit<T>::value;\n\ntemplate <typename T, typename = std::enable_if_t<!std::is_const_v<T> && !std::is_volatile_v<T>>> using enable_if_no_cv = T;\n\ntemplate <typename T> struct type_name_impl\n{\n using l = typename primitive_type_name<T>::value::template concat<spa>;\n using r = str_lit<>;\n};\ntemplate <typename T> struct type_name_impl<const T>\n{\n using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,\n spa::concat<typename type_name_impl<T>::l>,\n typename type_name_impl<T>::l>;\n using l = std::conditional_t<ptr_or_ref<T>,\n typename new_T_l::template concat<con>,\n con::concat<new_T_l>>;\n using r = typename type_name_impl<T>::r;\n};\ntemplate <typename T> struct type_name_impl<volatile T>\n{\n using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,\n spa::concat<typename type_name_impl<T>::l>,\n typename type_name_impl<T>::l>;\n using l = std::conditional_t<ptr_or_ref<T>,\n typename new_T_l::template concat<vol>,\n vol::concat<new_T_l>>;\n using r = typename type_name_impl<T>::r;\n};\ntemplate <typename T> struct type_name_impl<const volatile T>\n{\n using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,\n spa::concat<typename type_name_impl<T>::l>,\n typename type_name_impl<T>::l>;\n using l = std::conditional_t<ptr_or_ref<T>,\n typename new_T_l::template concat<con_vol>,\n con_vol::concat<new_T_l>>;\n using r = typename type_name_impl<T>::r;\n};\ntemplate <typename T> struct type_name_impl<T *>\n{\n using l = std::conditional_t<func_or_arr<T>,\n typename type_name_impl<T>::l::template concat<lpa, ast>,\n typename type_name_impl<T>::l::template concat< ast>>;\n using r = std::conditional_t<func_or_arr<T>,\n rpa::concat<typename type_name_impl<T>::r>,\n typename type_name_impl<T>::r>;\n};\ntemplate <typename T> struct type_name_impl<T &>\n{\n using l = std::conditional_t<func_or_arr<T>,\n typename type_name_impl<T>::l::template concat<lpa, amp>,\n typename type_name_impl<T>::l::template concat< amp>>;\n using r = std::conditional_t<func_or_arr<T>,\n rpa::concat<typename type_name_impl<T>::r>,\n typename type_name_impl<T>::r>;\n};\ntemplate <typename T> struct type_name_impl<T &&>\n{\n using l = std::conditional_t<func_or_arr<T>,\n typename type_name_impl<T>::l::template concat<lpa, amp, amp>,\n typename type_name_impl<T>::l::template concat< amp, amp>>;\n using r = std::conditional_t<func_or_arr<T>,\n rpa::concat<typename type_name_impl<T>::r>,\n typename type_name_impl<T>::r>;\n};\ntemplate <typename T, typename C> struct type_name_impl<T C::*>\n{\n using l = std::conditional_t<func_or_arr<T>,\n typename type_name_impl<T>::l::template concat<lpa, type_name_lit<C>, nsp, ast>,\n typename type_name_impl<T>::l::template concat< type_name_lit<C>, nsp, ast>>;\n using r = std::conditional_t<func_or_arr<T>,\n rpa::concat<typename type_name_impl<T>::r>,\n typename type_name_impl<T>::r>;\n};\ntemplate <typename T> struct type_name_impl<enable_if_no_cv<T[]>>\n{\n using l = typename type_name_impl<T>::l;\n using r = lbr::concat<rbr, typename type_name_impl<T>::r>;\n};\ntemplate <typename T, std::size_t N> struct type_name_impl<enable_if_no_cv<T[N]>>\n{\n using l = typename type_name_impl<T>::l;\n using r = lbr::concat<num_to_str_lit<N>, rbr, typename type_name_impl<T>::r>;\n};\ntemplate <typename T> struct type_name_impl<T()>\n{\n using l = typename type_name_impl<T>::l;\n using r = lpa::concat<rpa, typename type_name_impl<T>::r>;\n};\ntemplate <typename T, typename P1, typename ...P> struct type_name_impl<T(P1, P...)>\n{\n using l = typename type_name_impl<T>::l;\n using r = lpa::concat<type_name_lit<P1>,\n com::concat<type_name_lit<P>>..., rpa, typename type_name_impl<T>::r>;\n};\n\n#define TYPE_NAME(t) template <> struct primitive_type_name<t> {using value = STR_LIT(#t);};\n" }, { "answer_id": 56453627, "author": "Milo Lu", "author_id": 2846062, "author_profile": "https://Stackoverflow.com/users/2846062", "pm_score": 3, "selected": false, "text": "std::type_info::name template<typename T>\nclass TD;\n\nint main(){\n const int theAnswer = 32;\n auto x = theAnswer;\n auto y = &theAnswer;\n TD<decltype(x)> xType;\n TD<decltype(y)> yType;\n return 0;\n}\n test4.cpp:10:21: error: aggregate ‘TD<int> xType’ has incomplete type and cannot be defined TD<decltype(x)> xType;\n\ntest4.cpp:11:21: error: aggregate ‘TD<const int *> yType’ has incomplete type and cannot be defined TD<decltype(y)> yType;\n x int y const int*" }, { "answer_id": 56766138, "author": "康桓瑋", "author_id": 11638718, "author_profile": "https://Stackoverflow.com/users/11638718", "pm_score": 7, "selected": false, "text": "#include <string_view>\n\ntemplate <typename T>\nconstexpr auto type_name() {\n std::string_view name, prefix, suffix;\n#ifdef __clang__\n name = __PRETTY_FUNCTION__;\n prefix = \"auto type_name() [T = \";\n suffix = \"]\";\n#elif defined(__GNUC__)\n name = __PRETTY_FUNCTION__;\n prefix = \"constexpr auto type_name() [with T = \";\n suffix = \"]\";\n#elif defined(_MSC_VER)\n name = __FUNCSIG__;\n prefix = \"auto __cdecl type_name<\";\n suffix = \">(void)\";\n#endif\n name.remove_prefix(prefix.size());\n name.remove_suffix(suffix.size());\n return name;\n}\n" }, { "answer_id": 58331141, "author": "Val", "author_id": 7163942, "author_profile": "https://Stackoverflow.com/users/7163942", "pm_score": 4, "selected": false, "text": "#include <string_view>\nusing namespace std;\n\nnamespace typeName {\n template <typename T>\n constexpr string_view wrapped_type_name () {\n#ifdef __clang__\n return __PRETTY_FUNCTION__;\n#elif defined(__GNUC__)\n return __PRETTY_FUNCTION__;\n#elif defined(_MSC_VER)\n return __FUNCSIG__;\n#endif\n }\n\n class probe_type;\n constexpr string_view probe_type_name (\"typeName::probe_type\");\n constexpr string_view probe_type_name_elaborated (\"class typeName::probe_type\");\n constexpr string_view probe_type_name_used (wrapped_type_name<probe_type> ().find (probe_type_name_elaborated) != -1 ? probe_type_name_elaborated : probe_type_name);\n\n constexpr size_t prefix_size () {\n return wrapped_type_name<probe_type> ().find (probe_type_name_used);\n }\n\n constexpr size_t suffix_size () {\n return wrapped_type_name<probe_type> ().length () - prefix_size () - probe_type_name_used.length ();\n }\n\n template <typename T>\n string_view type_name () {\n constexpr auto type_name = wrapped_type_name<T> ();\n\n return type_name.substr (prefix_size (), type_name.length () - prefix_size () - suffix_size ());\n }\n}\n\n#include <iostream>\n\nusing typeName::type_name;\nusing typeName::probe_type;\n\nclass test;\n\nint main () {\n cout << type_name<class test> () << endl;\n\n cout << type_name<const int*&> () << endl;\n cout << type_name<unsigned int> () << endl;\n\n const int ic = 42;\n const int* pic = &ic;\n const int*& rpic = pic;\n cout << type_name<decltype(ic)> () << endl;\n cout << type_name<decltype(pic)> () << endl;\n cout << type_name<decltype(rpic)> () << endl;\n\n cout << type_name<probe_type> () << endl;\n}\n test\nconst int *&\nunsigned int\nconst int\nconst int *\nconst int *&\ntypeName::probe_type\n test\nconst int *&\nunsigned int\nconst int\nconst int *\nconst int *&\ntypeName::probe_type\n class test\nconst int*&\nunsigned int\nconst int\nconst int*\nconst int*&\nclass typeName::probe_type\n" }, { "answer_id": 64490578, "author": "einpoklum", "author_id": 1593077, "author_profile": "https://Stackoverflow.com/users/1593077", "pm_score": 4, "selected": false, "text": "template <typename T> int foo() double int foo() [T = double] #include <string_view>\n\ntemplate <typename T> constexpr std::string_view type_name();\n\ntemplate <>\nconstexpr std::string_view type_name<void>()\n{ return \"void\"; }\n\nnamespace detail {\n\nusing type_name_prober = void;\n\ntemplate <typename T>\nconstexpr std::string_view wrapped_type_name() \n{\n#ifdef __clang__\n return __PRETTY_FUNCTION__;\n#elif defined(__GNUC__)\n return __PRETTY_FUNCTION__;\n#elif defined(_MSC_VER)\n return __FUNCSIG__;\n#else\n#error \"Unsupported compiler\"\n#endif\n}\n\nconstexpr std::size_t wrapped_type_name_prefix_length() { \n return wrapped_type_name<type_name_prober>().find(type_name<type_name_prober>()); \n}\n\nconstexpr std::size_t wrapped_type_name_suffix_length() { \n return wrapped_type_name<type_name_prober>().length() \n - wrapped_type_name_prefix_length() \n - type_name<type_name_prober>().length();\n}\n\n} // namespace detail\n\ntemplate <typename T>\nconstexpr std::string_view type_name() {\n constexpr auto wrapped_name = detail::wrapped_type_name<T>();\n constexpr auto prefix_length = detail::wrapped_type_name_prefix_length();\n constexpr auto suffix_length = detail::wrapped_type_name_suffix_length();\n constexpr auto type_name_length = wrapped_name.length() - prefix_length - suffix_length;\n return wrapped_name.substr(prefix_length, type_name_length);\n}\n" }, { "answer_id": 64717914, "author": "CourageousPotato", "author_id": 11502722, "author_profile": "https://Stackoverflow.com/users/11502722", "pm_score": 1, "selected": false, "text": "static_assert() static_assert() constexpr string_view template<typename T>\nconstexpr void assertIfTestFailed()\n{\n#ifdef __clang__\n static_assert(testFn<T>(), \"Test failed on this used type: \" __PRETTY_FUNCTION__);\n#elif defined(__GNUC__)\n static_assert(testFn<T>(), \"Test failed on this used type: \" __PRETTY_FUNCTION__);\n#elif defined(_MSC_VER)\n static_assert(testFn<T>(), \"Test failed on this used type: \" __FUNCSIG__);\n#else\n static_assert(testFn<T>(), \"Test failed on this used type (see surrounding logged error for details).\");\n#endif\n }\n}\n error C2338: Test failed on this used type: void __cdecl assertIfTestFailed<class BadType>(void)\n... continued trace of where the erroring code came from ...\n" }, { "answer_id": 67562646, "author": "Chris Uzdavinis", "author_id": 8309701, "author_profile": "https://Stackoverflow.com/users/8309701", "pm_score": 2, "selected": false, "text": "struct X {\n using T = int *((*)[10]);\n T f(T, const unsigned long long * volatile * );\n};\n\nint main() {\n\n std::cout << describe<decltype(&X::f)>() << std::endl;\n}\n pointer to member function of class 1X taking (pointer to array[10]\nof pointer to int, pointer to volatile pointer to const unsigned \nlong long), and returning pointer to array[10] of pointer to int\n // Print types as strings, including functions, member \n\n#include <type_traits>\n#include <typeinfo>\n#include <string>\n#include <utility>\n\nnamespace detail {\n\ntemplate <typename T> struct Describe;\n\ntemplate <typename T, class ClassT> \nstruct Describe<T (ClassT::*)> {\n static std::string describe();\n};\ntemplate <typename RetT, typename... ArgsT> \nstruct Describe<RetT(ArgsT...)> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...)> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...)&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const &> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile &> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) & noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile &> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const & noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile & noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile & noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) &&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const &&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile &&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) && noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile &&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const && noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile && noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile && noexcept> {\n static std::string describe();\n};\n\ntemplate <typename T>\nstd::string describe()\n{\n using namespace std::string_literals;\n auto terminal = [&](char const * desc) {\n return desc + \" \"s + typeid(T).name();\n };\n if constexpr(std::is_const_v<T>) {\n return \"const \" + describe<std::remove_const_t<T>>();\n }\n else if constexpr(std::is_volatile_v<T>) {\n return \"volatile \" + describe<std::remove_volatile_t<T>>();\n }\n else if constexpr (std::is_same_v<bool, T>) {\n return \"bool\";\n }\n else if constexpr(std::is_same_v<char, T>) {\n return \"char\";\n }\n else if constexpr(std::is_same_v<signed char, T>) {\n return \"signed char\";\n }\n else if constexpr(std::is_same_v<unsigned char, T>) {\n return \"unsigned char\";\n }\n else if constexpr(std::is_unsigned_v<T>) {\n return \"unsigned \" + describe<std::make_signed_t<T>>();\n }\n else if constexpr(std::is_void_v<T>) {\n return \"void\";\n }\n else if constexpr(std::is_integral_v<T>) {\n if constexpr(std::is_same_v<short, T>) \n return \"short\";\n else if constexpr(std::is_same_v<int, T>) \n return \"int\";\n else if constexpr(std::is_same_v<long, T>) \n return \"long\";\n else if constexpr(std::is_same_v<long long, T>) \n return \"long long\";\n }\n else if constexpr(std::is_same_v<float, T>) {\n return \"float\";\n }\n else if constexpr(std::is_same_v<double, T>) {\n return \"double\";\n }\n else if constexpr(std::is_same_v<long double, T>) {\n return \"long double\";\n }\n else if constexpr(std::is_same_v<std::nullptr_t, T>) { \n return \"nullptr_t\";\n }\n else if constexpr(std::is_class_v<T>) {\n return terminal(\"class\");\n }\n else if constexpr(std::is_union_v<T>) {\n return terminal(\"union\");\n }\n else if constexpr(std::is_enum_v<T>) {\n std::string result;\n if (!std::is_convertible_v<T, std::underlying_type_t<T>>) {\n result += \"scoped \";\n }\n return result + terminal(\"enum\");\n } \n else if constexpr(std::is_pointer_v<T>) {\n return \"pointer to \" + describe<std::remove_pointer_t<T>>();\n }\n else if constexpr(std::is_lvalue_reference_v<T>) {\n return \"lvalue-ref to \" + describe<std::remove_reference_t<T>>();\n }\n else if constexpr(std::is_rvalue_reference_v<T>) {\n return \"rvalue-ref to \" + describe<std::remove_reference_t<T>>();\n }\n else if constexpr(std::is_bounded_array_v<T>) {\n return \"array[\" + std::to_string(std::extent_v<T>) + \"] of \" +\n describe<std::remove_extent_t<T>>();\n }\n else if constexpr(std::is_unbounded_array_v<T>) {\n return \"array[] of \" + describe<std::remove_extent_t<T>>();\n }\n else if constexpr(std::is_function_v<T>) {\n return Describe<T>::describe();\n }\n else if constexpr(std::is_member_object_pointer_v<T>) {\n return Describe<T>::describe();\n }\n else if constexpr(std::is_member_function_pointer_v<T>) {\n return Describe<T>::describe();\n }\n}\n\ntemplate <typename RetT, typename... ArgsT> \nstd::string Describe<RetT(ArgsT...)>::describe() {\n std::string result = \"function taking (\";\n ((result += detail::describe<ArgsT>(\", \")), ...);\n return result + \"), returning \" + detail::describe<RetT>();\n}\n\ntemplate <typename T, class ClassT> \nstd::string Describe<T (ClassT::*)>::describe() {\n return \"pointer to member of \" + detail::describe<ClassT>() +\n \" of type \" + detail::describe<T>();\n}\n\nstruct Comma {\n char const * sep = \"\";\n std::string operator()(std::string const& str) {\n return std::exchange(sep, \", \") + str;\n }\n};\nenum Qualifiers {NONE=0, CONST=1, VOLATILE=2, NOEXCEPT=4, LVREF=8, RVREF=16};\n\ntemplate <typename RetT, typename ClassT, typename... ArgsT>\nstd::string describeMemberPointer(Qualifiers q) {\n std::string result = \"pointer to \";\n if (NONE != (q & CONST)) result += \"const \";\n if (NONE != (q & VOLATILE)) result += \"volatile \";\n if (NONE != (q & NOEXCEPT)) result += \"noexcept \";\n if (NONE != (q & LVREF)) result += \"lvalue-ref \";\n if (NONE != (q & RVREF)) result += \"rvalue-ref \";\n result += \"member function of \" + detail::describe<ClassT>() + \" taking (\";\n Comma comma;\n ((result += comma(detail::describe<ArgsT>())), ...);\n return result + \"), and returning \" + detail::describe<RetT>();\n}\n\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...)>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(NONE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(VOLATILE | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | VOLATILE | NOEXCEPT);\n}\n\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) &>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const &>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) & noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile &>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile & noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | VOLATILE | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile &>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const & noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile & noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | VOLATILE | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...)&&>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const &&>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) && noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile &&>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile && noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | VOLATILE | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile &&>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const && noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile && noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | VOLATILE | NOEXCEPT);\n}\n\n} // detail\n\n///////////////////////////////////\n// Main function\n///////////////////////////////////\ntemplate <typename T>\nstd::string describe() {\n return detail::describe<T>();\n}\n\n\n///////////////////////////////////\n// Sample code\n///////////////////////////////////\n#include <iostream>\n\n\nstruct X {\n using T = int *((*)[10]);\n T f(T, const unsigned long long * volatile * );\n};\n\nint main() {\n std::cout << describe<decltype(&X::f)>() << std::endl;\n}\n\n" }, { "answer_id": 70839988, "author": "Jonas", "author_id": 2378300, "author_profile": "https://Stackoverflow.com/users/2378300", "pm_score": 1, "selected": false, "text": "__PRETTY_FUNCTION__ #include <iostream>\n#include <string_view>\n#include <array>\n\ntemplate <typename T>\nconstexpr auto type_name() {\n auto gen = [] <class R> () constexpr -> std::string_view {\n return __PRETTY_FUNCTION__;\n };\n constexpr std::string_view search_type = \"float\";\n constexpr auto search_type_string = gen.template operator()<float>();\n constexpr auto prefix = search_type_string.find(search_type);\n constexpr auto suffix = search_type_string.size() - prefix - search_type.size();\n constexpr auto str = gen.template operator()<T>();\n constexpr int size = str.size() - prefix - suffix;\n constexpr auto static arr = [&]<std::size_t... I>(std::index_sequence<I...>) constexpr {\n return std::array<char, size>{str[prefix + I]...};\n } (std::make_index_sequence<size>{});\n\n return std::string_view(arr.data(), size);\n}\n" }, { "answer_id": 72650356, "author": "Haseeb Mir", "author_id": 6219626, "author_profile": "https://Stackoverflow.com/users/6219626", "pm_score": 1, "selected": false, "text": "template <std::size_t...Idxs>\nconstexpr auto substring_as_array(std::string_view str, std::index_sequence<Idxs...>)\n{\n return std::array{str[Idxs]..., '\\n'};\n}\n\ntemplate <typename T>\nconstexpr auto type_name_array()\n{\n#if defined(__clang__)\n constexpr auto prefix = std::string_view{\"[T = \"};\n constexpr auto suffix = std::string_view{\"]\"};\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(__GNUC__)\n constexpr auto prefix = std::string_view{\"with T = \"};\n constexpr auto suffix = std::string_view{\"]\"};\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(_MSC_VER)\n constexpr auto prefix = std::string_view{\"type_name_array<\"};\n constexpr auto suffix = std::string_view{\">(void)\"};\n constexpr auto function = std::string_view{__FUNCSIG__};\n#else\n# error Unsupported compiler\n#endif\n\n constexpr auto start = function.find(prefix) + prefix.size();\n constexpr auto end = function.rfind(suffix);\n\n static_assert(start < end);\n\n constexpr auto name = function.substr(start, (end - start));\n return substring_as_array(name, std::make_index_sequence<name.size()>{});\n}\n\ntemplate <typename T>\nstruct type_name_holder {\n static inline constexpr auto value = type_name_array<T>();\n};\n\ntemplate <typename T>\nconstexpr auto type_name() -> std::string_view\n{\n constexpr auto& value = type_name_holder<T>::value;\n return std::string_view{value.data(), value.size()};\n}\n template <typename T>\nvoid PrintDataType(T type)\n{\n auto name = typeid(type).name();\n string cmd_str = \"echo '\" + string(name) + \"' | c++filt -t\";\n system(cmd_str.c_str());\n}\n #include <iostream>\n#include <map>\n#include <string>\n#include <typeinfo>\n#include <string_view>\n#include <array> // std::array\n#include <utility> // std::index_sequence\nusing std::string;\n int main()\n{\n //Dynamic resolution.\n std::map<int, int> iMap;\n PrintDataType(iMap);\n \n //Compile type resolution.\n std::cout << type_name<std::list<int>>() << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 73058336, "author": "CPP_is_no_STANDARD", "author_id": 18032104, "author_profile": "https://Stackoverflow.com/users/18032104", "pm_score": -1, "selected": false, "text": "#include <iostream>\n\nint main()\n{\n int a = 2; // Declare type \"int\"\n std::string b = \"Hi\"; // Declare type \"string\"\n long double c = 3438; // Declare type \"long double\"\n if(typeid(a) == typeid(int))\n {\n std::cout<<\"int\\n\";\n }\n\n if(typeid(b) == typeid(std::string))\n {\n std::cout<<\"string\\n\";\n }\n \n if(typeid(c) == typeid(long double))\n {\n std::cout<<\"long double\";\n }\n return 0;\n}\n int i int if string long double typeid typeid type" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ]
81,896
<p>I have a script that works fine on my test server (using IIS6). The script processes an ajax request and sends a response with the following line:</p> <pre><code>header( 'application/javascript' ); </code></pre> <p>But on my live server, this line crashes the page and causes a 500 error.</p> <p>Do I need to allow PHP to send different MIME types in IIS7? If so, how do I do this? I can't find any way on the interface.</p>
[ { "answer_id": 81940, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 8, "selected": true, "text": "header('Content-Type: application/javascript');\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15567/" ]
81,902
<p>I need a Java way to find a running Win process from which I know to name of the executable. I want to look whether it is running right now and I need a way to kill the process if I found it.</p>
[ { "answer_id": 82035, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "tasklist taskkill Runtime.exec()" }, { "answer_id": 7473589, "author": "1-14x0r", "author_id": 334927, "author_profile": "https://Stackoverflow.com/users/334927", "pm_score": 6, "selected": false, "text": "private static final String TASKLIST = \"tasklist\";\nprivate static final String KILL = \"taskkill /F /IM \";\n\npublic static boolean isProcessRunning(String serviceName) throws Exception {\n\n Process p = Runtime.getRuntime().exec(TASKLIST);\n BufferedReader reader = new BufferedReader(new InputStreamReader(\n p.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n\n System.out.println(line);\n if (line.contains(serviceName)) {\n return true;\n }\n }\n\n return false;\n\n}\n\npublic static void killProcess(String serviceName) throws Exception {\n\n Runtime.getRuntime().exec(KILL + serviceName);\n\n }\n public static void main(String args[]) throws Exception {\n String processName = \"WINWORD.EXE\";\n\n //System.out.print(isProcessRunning(processName));\n\n if (isProcessRunning(processName)) {\n\n killProcess(processName);\n }\n}\n" }, { "answer_id": 29413515, "author": "Craig", "author_id": 529256, "author_profile": "https://Stackoverflow.com/users/529256", "pm_score": 2, "selected": false, "text": "final Process jpsProcess = \"cmd /c jps\".execute()\nfinal BufferedReader reader = new BufferedReader(new InputStreamReader(jpsProcess.getInputStream()));\ndef jarFileName = \"FileName.jar\"\ndef processId = null\nreader.eachLine {\n if (it.contains(jarFileName)) {\n def args = it.split(\" \")\n if (processId != null) {\n throw new IllegalStateException(\"Multiple processes found executing ${jarFileName} ids: ${processId} and ${args[0]}\")\n } else {\n processId = args[0]\n }\n }\n}\nif (processId != null) {\n def killCommand = \"cmd /c TASKKILL /F /PID ${processId}\"\n def killProcess = killCommand.execute()\n def stdout = new StringBuilder()\n def stderr = new StringBuilder()\n killProcess.consumeProcessOutput(stdout, stderr)\n println(killCommand)\n def errorOutput = stderr.toString()\n if (!errorOutput.empty) {\n println(errorOutput)\n }\n def stdOutput = stdout.toString()\n if (!stdOutput.empty) {\n println(stdOutput)\n }\n killProcess.waitFor()\n} else {\n System.err.println(\"Could not find process for jar ${jarFileName}\")\n}\n" }, { "answer_id": 30458368, "author": "Harvendra", "author_id": 3343726, "author_profile": "https://Stackoverflow.com/users/3343726", "pm_score": 0, "selected": false, "text": "private static final String KILL = \"taskkill /IMF \";\n private static final String KILL = \"taskkill /IM \";\n /IMF /IM" }, { "answer_id": 30843674, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 1, "selected": false, "text": "/F /IM import java.io.BufferedReader;\nimport java.io.InputStreamReader;\n\npublic class WindowsProcess\n{\n private String processName;\n\n public WindowsProcess(String processName)\n {\n this.processName = processName;\n }\n\n public void kill() throws Exception\n {\n if (isRunning())\n {\n getRuntime().exec(\"taskkill /F /IM \" + processName);\n }\n }\n\n private boolean isRunning() throws Exception\n {\n Process listTasksProcess = getRuntime().exec(\"tasklist\");\n BufferedReader tasksListReader = new BufferedReader(\n new InputStreamReader(listTasksProcess.getInputStream()));\n\n String tasksLine;\n\n while ((tasksLine = tasksListReader.readLine()) != null)\n {\n if (tasksLine.contains(processName))\n {\n return true;\n }\n }\n\n return false;\n }\n\n private Runtime getRuntime()\n {\n return Runtime.getRuntime();\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11705/" ]
81,905
<p>I have a table in my database the records start and stop times for a specific task. Here is a sample of the data:</p> <pre><code>Start Stop 9/15/2008 5:59:46 PM 9/15/2008 6:26:28 PM 9/15/2008 6:30:45 PM 9/15/2008 6:40:49 PM 9/16/2008 8:30:45 PM 9/15/2008 9:20:29 PM 9/16/2008 12:30:45 PM 12/31/9999 12:00:00 AM </code></pre> <p>I would like to write a script that totals up the elapsed minutes for these time frames, and wherever there is a 12/31/9999 date, I want it to use the current date and time, as this is still in progress.</p> <p>How would I do this using Transact-SQL?</p>
[ { "answer_id": 81981, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select Start, \n Stop, \n CASE \n WHEN Stop = '9999-12-31' THEN datediff(ss, start,getdate())\n ELSE datediff(ss, start,stop) \n END duration_in_seconds \n\nfrom mytable\n Select Sum(duration_in_seconds)\nfrom \n(\nselect Start, \n Stop, \n CASE \n WHEN Stop = '9999-12-31' THEN datediff(ss, start,getdate())\n ELSE datediff(ss, start,stop) \n END duration_in_seconds \n\nfrom mytable)x\n" }, { "answer_id": 82039, "author": "Nerdfest", "author_id": 7855, "author_profile": "https://Stackoverflow.com/users/7855", "pm_score": 2, "selected": false, "text": "Select Sum(\n DateDiff(\n Minute,\n IsNull((Select Start where Start != '9999.12.31'), GetDate()),\n IsNull((Select End where End != '9999.12.31'), GetDate())\n )\n)\nfrom *tableName*\n" }, { "answer_id": 82100, "author": "Martynnw", "author_id": 5466, "author_profile": "https://Stackoverflow.com/users/5466", "pm_score": 1, "selected": false, "text": "Select Case When (Stop <> '31 Dec 9999') Then \n DateDiff(mi, Start, Stop) \n Else \n DateDiff(mi, Start, GetDate()) \n End\nFrom ATable\n" }, { "answer_id": 83005, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 5, "selected": true, "text": "SELECT SUM( CASE WHEN Stop = '31 dec 9999' \n THEN DateDiff(mi, Start, Stop)\n ELSE DateDiff(mi, Start, GetDate())\n END ) AS TotalMinutes \nFROM task\n Stop field nullable, and make it null when the task is still running. That way, you could do this: \n\n SELECT SUM( DateDiff( mi, Start, IsNull(Stop, GetDate() ) ) AS TotalMinutes \nFROM task\n" }, { "answer_id": 86813, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 0, "selected": false, "text": "Select Sum(\n Case When End = '12/31/9999 12:00:00 AM' Then\n DateDiff(mi, Start, Getdate()) \n Else \n DateDiff(mi, Start, End) \n End) As ElapsedTime \nFrom Table\n" }, { "answer_id": 136859, "author": "GilM", "author_id": 10192, "author_profile": "https://Stackoverflow.com/users/10192", "pm_score": 2, "selected": false, "text": " SELECT SUM(\n DATEDIFF(mi, Start, ISNULL(NULLIF(Stop,'99991231'), GetDate()))\n ) AS ElapsedTime\n FROM Table\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
81,934
<p>I need a way to easily export and then import data in a MySQL table from a remote server to my home server. I don't have direct access to the server, and no utilities such as phpMyAdmin are installed. I do, however, have the ability to put PHP scripts on the server.</p> <p>How do I get at the data?</p> <p><em>I ask this question purely to record my way to do it</em></p>
[ { "answer_id": 81951, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 4, "selected": false, "text": "$result = $db_con->query('SELECT * FROM `some_table`');\n$fp = fopen('php://output', 'w');\nif ($fp && $result) {\n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename=\"export.csv\"');\n while ($row = $result->fetch_array(MYSQLI_NUM)) {\n fputcsv($fp, array_values($row));\n }\n die;\n}\n" }, { "answer_id": 82119, "author": "lewis", "author_id": 14442, "author_profile": "https://Stackoverflow.com/users/14442", "pm_score": 6, "selected": true, "text": "$file = 'backups/mytable.sql';\n$result = mysql_query(\"SELECT * INTO OUTFILE '$file' FROM `##table##`\");\n $file = 'backups/mytable.sql';\n$result = mysql_query(\"LOAD DATA INFILE '$file' INTO TABLE `##table##`\");\n $file = 'backups/mytable.sql';\nsystem(\"mysqldump --opt -h ##databaseserver## -u ##username## -p ##password## ##database | gzip > \".$file);\n" }, { "answer_id": 84981, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": -1, "selected": false, "text": "exec(\"mysqldump sourceDatabase -uUsername -p'password' > outputFilename.sql\");\n" }, { "answer_id": 30223691, "author": "T.Todua", "author_id": 2377343, "author_profile": "https://Stackoverflow.com/users/2377343", "pm_score": 3, "selected": false, "text": "EXPORT_TABLES(\"localhost\",\"user\",\"pass\",\"db_name\");\n //https://github.com/tazotodua/useful-php-scripts\nfunction EXPORT_TABLES($host,$user,$pass,$name, $tables=false, $backup_name=false ){\n $mysqli = new mysqli($host,$user,$pass,$name); $mysqli->select_db($name); $mysqli->query(\"SET NAMES 'utf8'\");\n $queryTables = $mysqli->query('SHOW TABLES'); while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; } if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); }\n foreach($target_tables as $table){\n $result = $mysqli->query('SELECT * FROM '.$table); $fields_amount=$result->field_count; $rows_num=$mysqli->affected_rows; $res = $mysqli->query('SHOW CREATE TABLE '.$table); $TableMLine=$res->fetch_row();\n $content = (!isset($content) ? '' : $content) . \"\\n\\n\".$TableMLine[1].\";\\n\\n\";\n for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0) {\n while($row = $result->fetch_row()) { //when started (and every after 100 command cycle):\n if ($st_counter%100 == 0 || $st_counter == 0 ) {$content .= \"\\nINSERT INTO \".$table.\" VALUES\";}\n $content .= \"\\n(\";\n for($j=0; $j<$fields_amount; $j++) { $row[$j] = str_replace(\"\\n\",\"\\\\n\", addslashes($row[$j]) ); if (isset($row[$j])){$content .= '\"'.$row[$j].'\"' ; }else {$content .= '\"\"';} if ($j<($fields_amount-1)){$content.= ',';} }\n $content .=\")\";\n //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler\n if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= \";\";} else {$content .= \",\";} $st_counter=$st_counter+1;\n }\n } $content .=\"\\n\\n\\n\";\n }\n $backup_name = $backup_name ? $backup_name : $name.\"___(\".date('H-i-s').\"_\".date('d-m-Y').\")__rand\".rand(1,11111111).\".sql\";\n header('Content-Type: application/octet-stream'); header(\"Content-Transfer-Encoding: Binary\"); header(\"Content-disposition: attachment; filename=\\\"\".$backup_name.\"\\\"\"); echo $content; exit;\n}\n" }, { "answer_id": 32117725, "author": "Vali Munteanu", "author_id": 4800442, "author_profile": "https://Stackoverflow.com/users/4800442", "pm_score": 2, "selected": false, "text": "PHP foreign key restrictions .sql .sql <?php\n\nbackup_tables();\n\n// backup all tables in db\nfunction backup_tables()\n{\n $day_of_backup = 'Monday'; //possible values: `Monday` `Tuesday` `Wednesday` `Thursday` `Friday` `Saturday` `Sunday`\n $backup_path = 'databases/'; //make sure it ends with \"/\"\n $db_host = 'localhost';\n $db_user = 'root';\n $db_pass = '';\n $db_name = 'movies_database_1';\n\n //set the correct date for filename\n if (date('l') == $day_of_backup) {\n $date = date(\"Y-m-d\");\n } else {\n //set $date to the date when last backup had to occur\n $datetime1 = date_create($day_of_backup);\n $date = date(\"Y-m-d\", strtotime($day_of_backup.' -7 days'));\n }\n\n if (!file_exists($backup_path.$date.'-backup'.'.sql')) {\n\n //connect to db\n $link = mysqli_connect($db_host,$db_user,$db_pass);\n mysqli_set_charset($link,'utf8');\n mysqli_select_db($link,$db_name);\n\n //get all of the tables\n $tables = array();\n $result = mysqli_query($link, 'SHOW TABLES');\n while($row = mysqli_fetch_row($result))\n {\n $tables[] = $row[0];\n }\n\n //disable foreign keys (to avoid errors)\n $return = 'SET FOREIGN_KEY_CHECKS=0;' . \"\\r\\n\";\n $return.= 'SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";' . \"\\r\\n\";\n $return.= 'SET AUTOCOMMIT=0;' . \"\\r\\n\";\n $return.= 'START TRANSACTION;' . \"\\r\\n\";\n\n //cycle through\n foreach($tables as $table)\n {\n $result = mysqli_query($link, 'SELECT * FROM '.$table);\n $num_fields = mysqli_num_fields($result);\n $num_rows = mysqli_num_rows($result);\n $i_row = 0;\n\n //$return.= 'DROP TABLE '.$table.';'; \n $row2 = mysqli_fetch_row(mysqli_query($link,'SHOW CREATE TABLE '.$table));\n $return.= \"\\n\\n\".$row2[1].\";\\n\\n\"; \n\n if ($num_rows !== 0) {\n $row3 = mysqli_fetch_fields($result);\n $return.= 'INSERT INTO '.$table.'( ';\n foreach ($row3 as $th) \n { \n $return.= '`'.$th->name.'`, '; \n }\n $return = substr($return, 0, -2);\n $return.= ' ) VALUES';\n\n for ($i = 0; $i < $num_fields; $i++) \n {\n while($row = mysqli_fetch_row($result))\n {\n $return.=\"\\n(\";\n for($j=0; $j<$num_fields; $j++) \n {\n $row[$j] = addslashes($row[$j]);\n $row[$j] = preg_replace(\"#\\n#\",\"\\\\n\",$row[$j]);\n if (isset($row[$j])) { $return.= '\"'.$row[$j].'\"' ; } else { $return.= '\"\"'; }\n if ($j<($num_fields-1)) { $return.= ','; }\n }\n if (++$i_row == $num_rows) {\n $return.= \");\"; // last row\n } else {\n $return.= \"),\"; // not last row\n } \n }\n }\n }\n $return.=\"\\n\\n\\n\";\n }\n\n // enable foreign keys\n $return .= 'SET FOREIGN_KEY_CHECKS=1;' . \"\\r\\n\";\n $return.= 'COMMIT;';\n\n //set file path\n if (!is_dir($backup_path)) {\n mkdir($backup_path, 0755, true);\n }\n\n //delete old file\n $old_date = date(\"Y-m-d\", strtotime('-4 weeks', strtotime($date)));\n $old_file = $backup_path.$old_date.'-backup'.'.sql';\n if (file_exists($old_file)) unlink($old_file);\n\n //save file\n $handle = fopen($backup_path.$date.'-backup'.'.sql','w+');\n fwrite($handle,$return);\n fclose($handle);\n }\n}\n\n?>\n" }, { "answer_id": 56603821, "author": "Teepeemm", "author_id": 2336725, "author_profile": "https://Stackoverflow.com/users/2336725", "pm_score": 1, "selected": false, "text": "SELECT * INTO OUTFILE $dbfile = tempnam(sys_get_temp_dir(),'sql');\n\n// array_chunk, but for an iterable\nfunction iter_chunk($iterable,$chunksize) {\n foreach ( $iterable as $item ) {\n $ret[] = $item;\n if ( count($ret) >= $chunksize ) {\n yield $ret;\n $ret = array();\n }\n }\n if ( count($ret) > 0 ) {\n yield $ret;\n }\n}\n\nfunction tupleFromArray($assocArr) {\n return '('.implode(',',array_map(function($val) {\n return '\"'.addslashes($val).'\"';\n },array_values($assocArr))).')';\n}\n\nfile_put_contents($dbfile,\"\\n-- Table $table --\\n/*\\n\");\n$description = $db->query(\"DESCRIBE `$table`\");\n$row = $description->fetch_assoc();\nfile_put_contents($dbfile,implode(\"\\t\",array_keys($row)).\"\\n\",FILE_APPEND);\nforeach ( $description as $row ) {\n file_put_contents($dbfile,implode(\"\\t\",array_values($row)).\"\\n\",FILE_APPEND);\n}\nfile_put_contents($dbfile,\"*/\\n\",FILE_APPEND);\nfile_put_contents($dbfile,\"DROP TABLE IF EXISTS `$table`;\\n\",FILE_APPEND);\nfile_put_contents($dbfile,array_pop($db->query(\"SHOW CREATE TABLE `$table`\")->fetch_row()),FILE_APPEND);\n$ret = $db->query(\"SELECT * FROM `$table`\");\n$chunkedData = iter_chunk($ret,1023);\nforeach ( $chunkedData as $chunk ) {\n file_put_contents($dbfile, \"\\n\\nINSERT INTO `$table` VALUES \" . implode(',',array_map('tupleFromArray',$chunk)) . \";\\n\", FILE_APPEND );\n}\nreadfile($dbfile);\nunlink($dbfile);\n CREATE SELECT * FROM information_schema.referential_constraints CREATE" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
81,972
<p>The question I want to ask is thus:</p> <p>Is casting down the inheritance tree (ie. towards a more specialiased class) from inside an abstract class excusable, or even a good thing, or is it always a poor choice with better options available?</p> <p>Now, the example of why I think it can be used for good.</p> <p>I recently implemented <a href="http://www.bittorrent.org/beps/bep_0003.html#the-connectivity-is-as-follows" rel="nofollow noreferrer">Bencoding from the BitTorrent protocol</a> in C#. A simple enough problem, how to represent the data. I chose to do it this way,</p> <p>We have an <code>abstract BItem</code> class, which provides some basic functionality, including the <code>static BItem Decode(string)</code> that is used to decode a Bencoded string into the necessary structure.</p> <p>There are also four derived classes, <code>BString</code>, <code>BInteger</code>, <code>BList</code> and <code>BDictionary</code>, representing the four different data types that be encoded. Now, here is the tricky part. <code>BList</code> and <code>BDictionary</code> have <code>this[int]</code> and <code>this[string]</code> accessors respectively to allow access to the array-like qualities of these data types.</p> <p>The potentially horrific part is coming now:</p> <pre><code>BDictionary torrent = (BDictionary) BItem.DecodeFile("my.torrent"); int filelength = (BInteger)((BDictionary)((BList)((BDictionary) torrent["info"])["files"])[0])["length"]; </code></pre> <p>Well, you get the picture... Ouch, that's hard on the eyes, not to mention the brain. So, I introduced something extra into the abstract class:</p> <pre><code>public BItem this[int index] { get { return ((BList)this)[index]; } } public BItem this[string index] { get { return ((BDictionary)this)[index]; } } </code></pre> <p>Now we could rewrite that old code as:</p> <pre><code>BDictionary torrent = (BDictionary)BItem.DecodeFile("my.torrent"); int filelength = (BInteger)torrent["info"]["files"][0]["length"]; </code></pre> <p>Wow, hey presto, MUCH more readable code. But did I just sell part of my soul for implying knowledge of subclasses into the abstract class?</p> <p>EDIT: In response to some of the answers coming in, you're completely off track for this particular question since the structure is variable, for instance my example of <code>torrent["info"]["files"][0]["length"]</code> is valid, but so is <code>torrent["announce-list"][0][0]</code>, and both would be in 90% of torrent files out there. Generics isn't the way to go, with this problem atleast :(. Have a click through to the spec I linked, it's only 4 small dot-points large.</p>
[ { "answer_id": 82012, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 1, "selected": false, "text": "BDictionary torrent = BItem.DecodeFile(\"my.torrent\");\nint filelength = torrent.FileLength;\n" }, { "answer_id": 82013, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 4, "selected": true, "text": " (BInteger)torrent[\"info\"][0][\"files\"][\"length\"];\n" }, { "answer_id": 82023, "author": "Stormenet", "author_id": 2090, "author_profile": "https://Stackoverflow.com/users/2090", "pm_score": 0, "selected": false, "text": "\nBDictionary torrent = BItem.DecodeFile(\"my.torrent\");\nint filelength = (int)torrent.Fetch(\"info.files.0.length\");\n" }, { "answer_id": 82037, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "BString GetString(BInteger);\nSetString(BInteger, BString);\n" }, { "answer_id": 82044, "author": "neaorin", "author_id": 15591, "author_profile": "https://Stackoverflow.com/users/15591", "pm_score": 1, "selected": false, "text": "abstract class BCollection : BItem {\n\n public BItem this[int index] {get;}\n public BItem this[string index] {get;}\n}\n" }, { "answer_id": 82193, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "class DecodedTorrent : BDictionary<BDictionary<BList<BDictionary<BInteger>>>>\n{\n}\n DecodedTorrent torrent = BItem.DecodeFile(\"mytorrent\");\nint x = torrent[\"info\"][\"files\"][0][\"length\"];\n" }, { "answer_id": 82399, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "BDictionary torrent = BItem.DecodeFile(\"my.torrent\");int filelength = (BInteger)((BDictionary)((BList)((BDictionary) torrent[\"info\"])[\"files\"])[0])[\"length\"];\n public BItem this[int index]{&nbsp; &nbsp; get { return ((BList)this)[index]; }}public BItem this[string index]{&nbsp; &nbsp; get { return ((BDictionary)this)[index]; }}\n BDictionary torrent = BItem.DecodeFile(\"my.torrent\");int filelength = (BInteger)((BList)((BDictionary)torrent[\"info\"][\"files\"])[0])[\"length\"];\n" }, { "answer_id": 86393, "author": "Thomas Eyde", "author_id": 3282, "author_profile": "https://Stackoverflow.com/users/3282", "pm_score": 1, "selected": false, "text": "BFile torrent = BFile.DecodeFile(\"my.torrent\");\nint filelength = torrent.Length;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
81,991
<p>Every time a user posts something containing <code>&lt;</code> or <code>&gt;</code> in a page in my web application, I get this exception thrown.</p> <p>I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this.</p> <p>Trapping the exception and showing</p> <blockquote> <p>An error has occurred please go back and re-type your entire form again, but this time please do not use &lt;</p> </blockquote> <p>doesn't seem professional enough to me.</p> <p>Disabling post validation (<code>validateRequest="false"</code>) will definitely avoid this error, but it will leave the page vulnerable to a number of attacks.</p> <p>Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded. So the <code>.Text</code> property of my text-box will be <code>something &amp; lt; html &amp; gt;</code></p> <p>Is there a way I can do this from a handler?</p>
[ { "answer_id": 82170, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 11, "selected": true, "text": "< < javascript: ValidateRequest=\"false\" <%@ Page ... %> .aspx <httpRuntime requestValidationMode=\"2.0\" />" }, { "answer_id": 82203, "author": "woany", "author_id": 15623, "author_profile": "https://Stackoverflow.com/users/15623", "pm_score": 3, "selected": false, "text": "> <" }, { "answer_id": 83949, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "< &lt; > &gt; & &amp; myTextBox.Text = Server.HtmlEncode(myStringFromDatabase); // Pseudo code\n <script> window.location = \"http://www.google.com\"; </script>" }, { "answer_id": 436247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "function AlphanumericValidation(evt)\n{\n var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :\n ((evt.which) ? evt.which : 0));\n\n // User type Enter key\n if (charCode == 13)\n {\n // Do something, set controls focus or do anything\n return false;\n }\n\n // User can not type non alphanumeric characters\n if ( (charCode < 48) ||\n (charCode > 122) ||\n ((charCode > 57) && (charCode < 65)) ||\n ((charCode > 90) && (charCode < 97))\n )\n {\n // Show a message or do something\n return false;\n }\n}\n Me.TextBox1.Attributes.Add(\"OnKeyPress\", \"return AlphanumericValidation(event);\")\n" }, { "answer_id": 1540976, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 9, "selected": false, "text": "[HttpPost, ValidateInput(false)]\npublic ActionResult Edit(FormCollection collection)\n{\n // ...\n}\n <AcceptVerbs(HttpVerbs.Post), ValidateInput(False)> _\nFunction Edit(ByVal collection As FormCollection) As ActionResult\n ...\nEnd Function\n" }, { "answer_id": 1563330, "author": "BenMaddox", "author_id": 38698, "author_profile": "https://Stackoverflow.com/users/38698", "pm_score": 6, "selected": false, "text": " void Application_Error(object sender, EventArgs e)\n {\n Exception ex = Server.GetLastError();\n\n if (ex is HttpRequestValidationException)\n {\n Response.Clear();\n Response.StatusCode = 200;\n Response.Write(@\"[html]\");\n Response.End();\n }\n }\n" }, { "answer_id": 3368769, "author": "JordanC", "author_id": 172330, "author_profile": "https://Stackoverflow.com/users/172330", "pm_score": 8, "selected": false, "text": "<system.web> <httpRuntime requestValidationMode=\"2.0\" />\n aspx .aspx requestValidationMode=\"2.0\"\n validateRequest=\"false\"\n" }, { "answer_id": 4113591, "author": "gligoran", "author_id": 227613, "author_profile": "https://Stackoverflow.com/users/227613", "pm_score": 6, "selected": false, "text": "[HttpPost, ValidateInput(true, Exclude = \"YourFieldName\")]\npublic virtual ActionResult Edit(int id, FormCollection collection)\n{\n ...\n}\n" }, { "answer_id": 4313998, "author": "ranthonissen", "author_id": 403259, "author_profile": "https://Stackoverflow.com/users/403259", "pm_score": 6, "selected": false, "text": "<httpRuntime requestValidationMode=\"2.0\"/>\n\n<configuration>\n <system.web>\n <pages validateRequest=\"false\" />\n </system.web>\n</configuration>\n [Post, ValidateInput(false)]\npublic ActionResult Edit(string message) {\n ...\n}\n" }, { "answer_id": 7306222, "author": "Anthony Johnston", "author_id": 122232, "author_profile": "https://Stackoverflow.com/users/122232", "pm_score": 9, "selected": false, "text": "AllowHtml [AllowHtml]\npublic string Description { get; set; }\n" }, { "answer_id": 9035316, "author": "Piercy", "author_id": 455135, "author_profile": "https://Stackoverflow.com/users/455135", "pm_score": 5, "selected": false, "text": "<%@ Page Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"Example.aspx.vb\" Inherits=\"Example.Example\" **ValidateRequest=\"false\"** %>\n" }, { "answer_id": 9711182, "author": "Mahdi jokar", "author_id": 1125430, "author_profile": "https://Stackoverflow.com/users/1125430", "pm_score": 5, "selected": false, "text": "<configuration>\n <system.web>\n <httpRuntime requestValidationMode=\"2.0\" />\n </system.web>\n <pages validateRequest=\"false\">\n </pages>\n</configuration>\n" }, { "answer_id": 9739209, "author": "magritte", "author_id": 931545, "author_profile": "https://Stackoverflow.com/users/931545", "pm_score": 3, "selected": false, "text": " protected override void Execute(RequestContext requestContext)\n {\n // Disable requestion validation (security) across the whole site\n ValidateRequest = false;\n base.Execute(requestContext);\n }\n" }, { "answer_id": 11530248, "author": "Jaider", "author_id": 480700, "author_profile": "https://Stackoverflow.com/users/480700", "pm_score": 4, "selected": false, "text": "protected override void OnError(EventArgs e)\n{\n base.OnError(e);\n var ex = Server.GetLastError().GetBaseException();\n if (ex is System.Web.HttpRequestValidationException)\n {\n Response.Clear();\n Response.Write(\"Invalid characters.\"); // Response.Write(HttpUtility.HtmlEncode(ex.Message));\n Response.StatusCode = 200;\n Response.End();\n }\n}\n" }, { "answer_id": 11798616, "author": "Ryan", "author_id": 1574529, "author_profile": "https://Stackoverflow.com/users/1574529", "pm_score": 3, "selected": false, "text": "<asp:Button runat=\"server\" ID=\"saveButton\" Text=\"Save\" CssClass=\"saveButton\" OnClientClick=\"return checkFields()\" />\n\nfunction checkFields() {\n var tbs = new Array();\n tbs = document.getElementsByTagName(\"input\");\n var isValid = true;\n for (i=0; i<tbs.length; i++) {\n if (tbs(i).type == 'text') {\n if (tbs(i).value.indexOf('<') != -1 || tbs(i).value.indexOf('>') != -1) {\n alert('<> symbols not allowed.');\n isValid = false;\n }\n }\n }\n return isValid;\n}\n" }, { "answer_id": 11955698, "author": "Leniel Maccaferri", "author_id": 114029, "author_profile": "https://Stackoverflow.com/users/114029", "pm_score": 3, "selected": false, "text": "á $.ajax data: { roleName: '@Model.RoleName', users: users }\n data: { roleName: '@Html.Raw(@Model.RoleName)', users: users }\n @Html.Raw roleName=\"Cadastro b&#225;s\" &#225; roleName roleName=\"Cadastro Básico\"" }, { "answer_id": 13589607, "author": "Carter Medlin", "author_id": 324479, "author_profile": "https://Stackoverflow.com/users/324479", "pm_score": 7, "selected": false, "text": "<location> ValidateRequest=\"false\" <configuration>\n...\n <location path=\"MyFolder/.aspx\">\n <system.web>\n <pages validateRequest=\"false\" />\n <httpRuntime requestValidationMode=\"2.0\" />\n </system.web>\n </location>\n...\n</configuration>\n" }, { "answer_id": 16224548, "author": "flakomalo", "author_id": 2321524, "author_profile": "https://Stackoverflow.com/users/2321524", "pm_score": 6, "selected": false, "text": "var varname = Request.Unvalidated[\"parameter_name\"];\n" }, { "answer_id": 16867157, "author": "Ady Levy", "author_id": 2442115, "author_profile": "https://Stackoverflow.com/users/2442115", "pm_score": 3, "selected": false, "text": "var nvc = Request.Unvalidated().Form;\n nvc[\"yourKey\"]" }, { "answer_id": 20450300, "author": "Sel", "author_id": 2706338, "author_profile": "https://Stackoverflow.com/users/2706338", "pm_score": 4, "selected": false, "text": "protected void Application_Start()\n{\n ...\n RequestValidator.Current = new MyRequestValidator();\n}\n\npublic class MyRequestValidator: RequestValidator\n{\n protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)\n {\n bool result = base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);\n\n if (!result)\n {\n // Write your validation here\n if (requestValidationSource == RequestValidationSource.Form ||\n requestValidationSource == RequestValidationSource.QueryString)\n\n return true; // Suppress error message\n }\n return result;\n }\n}\n" }, { "answer_id": 23415656, "author": "Walden Leverich", "author_id": 2673770, "author_profile": "https://Stackoverflow.com/users/2673770", "pm_score": 2, "selected": false, "text": "public class SkippableRequestValidator : RequestValidator\n{\n protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)\n {\n if (collectionKey != null && collectionKey.EndsWith(\"_NoValidation\"))\n {\n validationFailureIndex = 0;\n return true;\n }\n\n return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);\n }\n}\n" }, { "answer_id": 25872850, "author": "Jason Shuler", "author_id": 1026711, "author_profile": "https://Stackoverflow.com/users/1026711", "pm_score": 4, "selected": false, "text": "<textarea id=\"userbox\" onchange=\"boo();\"></textarea>\n string val = Server.UrlDecode(HiddenField1.Value);\n $(document).ready(function () {\n\n $(\"#txtHTML\").change(function () {\n var currentText = $(\"#txtHTML\").text();\n currentText = escape(currentText); // Escapes the HTML including quotations, etc\n $(\"#hidHTML\").val(currentText); // Set the hidden field\n });\n\n // Intercept the postback\n $(\"#btnMyPostbackButton\").click(function () {\n $(\"#txtHTML\").val(\"\"); // Clear the textarea before POSTing\n // If you don't clear it, it will give you\n // the error due to the HTML in the textarea.\n return true; // Post back\n });\n\n\n});\n <asp:HiddenField ID=\"hidHTML\" runat=\"server\" />\n<textarea id=\"txtHTML\"></textarea>\n<asp:Button ID=\"btnMyPostbackButton\" runat=\"server\" Text=\"Post Form\" />\n" }, { "answer_id": 29366891, "author": "Devendra Patel", "author_id": 3027600, "author_profile": "https://Stackoverflow.com/users/3027600", "pm_score": -1, "selected": false, "text": "Server.Encode Server.HtmlDecode" }, { "answer_id": 30838818, "author": "vakeel", "author_id": 4222088, "author_profile": "https://Stackoverflow.com/users/4222088", "pm_score": 4, "selected": false, "text": "@Page <%@ Page Language=\"C#\" AutoEventWireup=\"true\" ValidateRequest = \"false\" %>\n <pages validateRequest =\"false\" />\n <httpRuntime requestValidationMode = \"2.0\" />\n" }, { "answer_id": 34196133, "author": "Durgesh Pandey", "author_id": 5030579, "author_profile": "https://Stackoverflow.com/users/5030579", "pm_score": 4, "selected": false, "text": "<configuration>\n <system.web>\n <pages validateRequest=\"false\" />\n </system.web>\n</configuration>\n <system.web>\n <compilation debug=\"true\" targetFramework=\"4.5\" />\n <httpRuntime targetFramework=\"4.5\" requestValidationMode=\"2.0\"/>\n</system.web>\n <%@ Page EnableEventValidation=\"false\" %>\n EnableEventValidation=\"false\"" }, { "answer_id": 35621783, "author": "Sel", "author_id": 2706338, "author_profile": "https://Stackoverflow.com/users/2706338", "pm_score": 2, "selected": false, "text": " public class AppModelBinder : DefaultModelBinder\n {\n protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)\n {\n try\n {\n return base.CreateModel(controllerContext, bindingContext, modelType);\n }\n catch (HttpRequestValidationException e)\n {\n HandleHttpRequestValidationException(bindingContext, e);\n return null; // Encode here\n }\n }\n protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,\n PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)\n {\n try\n {\n return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);\n }\n catch (HttpRequestValidationException e)\n {\n HandleHttpRequestValidationException(bindingContext, e);\n return null; // Encode here\n }\n }\n\n protected void HandleHttpRequestValidationException(ModelBindingContext bindingContext, HttpRequestValidationException ex)\n {\n var valueProviderCollection = bindingContext.ValueProvider as ValueProviderCollection;\n if (valueProviderCollection != null)\n {\n ValueProviderResult valueProviderResult = valueProviderCollection.GetValue(bindingContext.ModelName, skipValidation: true);\n bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\n }\n\n string errorMessage = string.Format(CultureInfo.CurrentCulture, \"{0} contains invalid symbols: <, &\",\n bindingContext.ModelMetadata.DisplayName);\n\n bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);\n }\n }\n ModelBinders.Binders.DefaultBinder = new AppModelBinder();\n private void Application_Error(object sender, EventArgs e)\n{\n Exception exception = Server.GetLastError();\n HttpContext httpContext = HttpContext.Current;\n\n HttpException httpException = exception as HttpException;\n if (httpException != null)\n {\n RouteData routeData = new RouteData();\n routeData.Values.Add(\"controller\", \"Error\");\n var httpCode = httpException.GetHttpCode();\n switch (httpCode)\n {\n case (int)HttpStatusCode.BadRequest /* 400 */:\n if (httpException.Message.Contains(\"Request.Path\"))\n {\n httpContext.Response.Clear();\n RequestContext requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);\n requestContext.RouteData.Values[\"action\"] =\"InvalidUrl\";\n requestContext.RouteData.Values[\"controller\"] =\"Error\";\n IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();\n IController controller = factory.CreateController(requestContext, \"Error\");\n controller.Execute(requestContext);\n httpContext.Server.ClearError();\n Response.StatusCode = (int)HttpStatusCode.BadRequest /* 400 */;\n }\n break;\n }\n }\n}\n public class ErrorController : Controller\n {\n public ActionResult InvalidUrl()\n {\n return View();\n }\n} \n" }, { "answer_id": 36721339, "author": "Voigt", "author_id": 6166500, "author_profile": "https://Stackoverflow.com/users/6166500", "pm_score": 1, "selected": false, "text": "Server.HtmlEncode(\"yourtext\");" }, { "answer_id": 41679015, "author": "Peter", "author_id": 58553, "author_profile": "https://Stackoverflow.com/users/58553", "pm_score": 1, "selected": false, "text": "Public Class UnvalidatedTextBox\n Inherits TextBox\n Protected Overrides Function LoadPostData(postDataKey As String, postCollection As NameValueCollection) As Boolean\n Return MyBase.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form)\n End Function\nEnd Class\n public class UnvalidatedTextBox : TextBox\n{\n protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)\n {\n return base.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form);\n }\n}\n <prefix:UnvalidatedTextBox id=\"test\" runat=\"server\" /> <asp:TextBox" }, { "answer_id": 48480067, "author": "dpant", "author_id": 313935, "author_profile": "https://Stackoverflow.com/users/313935", "pm_score": 1, "selected": false, "text": "ItemTemplate ValidateRequest <%@ Page Language=\"C#\" ValidateRequest=\"false\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"WebApplication17._Default\" %> <html> <body>\n <form runat=\"server\">\n <asp:FormView ID=\"FormView1\" runat=\"server\" ItemType=\"WebApplication17.S\" SelectMethod=\"FormView1_GetItem\">\n <ItemTemplate>\n <asp:TextBox ID=\"TextBox1\" runat=\"server\"></asp:TextBox>\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" OnClick=\"Button1_Click\" />\n <asp:Label ID=\"Label1\" runat=\"server\" Text=\"<%#: Item.Text %>\"></asp:Label>\n <asp:TextBox ID=\"TextBox2\" runat=\"server\" Text=\"<%#: Item.Text %>\"></asp:TextBox>\n </ItemTemplate>\n </asp:FormView>\n </form> \n public partial class _Default : Page\n{\n S s = new S();\n\n protected void Button1_Click(object sender, EventArgs e)\n {\n s.Text = ((TextBox)FormView1.FindControl(\"TextBox1\")).Text;\n FormView1.DataBind();\n }\n\n public S FormView1_GetItem(int? id)\n {\n return s;\n }\n}\n\npublic class S\n{\n public string Text { get; set; }\n}\n &#39; Label1.Text &#39; TextBox2.Text &amp;#39; <script>alert('attack!');</script> Label1.Text <script>alert('attack!');</script> TextBox2.Text &lt;script&gt;alert(&#39;attack!&#39;);&lt;/script&gt;" }, { "answer_id": 49307591, "author": "KiranC", "author_id": 8167813, "author_profile": "https://Stackoverflow.com/users/8167813", "pm_score": 0, "selected": false, "text": "<system.web>\n <httpRuntime requestValidationMode=\"2.0\" />\n" }, { "answer_id": 49575929, "author": "Chris Catignani", "author_id": 3072350, "author_profile": "https://Stackoverflow.com/users/3072350", "pm_score": 2, "selected": false, "text": " protected void Page_Load(object sender, EventArgs e)\n {\n txtMachKey.ValidateRequestMode = ValidateRequestMode.Disabled;\n }\n" }, { "answer_id": 49639591, "author": "Magnus", "author_id": 1765710, "author_profile": "https://Stackoverflow.com/users/1765710", "pm_score": 2, "selected": false, "text": "<x <form id=\"form1\" runat=\"server\" onsubmit=\"return xssCheckValidates();\">\n function xssCheckValidates() {\n var valid = true;\n var inp = document.querySelectorAll(\n \"input:not(:disabled):not([readonly]):not([type=hidden])\" +\n \",textarea:not(:disabled):not([readonly])\");\n for (var i = 0; i < inp.length; i++) {\n if (!inp[i].readOnly) {\n if (inp[i].value.indexOf('<') > -1) {\n valid = false;\n break;\n }\n if (inp[i].value.indexOf('&#') > -1) {\n valid = false;\n break;\n }\n }\n }\n if (valid) {\n return true;\n } else {\n alert('In one or more of the text fields, you have typed\\r\\nthe character \"<\" or the character sequence \"&#\".\\r\\n\\r\\nThis is unfortunately not allowed since\\r\\nit can be used in hacking attempts.\\r\\n\\r\\nPlease edit the field and try again.');\n return false;\n }\n } <form onsubmit=\"return xssCheckValidates();\" >\n Try to type < or &# <br/>\n <input type=\"text\" /><br/>\n <textarea></textarea>\n <input type=\"submit\" value=\"Send\" />\n</form>" }, { "answer_id": 51490934, "author": "Wahid Masud", "author_id": 5538471, "author_profile": "https://Stackoverflow.com/users/5538471", "pm_score": 3, "selected": false, "text": "encodeURIComponent($(\"#MsgBody\").val()); \n string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form[\"MsgBody\"]) ?\nSystem.Web.HttpUtility.UrlDecode(HttpContext.Current.Request.Form[\"MsgBody\"]) : \nnull; \n string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form[\"MsgBody\"]) ?\nSystem.Uri.UnescapeDataString(HttpContext.Current.Request.Form[\"MsgBody\"]) : \nnull; \n UrlDecode UnescapeDataString" }, { "answer_id": 53590303, "author": "maozx", "author_id": 1516208, "author_profile": "https://Stackoverflow.com/users/1516208", "pm_score": 3, "selected": false, "text": "validateRequest=\"false\" <asp:TextBox runat=\"server\" ID=\"mainTextBox\"\n ValidateRequestMode=\"Disabled\"\n ></asp:TextBox>\n" }, { "answer_id": 61640372, "author": "Sanjeev Singh", "author_id": 3288863, "author_profile": "https://Stackoverflow.com/users/3288863", "pm_score": 0, "selected": false, "text": "requestValidationMode = \"2.0 editorID.value = editorID.value.replace(/>/g, \"&gt;\");\neditorID.value = editorID.value.replace(/</g, \"&lt;\");\n" }, { "answer_id": 67008025, "author": "syntap", "author_id": 2108172, "author_profile": "https://Stackoverflow.com/users/2108172", "pm_score": 0, "selected": false, "text": "<asp:TextBox ID=\"CommentsTextBox\" runat=\"server\" TextMode=\"MultiLine\"></asp:TextBox>\n<ajaxToolkit:FilteredTextBoxExtender ID=\"ftbe\" runat=\"server\" TargetControlID=\"CommentsTextBox\" filterMode=\"InvalidChars\" InvalidChars=\"<>\" />\n" }, { "answer_id": 70332576, "author": "Colin", "author_id": 150342, "author_profile": "https://Stackoverflow.com/users/150342", "pm_score": 0, "selected": false, "text": "//Register action filter via Autofac rather than GlobalFilters to allow dependency injection\nbuilder.RegisterFilterProvider();\nbuilder.RegisterType<OfflineActionFilter>()\n .AsActionFilterFor<Controller>()\n .InstancePerLifetimeScope();\n" }, { "answer_id": 70866955, "author": "jcs", "author_id": 2526059, "author_profile": "https://Stackoverflow.com/users/2526059", "pm_score": 0, "selected": false, "text": "<httpRuntime requestValidationMode=\"2.0\"> <sessionState mode=\"InProc\" cookieless=\"UseUri\"/> <system.web>" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/81991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
82,003
<p>I have a remote DB2 database that I'm accessing through ODBC. When I have a query like</p> <pre><code>SELECT t.foo, t.bar, t.problemcolumn FROM problemtable t WHERE t.bar &lt; 60; </code></pre> <p>it works like a charm, so the table and columns obviously exist.</p> <p>But if I specify the problem column in the WHERE clause</p> <pre><code>SELECT t.foo, t.bar, t.problemcolumn FROM problemtable t WHERE t.problemcolumn = 'x' AND t.bar &lt; 60; </code></pre> <p>it gives me an error </p> <pre><code>Table "problemtable" does not exist. </code></pre> <p>What could possibly be the reason for this? I've double checked the spellings and I can trigger the problem just by including the problemcolumn in the where-clause.</p>
[ { "answer_id": 82283, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 0, "selected": false, "text": "SELECT t.foo, t.bar, t.problemcolumn\nFROM problemtable t\nWHERE t.problemcolumn = 'x'\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2087/" ]
82,008
<p>I have xml where some of the element values are unicode characters. Is it possible to represent this in an ANSI encoding?</p> <p>E.g.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;xml&gt; &lt;value&gt;受&lt;/value&gt; &lt;/xml&gt; </code></pre> <p>to</p> <pre><code>&lt;?xml version="1.0" encoding="Windows-1252"?&gt; &lt;xml&gt; &lt;value&gt;&amp;#27544;&lt;/value&gt; &lt;/xml&gt; </code></pre> <p>I deserialize the XML and then attempt to serialize it using XmlTextWriter specifying the Default encoding (Default is Windows-1252). All the unicode characters end up as question marks. I'm using VS 2008, C# 3.5</p>
[ { "answer_id": 82021, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "; 27544 <?xml version=\"1.0\" encoding=\"Windows-1252\"?>\n<xml>\n<value>&#27544;</value>\n</xml>\n" }, { "answer_id": 82413, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 4, "selected": true, "text": " string xml = \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?><xml><value>受</value></xml>\";\n\n XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.Default };\n MemoryStream ms = new MemoryStream();\n using (XmlWriter writer = XmlTextWriter.Create(ms, settings))\n XElement.Parse(xml).WriteTo(writer);\n\n string value = Encoding.Default.GetString(ms.ToArray());\n <?xml version=\"1.0\" encoding=\"Windows-1252\"?><xml><value>&#x53D7;</value></xml>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9539/" ]
82,047
<p>I have a requirement to validate an incoming file against an XSD. Both will be on the server file system.<br /></p> <p>I've looked at <code>dbms_xmlschema</code>, but have had issues getting it to work.</p> <p>Could it be easier to do it with some Java?<br />What's the simplest class I could put in the database?</p> <p>Here's a simple example:</p> <pre><code>DECLARE v_schema_url VARCHAR2(200) := 'http://www.example.com/schema.xsd'; v_blob bLOB; v_clob CLOB; v_xml XMLTYPE; BEGIN begin dbms_xmlschema.deleteschema(v_schema_url); exception when others then null; end; dbms_xmlschema.registerSchema(schemaURL =&gt; v_schema_url, schemaDoc =&gt; ' &lt;xs:schema targetNamespace="http://www.example.com" xmlns:ns="http://www.example.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" version="3.0"&gt; &lt;xs:element name="something" type="xs:string"/&gt; &lt;/xs:schema&gt;', local =&gt; TRUE); v_xml := XMLTYPE.createxml('&lt;something xmlns="http://www.xx.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/schema.xsd"&gt; data &lt;/something&gt;'); IF v_xml.isschemavalid(v_schema_url) = 1 THEN dbms_output.put_line('valid'); ELSE dbms_output.put_line('not valid'); END IF; END; </code></pre> <p>This generates the following error:</p> <pre><code>ORA-01031: insufficient privileges ORA-06512: at "XDB.DBMS_XDBZ0", line 275 ORA-06512: at "XDB.DBMS_XDBZ", line 7 ORA-06512: at line 1 ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 3 ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 14 ORA-06512: at line 12 </code></pre>
[ { "answer_id": 5274406, "author": "Tomasz Żuk", "author_id": 655526, "author_profile": "https://Stackoverflow.com/users/655526", "pm_score": 2, "selected": false, "text": "ALTER SESSION" }, { "answer_id": 6367816, "author": "user272735", "author_id": 272735, "author_profile": "https://Stackoverflow.com/users/272735", "pm_score": 3, "selected": false, "text": "grant alter session to <USER>;\ngrant create type to <USER>; /* required when gentypes => true */\ngrant create table to <USER>; /* required when gentables => true */\n gentables gentypes insufficient privileges dbms_xmlschema.registerschema(schemaurl => name,\n schemadoc => xmltype(schema),\n local => true\n --gentypes => false,\n --gentables => false\n );\n\nORA-01031: insufficient privileges\nORA-06512: at \"XDB.DBMS_XMLSCHEMA_INT\", line 55\nORA-06512: at \"XDB.DBMS_XMLSCHEMA\", line 159\nORA-06512: at \"JANI.XML_VALIDATOR\", line 38\nORA-06512: at line 7\n dbms_xmlschema.registerschema(schemaurl => name,\n schemadoc => xmltype(schema),\n local => true,\n gentypes => false\n --gentables => false\n );\n\nORA-31084: error while creating table \"JANI\".\"example873_TAB\" for element \"example\"\nORA-01031: insufficient privileges\nORA-06512: at \"XDB.DBMS_XMLSCHEMA_INT\", line 55\nORA-06512: at \"XDB.DBMS_XMLSCHEMA\", line 159\nORA-06512: at \"JANI.XML_VALIDATOR\", line 38\nORA-06512: at line 7\n dbms_xmlschema.registerschema(schemaurl => name,\n schemadoc => xmltype(schema),\n local => true,\n --gentypes => false\n gentables => false\n );\n\nORA-01031: insufficient privileges\nORA-06512: at \"XDB.DBMS_XMLSCHEMA_INT\", line 55\nORA-06512: at \"XDB.DBMS_XMLSCHEMA\", line 159\nORA-06512: at \"JANI.XML_VALIDATOR\", line 38\nORA-06512: at line 7\n dbms_xmlschema.registerschema(schemaurl => name,\n schemadoc => xmltype(schema),\n local => true,\n gentypes => false,\n gentables => false\n );\n\nPL/SQL procedure successfully completed.\n" }, { "answer_id": 12053644, "author": "Pierre-Gilles Levallois", "author_id": 2162529, "author_profile": "https://Stackoverflow.com/users/2162529", "pm_score": 2, "selected": false, "text": "/* Formatted on 21/08/2012 12:52:47 (QP5 v5.115.810.9015) */\nDECLARE\n -- Local variables here\n res BOOLEAN;\n tempXML XMLTYPE;\n xmlDoc XMLTYPE;\n xmlSchema XMLTYPE;\n schemaURL VARCHAR2 (256) := 'testcase.xsd';\nBEGIN\n dbms_xmlSchema.deleteSchema (schemaURL, 4);\n -- Test statements here\n xmlSchema :=\n xmlType('<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xdb=\"http://xmlns.oracle.com/xdb\"\nelementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">\n<xs:element name=\"root\" xdb:defaultTable=\"ROOT_TABLE\">\n<xs:complexType>\n<xs:sequence>\n<xs:element name=\"child1\"/>\n<xs:element name=\"child2\"/>\n</xs:sequence>\n</xs:complexType>\n</xs:element>\n</xs:schema>\n');\n -- http://stackoverflow.com/questions/82047/validating-xml-files-against-schema-in-oracle-pl-sql\n dbms_xmlschema.registerschema(schemaurl => schemaURL,\n schemadoc => xmlSchema,\n local => true,\n gentypes => false,\n gentables => false\n );\n xmlDoc :=\n xmltype('<root xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"'\n || schemaURL\n || '\"><child1>foo</child1><child2>bar</child2></root>');\n xmlDoc.schemaValidate ();\n -- if we are here, xml is valid\n DBMS_OUTPUT.put_line ('OK');\nexception\n when others then\n DBMS_OUTPUT.put_line (SQLErrm);\nEND;\n" }, { "answer_id": 48176686, "author": "Robin", "author_id": 6010174, "author_profile": "https://Stackoverflow.com/users/6010174", "pm_score": 0, "selected": false, "text": "grant create table to <user>;\ngrant create type to <user>;\ngrant create trigger to <user>;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1895/" ]
82,058
<p>Given the following JSON Date representation:</p> <pre><code>"\/Date(1221644506800-0700)\/" </code></pre> <p>How do you deserialize this into it's JavaScript Date-type form?</p> <p>I've tried using MS AJAX JavaScrioptSerializer as shown below:</p> <pre><code>Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/") </code></pre> <p>However, all I get back is the literal string date.</p>
[ { "answer_id": 82244, "author": "Daniel", "author_id": 6852, "author_profile": "https://Stackoverflow.com/users/6852", "pm_score": 1, "selected": false, "text": "new Date(1221644506800)\n" }, { "answer_id": 82377, "author": "Sjoerd Visscher", "author_id": 5852, "author_profile": "https://Stackoverflow.com/users/5852", "pm_score": 4, "selected": false, "text": "var s = \"\\/Date(1221644506800-0700)\\/\";\nvar m = s.match(/^\\/Date\\((\\d+)([-+]\\d\\d)(\\d\\d)\\)\\/$/);\nvar date = null;\nif (m)\n date = new Date(1*m[1] + 3600000*m[2] + 60000*m[3]);\n" }, { "answer_id": 428857, "author": "Kyle Jones", "author_id": 53424, "author_profile": "https://Stackoverflow.com/users/53424", "pm_score": 3, "selected": false, "text": "Sys.Serialization.JavaScriptSerializer.deserialize(\"\\\"\\\\/Date(1221644506800)\\\\/\\\"\")\n Script.Serialization.JavaScriptSerializer jss = new Script.Serialization.JavaScriptSerializer();\nstring script = string.Format(\"alert(Sys.Serialization.JavaScriptSerializer.deserialize({0}));\", jss.Serialize(jss.Serialize(DateTime.Now)));\nPage.ClientScript.RegisterStartupScript(this.GetType(), \"ClientScript\", script, true);\n" }, { "answer_id": 959092, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 6, "selected": true, "text": " new Date(parseInt(value.replace(\"/Date(\", \"\").replace(\")/\",\"\"), 10))\n" }, { "answer_id": 1646987, "author": "Alex Nolasco", "author_id": 65694, "author_profile": "https://Stackoverflow.com/users/65694", "pm_score": 2, "selected": false, "text": " String.prototype.dateFromJSON = function () {\n return eval(this.replace(/\\/Date\\((\\d+)\\)\\//gi, \"new Date($1)\"));\n};\n var date = new Date(parseInt(jsonDate.substr(6)));\n" }, { "answer_id": 2654571, "author": "ESV", "author_id": 150, "author_profile": "https://Stackoverflow.com/users/150", "pm_score": 4, "selected": false, "text": "var serializedDateTime = \"\\/Date(1271389496563)\\/\";\ndocument.writeln(\"Serialized: \" + serializedDateTime + \"<br />\");\n\nvar toDateRe = new RegExp(\"^/Date\\\\((\\\\d+)\\\\)/$\");\nfunction toDate(s) {\n if (!s) {\n return null;\n }\n var constructor = s.replace(toDateRe, \"new Date($1)\");\n if (constructor == s) {\n throw 'Invalid serialized DateTime value: \"' + s + '\"';\n }\n return eval(constructor);\n}\n\ndocument.writeln(\"Deserialized: \" + toDate(serializedDateTime) + \"<br />\");\n" }, { "answer_id": 41367697, "author": "tavo", "author_id": 3545581, "author_profile": "https://Stackoverflow.com/users/3545581", "pm_score": 2, "selected": false, "text": " var momentValue = moment(value);\n\n momentValue.toDate();\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9275/" ]
82,064
<p>I have a version number of the following form:</p> <p>version.release.modification</p> <p>where version, release and modification are either a set of digits or the '*' wildcard character. Additionally, any of these numbers (and any preceding .) may be missing.</p> <p>So the following are valid and parse as:</p> <pre><code>1.23.456 = version 1, release 23, modification 456 1.23 = version 1, release 23, any modification 1.23.* = version 1, release 23, any modification 1.* = version 1, any release, any modification 1 = version 1, any release, any modification * = any version, any release, any modification </code></pre> <p>But these are not valid:</p> <pre><code>*.12 *123.1 12* 12.*.34 </code></pre> <p>Can anyone provide me a not-too-complex regex to validate and retrieve the release, version and modification numbers?</p>
[ { "answer_id": 82104, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "^(\\*|\\d+(\\.\\d+){0,2}(\\.\\*)?)$\n (\\.\\d+){0,2}" }, { "answer_id": 82205, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 8, "selected": true, "text": "^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$\n \".\" @version = ();\n@groups = ($1, $2, $3);\nforeach (@groups) {\n next if !defined;\n s/\\.//;\n push @version, $_;\n}\n($major, $minor, $mod) = (@version, \"*\", \"*\");\n \".\"" }, { "answer_id": 82262, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 3, "selected": false, "text": "#!/usr/bin/perl -w\n\n\n@strings = ( \"1.2.3\", \"1.2.*\", \"1.*\",\"*\" );\n\n%regexp = ( svrist => qr/(?:(\\d+)\\.(\\d+)\\.(\\d+)|(\\d+)\\.(\\d+)|(\\d+))?(?:\\.\\*)?/,\n onebyone => qr/^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$/,\n greg => qr/^(\\*|\\d+(\\.\\d+){0,2}(\\.\\*)?)$/,\n vonc => qr/^((?:\\d+(?!\\.\\*)\\.)+)(\\d+)?(\\.\\*)?$|^(\\d+)\\.\\*$|^(\\*|\\d+)$/,\n ajb => qr/^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$/,\n jrudolph => qr/^(((\\d+)\\.)?(\\d+)\\.)?(\\d+|\\*)$/\n );\n\n foreach my $r (keys %regexp){\n my $reg = $regexp{$r};\n print \"Using $r regexp\\n\";\nforeach my $s (@strings){\n print \"$s : \";\n\n if ($s =~m/$reg/){\n my ($main, $maj, $min,$rev,$ex1,$ex2,$ex3) = (\"any\",\"any\",\"any\",\"any\",\"any\",\"any\",\"any\");\n $main = $1 if ($1 && $1 ne \"*\") ;\n $maj = $2 if ($2 && $2 ne \"*\") ;\n $min = $3 if ($3 && $3 ne \"*\") ;\n $rev = $4 if ($4 && $4 ne \"*\") ;\n $ex1 = $5 if ($5 && $5 ne \"*\") ;\n $ex2 = $6 if ($6 && $6 ne \"*\") ;\n $ex3 = $7 if ($7 && $7 ne \"*\") ;\n print \"$main $maj $min $rev $ex1 $ex2 $ex3\\n\";\n\n }else{\n print \" nomatch\\n\";\n }\n }\nprint \"------------------------\\n\";\n}\n > perl regex.pl\nUsing onebyone regexp\n1.2.3 : 1. 2. 3 any any any any\n1.2.* : 1. 2. any any any any any\n1.* : 1. any any any any any any\n* : any any any any any any any\n------------------------\nUsing svrist regexp\n1.2.3 : 1 2 3 any any any any\n1.2.* : any any any 1 2 any any\n1.* : any any any any any 1 any\n* : any any any any any any any\n------------------------\nUsing vonc regexp\n1.2.3 : 1.2. 3 any any any any any\n1.2.* : 1. 2 .* any any any any\n1.* : any any any 1 any any any\n* : any any any any any any any\n------------------------\nUsing ajb regexp\n1.2.3 : 1 2 3 any any any any\n1.2.* : 1 2 any any any any any\n1.* : 1 any any any any any any\n* : any any any any any any any\n------------------------\nUsing jrudolph regexp\n1.2.3 : 1.2. 1. 1 2 3 any any\n1.2.* : 1.2. 1. 1 2 any any any\n1.* : 1. any any 1 any any any\n* : any any any any any any any\n------------------------\nUsing greg regexp\n1.2.3 : 1.2.3 .3 any any any any any\n1.2.* : 1.2.* .2 .* any any any any\n1.* : 1.* any .* any any any any\n* : any any any any any any any\n------------------------\n" }, { "answer_id": 82271, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "(?ms)^((?:\\d+(?!\\.\\*)\\.)+)(\\d+)?(\\.\\*)?$|^(\\d+)\\.\\*$|^(\\*|\\d+)$\n" }, { "answer_id": 82427, "author": "Andrew Borley", "author_id": 7271, "author_profile": "https://Stackoverflow.com/users/7271", "pm_score": 4, "selected": false, "text": "^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$\n" }, { "answer_id": 82472, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 2, "selected": false, "text": "^(((\\d+)\\.)?(\\d+)\\.)?(\\d+|\\*)$\n" }, { "answer_id": 82488, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 2, "selected": false, "text": "^(\\*|(\\d+(\\.(\\d+(\\.(\\d+|\\*))?|\\*))?))$\n" }, { "answer_id": 82598, "author": "ofaurax", "author_id": 15209, "author_profile": "https://Stackoverflow.com/users/15209", "pm_score": 3, "selected": false, "text": "^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$\n ^(?:(\\d+)\\.){0,2}(\\*|\\d+)$\n" }, { "answer_id": 2619727, "author": "nomuus", "author_id": 314179, "author_profile": "https://Stackoverflow.com/users/314179", "pm_score": 3, "selected": false, "text": "^((\\*)|([0-9]+(\\.((\\*)|([0-9]+(\\.((\\*)|([0-9]+)))?)))?))$\n" }, { "answer_id": 16540907, "author": "Israel Romero", "author_id": 1485676, "author_profile": "https://Stackoverflow.com/users/1485676", "pm_score": 3, "selected": false, "text": "^(?:(0\\\\.|([1-9]+\\\\d*)\\\\.))+(?:(0\\\\.|([1-9]+\\\\d*)\\\\.))+((0|([1-9]+\\\\d*)))$\n" }, { "answer_id": 27540795, "author": "Sudhanshu Mishra", "author_id": 190476, "author_profile": "https://Stackoverflow.com/users/190476", "pm_score": 4, "selected": false, "text": "(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\.\\d+)\n void Main()\n{\n Regex regEx = new Regex(@\"(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\.\\d+)\", RegexOptions.Compiled);\n\n Match version = regEx.Match(\"The Service SuperService 2.1.309.0) is Running!\");\n version.Value.Dump(\"Version using RegEx\"); // Prints 2.1.309.0 \n}\n" }, { "answer_id": 39345000, "author": "Oleksandr Yarushevskyi", "author_id": 4262975, "author_profile": "https://Stackoverflow.com/users/4262975", "pm_score": 2, "selected": false, "text": "^[1-9][\\d]*(.[1-9][\\d]*)*(.\\*)?|\\*$\n" }, { "answer_id": 41364868, "author": "Emmerson", "author_id": 3159257, "author_profile": "https://Stackoverflow.com/users/3159257", "pm_score": 2, "selected": false, "text": "<xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:pattern value=\"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}(\\..*)?\"/>\n </xs:restriction>\n</xs:simpleType>\n" }, { "answer_id": 44088487, "author": "vitaly-t", "author_id": 1102051, "author_profile": "https://Stackoverflow.com/users/1102051", "pm_score": 2, "selected": false, "text": "function parseVersion(v) {\n var m = v.match(/\\d*\\.|\\d+/g) || [];\n v = {\n major: +m[0] || 0,\n minor: +m[1] || 0,\n patch: +m[2] || 0,\n build: +m[3] || 0\n };\n v.isEmpty = !v.major && !v.minor && !v.patch && !v.build;\n v.parsed = [v.major, v.minor, v.patch, v.build];\n v.text = v.parsed.join('.');\n return v;\n}\n" }, { "answer_id": 44500980, "author": "Shiva", "author_id": 2068802, "author_profile": "https://Stackoverflow.com/users/2068802", "pm_score": 3, "selected": false, "text": "'^[0-9][0-9.]*$'\n" }, { "answer_id": 62344454, "author": "Pau Ballada", "author_id": 1542507, "author_profile": "https://Stackoverflow.com/users/1542507", "pm_score": 3, "selected": false, "text": "^(\\d+)((\\.{1}\\d+)*)(\\.{0})$\n" }, { "answer_id": 64274924, "author": "Marc Ruef", "author_id": 6424520, "author_profile": "https://Stackoverflow.com/users/6424520", "pm_score": 2, "selected": false, "text": "([0-9]{1,4}(\\.[0-9a-z]{1,6}){1,5})\n" }, { "answer_id": 64784354, "author": "Or Assayag", "author_id": 4442606, "author_profile": "https://Stackoverflow.com/users/4442606", "pm_score": 1, "selected": false, "text": "/(\\^|\\~?)(\\d|x|\\*)+\\.(\\d|x|\\*)+\\.(\\d|x|\\*)+\n" }, { "answer_id": 70575435, "author": "山茶树和葡萄树", "author_id": 5819157, "author_profile": "https://Stackoverflow.com/users/5819157", "pm_score": 1, "selected": false, "text": "/^([1-9]{1}\\d{0,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\-(alpha|beta|rc|HP|CP|SP|hp|cp|sp)[1-9]\\d*)?(\\.C[0-9a-zA-Z]+(-U[1-9]\\d*)?)?(\\.[0-9a-zA-Z]+)?$/\n ([1-9]{1}\\d{0,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\.)([0-9]|[1-9]\\d{1,3}) (\\-(alpha|beta|rc|EP|HP|CP|SP|ep|hp|cp|sp)[1-9]\\d*)? (\\.C[0-9a-zA-Z]+(-U[1-9]\\d*)?)? (\\.[0-9a-zA-Z]+)?" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7271/" ]
82,074
<p>In a digital signal acquisition system, often data is pushed into an observer in the system by one thread. </p> <p>example from <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Wikipedia/Observer_pattern</a>:</p> <pre><code>foreach (IObserver observer in observers) observer.Update(message); </code></pre> <p>When e.g. a user action from e.g. a GUI-thread requires the data to stop flowing, you want to break the subject-observer connection, and even dispose of the observer alltogether.</p> <p>One may argue: you should just stop the data source, and wait for a sentinel value to dispose of the connection. But that would incur more latency in the system.</p> <p>Of course, if the data pumping thread has just asked for the address of the observer, it might find it's sending a message to a destroyed object.</p> <p>Has someone created an 'official' Design Pattern countering this situation? Shouldn't they?</p>
[ { "answer_id": 82116, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "event += observer event -= observer" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6610/" ]
82,099
<p>I have create a WCF service and am utilising netMsmqBinding binding.</p> <p>This is a simple service that passes a Dto to my service method and does not expect a response. The message is placed in an MSMQ, and once picked up inserted into a database.</p> <p>What is the best method to make sure no data is being lost.</p> <p>I have tried the 2 following methods:</p> <ol> <li><p>Throw an exception</p> <p>This places the message in a dead letter queue for manual perusal. I can process this when my strvice starts</p> </li> <li><p>set the receiveRetryCount=&quot;3&quot; on the binding</p> <p>After 3 tries - which happen instantanously, this seems to leave the message in queue, but fault my service. Restarting my service repeats this process.</p> </li> </ol> <p>Ideally I would like to do the follow:</p> <p>Try process the message</p> <ul> <li>If this fails, wait 5 minutes for that message and try again.</li> <li>If that process fails 3 times, move the message to a dead letter queue.</li> <li>Restarting the service will push all messages from the dead letter queue back into the queue so that it can be processed.</li> </ul> <p>Can I achieve this? If so how? Can you point me to any good articles on how best to utilize WCF and MSMQ for my given sceneria.</p> <p>Any help would be much appreciated. Thanks!</p> <p><strong>Some additional information</strong></p> <p>I am using MSMQ 3.0 on Windows XP and Windows Server 2003. Unfortunately I can't use the built in poison message support targeted at MSMQ 4.0 and Vista/2008.</p>
[ { "answer_id": 82586, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 4, "selected": false, "text": "<bindings>\n <netMsmqBinding>\n <binding name=\"PosionMessageHandling\"\n receiveRetryCount=\"3\"\n retryCycleDelay=\"00:05:00\"\n maxRetryCycles=\"3\"\n receiveErrorHandling=\"Move\" />\n </netMsmqBinding>\n</bindings>\n" }, { "answer_id": 82822, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 2, "selected": false, "text": " [OperationBehavior(TransactionScopeRequired=true, TransactionAutoComplete=true)]\n public void InsertRecord(RecordType record)\n {\n try\n {\n using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))\n {\n SqlConnection InsertConnection = new SqlConnection(ConnectionString);\n InsertConnection.Open();\n\n // Insert statements go here\n\n InsertConnection.Close();\n\n // Vote to commit the transaction if there were no failures\n scope.Complete();\n }\n }\n catch (Exception ex)\n {\n logger.WarnException(string.Format(\"Distributed transaction failure for {0}\", \n Transaction.Current.TransactionInformation.DistributedIdentifier.ToString()),\n ex);\n }\n }\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15360/" ]
82,109
<p>I am using Java 1.4 with Log4J. </p> <p>Some of my code involves serializing and deserializing value objects (POJOs). </p> <p>Each of my POJOs declares a logger with</p> <pre><code>private final Logger log = Logger.getLogger(getClass()); </code></pre> <p>The serializer complains of org.apache.log4j.Logger not being Serializable.</p> <p>Should I use</p> <pre><code>private final transient Logger log = Logger.getLogger(getClass()); </code></pre> <p>instead?</p>
[ { "answer_id": 82132, "author": "Aleksi Yrttiaho", "author_id": 11427, "author_profile": "https://Stackoverflow.com/users/11427", "pm_score": 6, "selected": true, "text": "ObjectStreamField serialPersistentFields" }, { "answer_id": 82565, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 3, "selected": false, "text": " private void readObject(java.io.ObjectInputStream in) \n throws IOException, ClassNotFoundException;\n private void readObject(java.io.ObjectInputStream in) \n throws IOException, ClassNotFoundException {\n log = Logger.getLogger(...);\n in.defaultReadObject();\n }\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]
82,123
<p>I'm new to BIRT and I'm trying to make the Report Engine running. I'm using the code snippets provided in <a href="http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php" rel="nofollow noreferrer">http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php</a></p> <p>But I have a strange exception:</p> <blockquote> <p>java.lang.AssertionError at org.eclipse.birt.core.framework.Platform.startup(Platform.java:86)</p> </blockquote> <p>and nothing in the log file.</p> <p>Maybe I missed something in the configuration? Could somebody give me a hint about what I can try to make it running?</p> <p>Here is the code I'm using:</p> <pre><code>public static void executeReport() { IReportEngine engine=null; EngineConfig config = null; try{ config = new EngineConfig( ); config.setBIRTHome("D:\\birt-runtime-2_3_0\\ReportEngine"); config.setLogConfig("d:/temp", Level.FINEST); Platform.startup( config ); IReportEngineFactory factory = (IReportEngineFactory) Platform .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY ); engine = factory.createReportEngine( config ); IReportRunnable design = null; //Open the report design design = engine.openReportDesign("D:\\birt-runtime-2_3_0\\ReportEngine\\samples\\hello_world.rptdesign"); IRunAndRenderTask task = engine.createRunAndRenderTask(design); HTMLRenderOption options = new HTMLRenderOption(); options.setOutputFileName("output/resample/Parmdisp.html"); options.setOutputFormat("html"); task.setRenderOption(options); task.run(); task.close(); engine.destroy(); }catch( Exception ex){ ex.printStackTrace(); } finally { Platform.shutdown( ); } } </code></pre>
[ { "answer_id": 82229, "author": "cH1cK3n", "author_id": 15615, "author_profile": "https://Stackoverflow.com/users/15615", "pm_score": 2, "selected": false, "text": " IDesignEngine engine = null;\n DesignConfig dConfig = new DesignConfig();\n EngineConfig config = new EngineConfig();\n IDesignEngineFactory factory = null;\n config.setLogConfig(LOG_DIRECTORY, Level.FINE);\n HttpServletRequest servletRequest = (HttpServletRequest) FacesContext.getCurrentInstance()\n .getExternalContext().getRequest();\n\n String u = servletRequest.getSession().getServletContext().getRealPath(\"/\");\n File f = new File(u + PATH_TO_ENGINE_HOME);\n\n log.debug(\"setting engine home to:\"+f.getAbsolutePath());\n config.setEngineHome(f.getAbsolutePath());\n\n Platform.startup(config);\n factory = (IDesignEngineFactory) Platform.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);\n engine = factory.createDesignEngine(dConfig);\n SessionHandle session = engine.newSessionHandle(null);\n\n this.design = session.openDesign(u + PATH_TO_MAIN_DESIGN);\n" }, { "answer_id": 93278, "author": "Scott Rosenbaum", "author_id": 5412, "author_profile": "https://Stackoverflow.com/users/5412", "pm_score": 2, "selected": true, "text": "config.setLogConfig(\"d:/temp\", Level.FINEST);\n config.setLogConfig(\"/temp\", Level.FINEST);\n config.setLogConfig(\"d:\\\\temp\", Level.FINEST);\n http://longlake.minnovent.com/repos/birt_example\n birt_api_example\nbirt_runtime_lib\nscript.lib\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
82,128
<p>Our build server is taking too long to build one of our C++ projects. It uses <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#2008" rel="nofollow noreferrer">Visual Studio 2008</a>, running <code>devenv.com MyApp.sln /Build</code> -- see <a href="https://learn.microsoft.com/en-us/visualstudio/ide/reference/devenv-command-line-switches?view=vs-2022" rel="nofollow noreferrer">devenv command-line switches</a> (although that's for a newer version of VS). Is there a way to get devenv.com to log the time taken to build each project in the solution, so that I know where to focus my efforts?</p> <p>Improved hardware is not an option in this case.</p> <p>I've tried setting the output verbosity (under menu <em>Tools</em> → <em>Options</em> → <em>Projects and Solutions</em> → <em>Build and Run</em> → <em>MSBuild project build output verbosity</em>). This doesn't seem to have any effect in the IDE.</p> <p>When running MSBuild from the command line (and, for Visual Studio 2008, it needs to be MSBuild v3.5), it displays the total time elapsed at the end, but not in the IDE.</p> <p>I really wanted a time-taken report for each project in the solution, so that I could figure out where the build process was taking its time.</p>
[ { "answer_id": 82218, "author": "Dave Moore", "author_id": 6996, "author_profile": "https://Stackoverflow.com/users/6996", "pm_score": 3, "selected": false, "text": "msbuild /fl /flp:Verbosity=diagnostic Your.sln\n msbuild /?" }, { "answer_id": 29146660, "author": "InbetweenWeekends", "author_id": 902874, "author_profile": "https://Stackoverflow.com/users/902874", "pm_score": 2, "selected": false, "text": "echo %date% %time%" }, { "answer_id": 31827370, "author": "Blue Clouds", "author_id": 1501191, "author_profile": "https://Stackoverflow.com/users/1501191", "pm_score": 2, "selected": false, "text": "echo ###########%date% %time%#############" }, { "answer_id": 37139065, "author": "Andreas Haferburg", "author_id": 872616, "author_profile": "https://Stackoverflow.com/users/872616", "pm_score": 1, "selected": false, "text": "End Module Dim buildStart As Date\n\nPrivate Sub RunCtime(ByVal StartRatherThanEnd As Boolean)\n Dim Arg As String\n Dim psi As New System.Diagnostics.ProcessStartInfo(\"ctime.exe\")\n If StartRatherThanEnd Then\n psi.Arguments = \"-begin\"\n Else\n psi.Arguments = \"-end\"\n End If\n psi.Arguments += \" c:\\my\\path\\build.ctm\"\n psi.RedirectStandardOutput = False\n psi.WindowStyle = ProcessWindowStyle.Hidden\n psi.UseShellExecute = False\n psi.CreateNoWindow = True\n Dim process As System.Diagnostics.Process\n process = System.Diagnostics.Process.Start(psi)\n Dim myOutput As System.IO.StreamReader = process.StandardOutput\n process.WaitForExit(2000)\n If process.HasExited Then\n Dim output As String = myOutput.ReadToEnd\n WriteToBuildWindow(\"CTime output: \" + output)\n End If\nEnd Sub\n\nPrivate Sub BuildEvents_OnBuildBegin(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildBegin\n WriteToBuildWindow(\"Build started!\")\n buildStart = Date.Now\n RunCtime(True)\nEnd Sub\n\nPrivate Sub BuildEvents_OnBuildDone(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildDone\n Dim buildTime = Date.Now - buildStart\n WriteToBuildWindow(String.Format(\"Total build time: {0} seconds\", buildTime.ToString))\n RunCtime(False)\nEnd Sub\n\nPrivate Sub WriteToBuildWindow(ByVal message As String)\n Dim win As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)\n Dim ow As OutputWindow = CType(win.Object, OutputWindow)\n If (Not message.EndsWith(vbCrLf)) Then\n message = message + vbCrLf\n End If\n ow.OutputWindowPanes.Item(\"Build\").OutputString(message)\nEnd Sub\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8446/" ]
82,141
<p>I have 6 sound files (1.wav 2.wav etc..) of which 3 different ones have to be heard each time the web page opens. The numbers are selected randomly. I have tried multiple "embeds" but only the last sound selected gets produced. I have also tried javascript routines that fiddle the bgsound attribute, however, I was not able to produce more than one sound at a time. The sounds are required to play either automatically on page open or they can be triggered by a click on a button or link, however, only one click is acceptable for the three sounds. Is there another way to do this? suggestions very welcome.</p>
[ { "answer_id": 82222, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "1_2_3, 1_2_3, 1_2_5, 1_2_6 \n1_3_4, 1_3_5, 1_3_6\n1_4_5, 1_4_6\n2_3_4, 2_3_5, 2_3_6, \n2_4_5, 2_4_6,\n2_5_6\n3_4_5, 3_4_6,\n3_5_6,\n4_5_6\n $n = [ randomnumber , randomnumber , randomnumber ]; \n $n = sort $n; \n file = \"$n[0]_$n[1]_$n[2].wav\" \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15588/" ]
82,191
<p>I'm creating a plugin, and am looking to use RSpec so I can build it using BDD. </p> <p>Is there a recommended method of doing this?</p>
[ { "answer_id": 83039, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 2, "selected": true, "text": "\n require 'spec/rake/spectask' \n\ndesc 'Test the PLUGIN_NAME plugin.'\nSpec::Rake::SpecTask.new(:spec) do |t|\n t.libs << 'lib'\n t.verbose = true\nend\n\n\n desc 'Test the PLUGIN_NAME plugin.'\nSpec::Rake::SpecTask.new(:spec) do |t|\n t.libs << 'lib'\n t.verbose = true\nend\n " } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12037/" ]
82,214
<p>In the early days of SharePoint 2007 beta, I've come across the ability to customize the template used to emit the RSS feeds from lists. I can't find it again. Anybody know where it is?</p>
[ { "answer_id": 83039, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 2, "selected": true, "text": "\n require 'spec/rake/spectask' \n\ndesc 'Test the PLUGIN_NAME plugin.'\nSpec::Rake::SpecTask.new(:spec) do |t|\n t.libs << 'lib'\n t.verbose = true\nend\n\n\n desc 'Test the PLUGIN_NAME plugin.'\nSpec::Rake::SpecTask.new(:spec) do |t|\n t.libs << 'lib'\n t.verbose = true\nend\n " } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533/" ]
82,232
<p>Problem:<br/></p> <ol> <li>html file on local server (inside our organization) with link to an exe on the same server.</li> <li>clicking the link runs the exe on the client. Instead I want it to offer downloading it.</li> </ol> <p>Tried so far:<br/></p> <ol> <li>Changed permissions on the exe's virtual directory to be read and script.</li> <li>Added Content-disposition header on the exe's directory.</li> <li>I can't change settings in the browser. It's intended for a lot of people to consume.</li> </ol>
[ { "answer_id": 82246, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "content-disposition" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11519/" ]
82,235
<p>I'm experiencing the following very annoying behaviour when using JPA entitys in conjunction with Oracle 10g. </p> <p>Suppose you have the following entity.</p> <pre><code>@Entity @Table(name = "T_Order") public class TOrder implements Serializable { private static final long serialVersionUID = 2235742302377173533L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "activationDate") private Calendar activationDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Calendar getActivationDate() { return activationDate; } public void setActivationDate(Calendar activationDate) { this.activationDate = activationDate; } } </code></pre> <p>This entity is mapped to Oracle 10g, so in the DB there will be a table <code>T_ORDER</code> with a primary key <code>NUMBER</code> column <code>ID</code> and a <code>TIMESTAMP</code> column <code>activationDate</code>.</p> <p>Lets suppose I create an instance of this class with the activation date <code>15. Sep 2008 00:00AM</code>. My local timezone is CEST which is <code>GMT+02:00</code>. When I persist this object and select the data from the table <code>T_ORDER</code> using sqlplus, I find out that in the table actually <code>14. Sep 2008 22:00</code> is stored, which is ok so far, because the oracle db timezone is GMT.</p> <p>But now the annoying part. When I read this entity back into my JAVA program, I find out that the oracle time zone is ignored and I get <code>14. Sep 2008 22:00 CEST</code>, which is definitly wrong. </p> <p>So basically, when writing to the DB the timezone information will be used, when reading it will be ignored.</p> <p>Is there any solution for this out there? The most simple solution I guess would be to set the oracle dbs timezone to <code>GMT+02</code>, but unfortunatly I can't do this because there are other applications using the same server.</p> <p>We use the following technology</p> <p>MyEclipse 6.5 JPA with Hibernate 3.2 Oracle 10g thin JDBC Driver</p>
[ { "answer_id": 85329, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 3, "selected": true, "text": "java.util.Date @Temporal(TemporalType.TIMESTAMP)\n@Column(name=\"activationDate\")\npublic Date getActivationDate() {\n return this.activationDate;\n}\n java.util.Date" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15657/" ]
82,256
<p>I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.</p> <p>The trouble is, this contrived example doesn't work:</p> <pre><code>sudo ls -hal /root/ &gt; /root/test.out </code></pre> <p>I just receive the response:</p> <pre><code>-bash: /root/test.out: Permission denied </code></pre> <p>How can I get this to work?</p>
[ { "answer_id": 82274, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "#!/bin/sh\n\n/bin/ls -lah /root > /root/test.out\n\n# end script\n sudo ./myscript\n" }, { "answer_id": 82276, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 5, "selected": false, "text": "sudo sh -c \"echo foo > ~root/out\"\n" }, { "answer_id": 82278, "author": "Cristian Ciupitu", "author_id": 12892, "author_profile": "https://Stackoverflow.com/users/12892", "pm_score": 12, "selected": true, "text": "/root/test.out -c sudo sh -c 'ls -hal /root/ > /root/test.out'\n #!/bin/sh\nls -hal /root/ > /root/test.out\n sudo ls.sh sudo -s [nobody@so]$ sudo -s\n[root@so]# ls -hal /root/ > /root/test.out\n[root@so]# ^D\n[nobody@so]$\n sudo tee -c sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null\n /dev/null >> tee -a tee --append" }, { "answer_id": 82279, "author": "Adam J. Forster", "author_id": 15676, "author_profile": "https://Stackoverflow.com/users/15676", "pm_score": 3, "selected": false, "text": "# sudo -s\n# ls -hal /root/ > /root/test.out\n# exit\n" }, { "answer_id": 82331, "author": "user15453", "author_id": 15453, "author_profile": "https://Stackoverflow.com/users/15453", "pm_score": 1, "selected": false, "text": "cat > myscript.sh\n#!/bin/sh\nls -hal /root/ > /root/test.out \n chmod a+x myscript.sh\nsudo myscript.sh\n" }, { "answer_id": 82553, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 7, "selected": false, "text": "sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null\n" }, { "answer_id": 120174, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 6, "selected": false, "text": "sudo sudo command > /some/file.log\n`-----v-----'`-------v-------'\n command redirection\n sudo log_script command /log/file.txt\n -c sudo bash -c \"{ command1 arg; command2 arg; } > /log/file.txt\"\n # Read and append to a file\ncat ./'file1.txt' | sudo tee -a '/log/file.txt' > '/dev/null';\n\n# Store both stdout and stderr streams in a file\n{ command1 arg; command2 arg; } |& sudo tee -a '/log/file.txt' > '/dev/null';\n" }, { "answer_id": 8213307, "author": "rhlee", "author_id": 420540, "author_profile": "https://Stackoverflow.com/users/420540", "pm_score": 7, "selected": false, "text": "sudo ls -hal /root/ | sudo dd of=/root/test.out\n" }, { "answer_id": 16131140, "author": "fardjad", "author_id": 303270, "author_profile": "https://Stackoverflow.com/users/303270", "pm_score": 3, "selected": false, "text": "sudo su -c 'ls -hal /root/ > /root/test.out'\n" }, { "answer_id": 16514624, "author": "Steve Bennett", "author_id": 263268, "author_profile": "https://Stackoverflow.com/users/263268", "pm_score": 5, "selected": false, "text": "sudo bash <<EOF\nls -hal /root/ > /root/test.out\nEOF\n echo 'ls -hal /root/ > /root/test.out' | sudo bash\n sudo sh bash" }, { "answer_id": 19738137, "author": "jg3", "author_id": 2094009, "author_profile": "https://Stackoverflow.com/users/2094009", "pm_score": 5, "selected": false, "text": "ls -hal /root/ | sudo tee /root/test.out\n # kill off one source of annoying advertisements\necho 127.0.0.1 ad.doubleclick.net | sudo tee -a /etc/hosts\n\n# configure eth4 to come up on boot, set IP and netmask (centos 6.4)\necho -e \"ONBOOT=\\\"YES\\\"\\nIPADDR=10.42.84.168\\nPREFIX=24\" | sudo tee -a /etc/sysconfig/network-scripts/ifcfg-eth4\n echo >> >" }, { "answer_id": 20234210, "author": "jamadagni", "author_id": 1503120, "author_profile": "https://Stackoverflow.com/users/1503120", "pm_score": 2, "selected": false, "text": "tee suwrite /usr/local/bin/ +x #! /bin/sh\nif [ $# = 0 ] ; then\n echo \"USAGE: <command writing to stdout> | suwrite [-a] <output file 1> ...\" >&2\n exit 1\nfi\nfor arg in \"$@\" ; do\n if [ ${arg#/dev/} != ${arg} ] ; then\n echo \"Found dangerous argument ‘$arg’. Will exit.\"\n exit 2\n fi\ndone\nsudo tee \"$@\" > /dev/null\n sudo echo test | suwrite /root/test.txt\n tee -a echo test2 | suwrite -a /root/test.txt\necho test-multi | suwrite /root/test-a.txt /root/test-b.txt\n /dev/" }, { "answer_id": 38021076, "author": "Nikola Petkanski", "author_id": 581062, "author_profile": "https://Stackoverflow.com/users/581062", "pm_score": 4, "selected": false, "text": "echo \"some text\" | sudo tee /path/to/file\n echo \"some text\" | sudo tee -a /path/to/file\n" }, { "answer_id": 38632314, "author": "haridsv", "author_id": 95750, "author_profile": "https://Stackoverflow.com/users/95750", "pm_score": 4, "selected": false, "text": "tee stdout /dev/null cat sudo ls -hal /root/ | sudo bash -c \"cat > /root/test.out\"\n sudo" }, { "answer_id": 46342096, "author": "user8648126", "author_id": 8648126, "author_profile": "https://Stackoverflow.com/users/8648126", "pm_score": 2, "selected": false, "text": "sudo at now \nat> echo test > /tmp/test.out \nat> <EOT> \njob 1 at Thu Sep 21 10:49:00 2017 \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6910/" ]
82,259
<p>Ever wanted to have an HTML drag and drop sortable table in which you could sort both rows and columns? I know it's something I'd die for. There's a lot of sortable lists going around but finding a sortable table seems to be impossible to find. </p> <p>I know that you can get pretty close with the tools that script.aculo.us provides but I ran into some cross-browser issues with them. </p>
[ { "answer_id": 100514, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 5, "selected": false, "text": "<table id=\"myTable\">\n<thead>\n<tr><th>ID</th><th>Name</th><th>Details</th></tr>\n</thead>\n<tbody class=\"sort\">\n<tr id=\"1\"><td>1</td><td>Name1</td><td>Details1</td></tr>\n<tr id=\"2\"><td>2</td><td>Name1</td><td>Details2</td></tr>\n<tr id=\"3\"><td>3</td><td>Name1</td><td>Details3</td></tr>\n<tr id=\"4\"><td>4</td><td>Name1</td><td>Details4</td></tr>\n</tbody>\n</table>\n $('.sort').sortable({\n cursor: 'move',\n axis: 'y',\n update: function(e, ui) {\n href = '/myReorderFunctionURL/';\n $(this).sortable(\"refresh\");\n sorted = $(this).sortable(\"serialize\", 'id');\n $.ajax({\n type: 'POST',\n url: href,\n data: sorted,\n success: function(msg) {\n //do something with the sorted data\n }\n });\n }\n});\n" }, { "answer_id": 362459, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var sort = function(event, ui) {\n var url = \"/myReorderFunctionURL/\" + $(this).sortable('serialize');\n $.post(url, null,null,\"script\"); // sortable(\"refresh\") is automatic\n}\n\n$(\".sort\").sortable({\n cursor: 'move',\n axis: 'y',\n stop: sort\n});\n" }, { "answer_id": 11133174, "author": "CDR", "author_id": 50542, "author_profile": "https://Stackoverflow.com/users/50542", "pm_score": 0, "selected": false, "text": "<tr id=\"id_1\"><td>1</td><td>Name1</td><td>Details1</td></tr>\n<tr id=\"id_2\"><td>2</td><td>Name1</td><td>Details2</td></tr>\n<tr id=\"id_3\"><td>3</td><td>Name1</td><td>Details3</td></tr>\n<tr id=\"id_4\"><td>4</td><td>Name1</td><td>Details4</td></tr>\n" }, { "answer_id": 54500687, "author": "PirateApp", "author_id": 5371505, "author_profile": "https://Stackoverflow.com/users/5371505", "pm_score": 0, "selected": false, "text": "Vue.directive(\"draggable\", {\n //adapted from https://codepen.io/kminek/pen/pEdmoo\n inserted: function(el, binding, a) {\n Sortable.create(el, {\n draggable: \".draggable\",\n onEnd: function(e) {\n /* vnode.context is the context vue instance: \"This is not documented as it's not encouraged to manipulate the vm from directives in Vue 2.0 - instead, directives should be used for low-level DOM manipulation, and higher-level stuff should be solved with components instead. But you can do this if some usecase needs this. */\n // fixme: can this be reworked to use a component?\n // https://github.com/vuejs/vue/issues/4065\n // https://forum.vuejs.org/t/how-can-i-access-the-vm-from-a-custom-directive-in-2-0/2548/3\n // https://github.com/vuejs/vue/issues/2873 \"directive interface change\"\n // `binding.expression` should be the name of your array from vm.data\n // set the expression like v-draggable=\"items\"\n\n var clonedItems = a.context[binding.expression].filter(function(item) {\n return item;\n });\n clonedItems.splice(e.newIndex, 0, clonedItems.splice(e.oldIndex, 1)[0]);\n a.context[binding.expression] = [];\n Vue.nextTick(function() {\n a.context[binding.expression] = clonedItems;\n });\n\n }\n });\n }\n});\n\nconst cols = [\n {name: \"One\", id: \"one\", canMove: false},\n {name: \"Two\", id: \"two\", canMove: true},\n {name: \"Three\", id: \"three\", canMove: true},\n {name: \"Four\", id: \"four\", canMove: true},\n]\n\nconst rows = [\n {one: \"Hi there\", two: \"I am so excited to test\", three: \"this column that actually drags and replaces\", four: \"another column in its place only if both can move\"},\n {one: \"Hi\", two: \"I\", three: \"am\", four: \"two\"},\n {one: \"Hi\", two: \"I\", three: \"am\", four: \"three\"},\n {one: \"Hi\", two: \"I\", three: \"am\", four: \"four\"},\n {one: \"Hi\", two: \"I\", three: \"am\", four: \"five\"},\n {one: \"Hi\", two: \"I\", three: \"am\", four: \"six\"},\n {one: \"Hi\", two: \"I\", three: \"am\", four: \"seven\"}\n]\n\nVue.component(\"datatable\", {\n template: \"#datatable\",\n data() {\n return {\n cols: cols,\n rows: rows\n }\n }\n})\n\nnew Vue({\n el: \"#app\"\n})\n .draggable {\n cursor: move;\n}\n\ntable.table tbody td {\n white-space: nowrap;\n}\n #app\n datatable\n\nscript(type=\"text/x-template\" id=\"datatable\")\n table.table\n thead(v-draggable=\"cols\")\n template(v-for=\"c in cols\")\n th(:class=\"{draggable: c.canMove}\")\n b-dropdown#ddown1.m-md-2(:text='c.name')\n b-dropdown-item First Action\n b-dropdown-item Second Action\n b-dropdown-item Third Action\n b-dropdown-divider\n b-dropdown-item Something else here...\n b-dropdown-item(disabled='') Disabled action\n\n tbody\n template(v-for=\"row in rows\")\n tr\n template(v-for=\"(col, index) in cols\")\n td {{row[col.id]}}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7382/" ]
82,268
<p>I have to deal with text files in a motley selection of formats. Here's an example (Columns <strong>A</strong> and <strong>B</strong> are tab delimited):</p> <pre><code>A B a Name1=Val1, Name2=Val2, Name3=Val3 b Name1=Val4, Name3=Val5 c Name1=Val6, Name2=Val7, Name3=Val8 </code></pre> <p>The files could have headers or not, have mixed delimiting schemes, have columns with name/value pairs as above etc.<br> I often have the ad-hoc need to extract data from such files in various ways. For example from the above data I might want the value associated with Name2 where it is present. i.e.</p> <pre><code>A B a Val2 c Val7 </code></pre> <p>What tools/techniques are there for performing such manipulations as one line commands, using the above as an example but extensible to other cases?</p>
[ { "answer_id": 82300, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 0, "selected": false, "text": " # print section of file between two regular expressions (inclusive)\n sed -n '/Iowa/,/Montana/p' # case sensitive\n" }, { "answer_id": 82353, "author": "Weidenrinde", "author_id": 11344, "author_profile": "https://Stackoverflow.com/users/11344", "pm_score": 2, "selected": true, "text": "var=\"Name2\";sed -n \"1p;s/\\([^ ]*\\) .*$var=\\([^ ,]*\\).*/\\1 \\2/p\" < filename\n A B\n a Val2\n c Val7\n" }, { "answer_id": 82557, "author": "deterb", "author_id": 15585, "author_profile": "https://Stackoverflow.com/users/15585", "pm_score": 0, "selected": false, "text": "perl -e 'use Parser;' -e 'parser(\"in.input\").get(\"Name2\");'\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6387/" ]
82,286
<p>I want to place a Webpart on a page that holds a subfolder of the Document Library in SharePoint, but somehow, the only thing I get is the root folder of the document library.</p> <p>Is there a Webpart that fills this need?</p>
[ { "answer_id": 156049, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 1, "selected": false, "text": "\"?RootFolder=%2fDocuments%2fMyFolder1&FolderCTID=\"\n \\\\sharepointsite\\documents" }, { "answer_id": 12008006, "author": "Derek", "author_id": 1607210, "author_profile": "https://Stackoverflow.com/users/1607210", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\" language=\"javascript\">\n\n //change this to meet your needs\n var patt = /FOLDER%20TO%20SEARCH/gi; \n var x = document.getElementsByTagName(\"TD\"); // find all of the TDs\n var i=0; \n\n for (i=0;i<x.length;i++)\n {\n if (x[i].className ==\"ms-vb-title\") //find the TDs styled for documents\n {\n var y = x[i].getElementsByTagName(\"A\"); //this gets the URL linked to the name field\n //conveniently the URL is the first variable in the array. YMMV.\n var title = y[0]; \n\n //search for pattern\n var result = patt.test(title);\n\n //If the pattern isn't in that row, do not display the row\n if ( !result )\n {\n x[i].parentNode.style.display = \"none\"; //and hide the row \n }\n }\n } \n</script> \n" }, { "answer_id": 29227940, "author": "JohnDUSA", "author_id": 3612746, "author_profile": "https://Stackoverflow.com/users/3612746", "pm_score": 1, "selected": false, "text": "www.mysite.com/sharepoint/default.aspx?RootFolder=%2Fsubfoldername&FolderCTID=... &FolderCTID www.mysite.com/sharepoint/default.aspx?RootFolder=%2Fsubfoldername" }, { "answer_id": 47141636, "author": "Alberto S.", "author_id": 1538604, "author_profile": "https://Stackoverflow.com/users/1538604", "pm_score": 1, "selected": false, "text": "path:[your site]/Docs/our_team UrlDepth:7 \n path:[your site]/Docs/\"our team\"\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15637/" ]
82,319
<p>In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there: (channels) * (bits) * (samples/s) * (seconds) = (filesize)</p> <p>Is there a simpler way - a free library, or something in the .net framework perhaps?</p> <p>How would I do this if the .wav file is compressed (with the mpeg codec for example)?</p>
[ { "answer_id": 82408, "author": "Jan Zich", "author_id": 15716, "author_profile": "https://Stackoverflow.com/users/15716", "pm_score": 6, "selected": true, "text": "using System;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace Sound\n{\n public static class SoundInfo\n {\n [DllImport(\"winmm.dll\")]\n private static extern uint mciSendString(\n string command,\n StringBuilder returnValue,\n int returnLength,\n IntPtr winHandle);\n\n public static int GetSoundLength(string fileName)\n {\n StringBuilder lengthBuf = new StringBuilder(32);\n\n mciSendString(string.Format(\"open \\\"{0}\\\" type waveaudio alias wave\", fileName), null, 0, IntPtr.Zero);\n mciSendString(\"status wave length\", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);\n mciSendString(\"close wave\", null, 0, IntPtr.Zero);\n\n int length = 0;\n int.TryParse(lengthBuf.ToString(), out length);\n\n return length;\n }\n }\n}\n" }, { "answer_id": 396113, "author": "Lars", "author_id": 42809, "author_profile": "https://Stackoverflow.com/users/42809", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Text;\nusing System.Windows.Media;\nusing System.Windows;\n\nnamespace ConsoleApplication2\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args.Length == 0)\n return;\n Console.Write(args[0] + \": \");\n MediaPlayer player = new MediaPlayer();\n Uri path = new Uri(args[0]);\n player.Open(path);\n TimeSpan maxWaitTime = TimeSpan.FromSeconds(10);\n DateTime end = DateTime.Now + maxWaitTime;\n while (DateTime.Now < end)\n {\n System.Threading.Thread.Sleep(100);\n Duration duration = player.NaturalDuration;\n if (duration.HasTimeSpan)\n {\n Console.WriteLine(duration.TimeSpan.ToString());\n break;\n }\n }\n player.Close();\n }\n }\n}\n" }, { "answer_id": 2009777, "author": "Josh Stodola", "author_id": 54420, "author_profile": "https://Stackoverflow.com/users/54420", "pm_score": 3, "selected": false, "text": "Microsoft.DirectX.AudioVideoPlayBack Public Shared Function GetDuration(ByVal Path As String) As Integer\n If File.Exists(Path) Then\n Return CInt(New Audio(Path, False).Duration)\n Else\n Throw New FileNotFoundException(\"Audio File Not Found: \" & Path)\n End If\nEnd Function\n" }, { "answer_id": 8181938, "author": "Monti Pal", "author_id": 1053726, "author_profile": "https://Stackoverflow.com/users/1053726", "pm_score": 5, "selected": false, "text": "public static TimeSpan GetWavFileDuration(string fileName) \n{ \n WaveFileReader wf = new WaveFileReader(fileName);\n return wf.TotalTime; \n}\n" }, { "answer_id": 12416165, "author": "Neoheurist", "author_id": 1670042, "author_profile": "https://Stackoverflow.com/users/1670042", "pm_score": -1, "selected": false, "text": "Imports System.IO\nImports System.Text\n\nImports System.Math\nImports System.BitConverter\n\nPublic Class PulseCodeModulation\n ' Pulse Code Modulation WAV (RIFF) file layout\n\n ' Header chunk\n\n ' Type Byte Offset Description\n ' Dword 0 Always ASCII \"RIFF\"\n ' Dword 4 Number of bytes in the file after this value (= File Size - 8)\n ' Dword 8 Always ASCII \"WAVE\"\n\n ' Format Chunk\n\n ' Type Byte Offset Description\n ' Dword 12 Always ASCII \"fmt \"\n ' Dword 16 Number of bytes in this chunk after this value\n ' Word 20 Data format PCM = 1 (i.e. Linear quantization)\n ' Word 22 Channels Mono = 1, Stereo = 2\n ' Dword 24 Sample Rate per second e.g. 8000, 44100\n ' Dword 28 Byte Rate per second (= Sample Rate * Channels * (Bits Per Sample / 8))\n ' Word 32 Block Align (= Channels * (Bits Per Sample / 8))\n ' Word 34 Bits Per Sample e.g. 8, 16\n\n ' Data Chunk\n\n ' Type Byte Offset Description\n ' Dword 36 Always ASCII \"data\"\n ' Dword 40 The number of bytes of sound data (Samples * Channels * (Bits Per Sample / 8))\n ' Buffer 44 The sound data\n\n Dim HeaderData(43) As Byte\n\n Private AudioFileReference As String\n\n Public Sub New(ByVal AudioFileReference As String)\n Try\n Me.HeaderData = Read(AudioFileReference, 0, Me.HeaderData.Length)\n Catch Exception As Exception\n Throw\n End Try\n\n 'Validate file format\n\n Dim Encoder As New UTF8Encoding()\n\n If \"RIFF\" <> Encoder.GetString(BlockCopy(Me.HeaderData, 0, 4)) Or _\n \"WAVE\" <> Encoder.GetString(BlockCopy(Me.HeaderData, 8, 4)) Or _\n \"fmt \" <> Encoder.GetString(BlockCopy(Me.HeaderData, 12, 4)) Or _\n \"data\" <> Encoder.GetString(BlockCopy(Me.HeaderData, 36, 4)) Or _\n 16 <> ToUInt32(BlockCopy(Me.HeaderData, 16, 4), 0) Or _\n 1 <> ToUInt16(BlockCopy(Me.HeaderData, 20, 2), 0) _\n Then\n Throw New InvalidDataException(\"Invalid PCM WAV file\")\n End If\n\n Me.AudioFileReference = AudioFileReference\n End Sub\n\n ReadOnly Property Channels() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 22, 2), 0) 'mono = 1, stereo = 2\n End Get\n End Property\n\n ReadOnly Property SampleRate() As Integer\n Get\n Return ToUInt32(BlockCopy(Me.HeaderData, 24, 4), 0) 'per second\n End Get\n End Property\n\n ReadOnly Property ByteRate() As Integer\n Get\n Return ToUInt32(BlockCopy(Me.HeaderData, 28, 4), 0) 'sample rate * channels * (bits per channel / 8)\n End Get\n End Property\n\n ReadOnly Property BlockAlign() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 32, 2), 0) 'channels * (bits per sample / 8)\n End Get\n End Property\n\n ReadOnly Property BitsPerSample() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 34, 2), 0)\n End Get\n End Property\n\n ReadOnly Property Duration() As Integer\n Get\n Dim Size As Double = ToUInt32(BlockCopy(Me.HeaderData, 40, 4), 0)\n Dim ByteRate As Double = ToUInt32(BlockCopy(Me.HeaderData, 28, 4), 0)\n Return Ceiling(Size / ByteRate)\n End Get\n End Property\n\n Public Sub Play()\n Try\n My.Computer.Audio.Play(Me.AudioFileReference, AudioPlayMode.Background)\n Catch Exception As Exception\n Throw\n End Try\n End Sub\n\n Public Sub Play(playMode As AudioPlayMode)\n Try\n My.Computer.Audio.Play(Me.AudioFileReference, playMode)\n Catch Exception As Exception\n Throw\n End Try\n End Sub\n\n Private Function Read(AudioFileReference As String, ByVal Offset As Long, ByVal Bytes As Long) As Byte()\n Dim inputFile As System.IO.FileStream\n\n Try\n inputFile = IO.File.Open(AudioFileReference, IO.FileMode.Open)\n Catch Exception As FileNotFoundException\n Throw New FileNotFoundException(\"PCM WAV file not found\")\n Catch Exception As Exception\n Throw\n End Try\n\n Dim BytesRead As Long\n Dim Buffer(Bytes - 1) As Byte\n\n Try\n BytesRead = inputFile.Read(Buffer, Offset, Bytes)\n Catch Exception As Exception\n Throw\n Finally\n Try\n inputFile.Close()\n Catch Exception As Exception\n 'Eat the second exception so as to not mask the previous exception\n End Try\n End Try\n\n If BytesRead < Bytes Then\n Throw New InvalidDataException(\"PCM WAV file read failed\")\n End If\n\n Return Buffer\n End Function\n\n Private Function BlockCopy(ByRef Source As Byte(), ByVal Offset As Long, ByVal Bytes As Long) As Byte()\n Dim Destination(Bytes - 1) As Byte\n\n Try\n Buffer.BlockCopy(Source, Offset, Destination, 0, Bytes)\n Catch Exception As Exception\n Throw\n End Try\n\n Return Destination\n End Function\nEnd Class\n" }, { "answer_id": 21500321, "author": "Aleks", "author_id": 3258422, "author_profile": "https://Stackoverflow.com/users/3258422", "pm_score": 2, "selected": false, "text": " string path = @\"c:\\test.wav\";\n WaveReader wr = new WaveReader(File.OpenRead(path));\n int durationInMS = wr.GetDurationInMS();\n wr.Close();\n" }, { "answer_id": 40933199, "author": "Manish Nayak", "author_id": 4732757, "author_profile": "https://Stackoverflow.com/users/4732757", "pm_score": 3, "selected": false, "text": "using TagLib.Mpeg;\n\npublic static double GetSoundLength(string FilePath)\n{\n AudioFile ObjAF = new AudioFile(FilePath);\n return ObjAF.Properties.Duration.TotalSeconds;\n}\n" }, { "answer_id": 54192641, "author": "item.wu", "author_id": 10915057, "author_profile": "https://Stackoverflow.com/users/10915057", "pm_score": 2, "selected": false, "text": " public static class SoundInfo\n {\n [DllImport(\"winmm.dll\")]\n private static extern uint mciSendString\n (\n string command,\n StringBuilder returnValue,\n int returnLength,\n IntPtr winHandle\n );\n\n public static int GetSoundLength(string fileName)\n {\n StringBuilder lengthBuf = new StringBuilder(32);\n\n mciSendString(string.Format(\"open \\\"{0}\\\" type waveaudio alias wave\", fileName), null, 0, IntPtr.Zero);\n mciSendString(\"status wave length\", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);\n mciSendString(\"close wave\", null, 0, IntPtr.Zero);\n\n int length = 0;\n int.TryParse(lengthBuf.ToString(), out length);\n\n return length;\n }\n}\n public static int GetSoundLength(string fileName)\n {\n using (WaveFileReader wf = new WaveFileReader(fileName))\n {\n return (int)wf.TotalTime.TotalMilliseconds;\n }\n }`\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078/" ]
82,323
<p>I have a 3 column grid in a window with a GridSplitter on the first column. I want to set the MaxWidth of the first column to a third of the parent Window or Page <code>Width</code> (or <code>ActualWidth</code>) and I would prefer to do this in XAML if possible.</p> <p>This is some sample XAML to play with in XamlPad (or similar) which shows what I'm doing. </p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" &gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition x:Name="Column1" Width="200"/&gt; &lt;ColumnDefinition x:Name="Column2" MinWidth="50" /&gt; &lt;ColumnDefinition x:Name="Column3" Width="{ Binding ElementName=Column1, Path=Width }"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Label Grid.Column="0" Background="Green" /&gt; &lt;GridSplitter Grid.Column="0" Width="5" /&gt; &lt;Label Grid.Column="1" Background="Yellow" /&gt; &lt;Label Grid.Column="2" Background="Red" /&gt; &lt;/Grid&gt; &lt;/Page&gt; </code></pre> <p>As you can see, the right column width is bound to the width of the first column, so when you slide the left column using the splitter, the right column does the same :) If you slide the left column to the right, eventually it will slide over half the page/window and over to the right side of the window, pushing away column 2 and 3. </p> <p>I want to prevent this by setting the MaxWidth of column 1 to a third of the window width (or something like that). I can do this in code behind quite easily, but how to do it in "XAML Only"?</p> <p><strong><em>EDIT:</strong> David Schmitt suggested to use SharedSizeGroup instead of binding, which is an excellent suggestion. My sample code would look like this then:</em></p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" &gt; &lt;Grid IsSharedSizeScope="True"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition x:Name="Column1" SharedSizeGroup="ColWidth" Width="40"/&gt; &lt;ColumnDefinition x:Name="Column2" MinWidth="50" Width="*" /&gt; &lt;ColumnDefinition x:Name="Column3" SharedSizeGroup="ColWidth"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Label Grid.Column="0" Background="Green" /&gt; &lt;GridSplitter Grid.Column="0" Width="5" /&gt; &lt;Label Grid.Column="1" Background="Yellow" /&gt; &lt;Label Grid.Column="2" Background="Red" /&gt; &lt;/Grid&gt; &lt;/Page&gt; </code></pre>
[ { "answer_id": 85173, "author": "Thomas", "author_id": 9970, "author_profile": "https://Stackoverflow.com/users/9970", "pm_score": 0, "selected": false, "text": "//I know I borrowed this from someone, sorry I forgot to add a comment from whom\npublic class ScaledValueConverter : IValueConverter\n{\n public Object Convert(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)\n {\n Double scalingFactor = 0;\n if (parameter != null)\n {\n Double.TryParse((String)(parameter), out scalingFactor);\n }\n\n if (scalingFactor == 0.0d)\n {\n return Double.NaN;\n }\n\n return (Double)value * scalingFactor;\n }\n\n public Object ConvertBack(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)\n {\n throw new Exception(\"The method or operation is not implemented.\");\n }\n}\n" }, { "answer_id": 157780, "author": "Christopher Bennage", "author_id": 6855, "author_profile": "https://Stackoverflow.com/users/6855", "pm_score": 4, "selected": true, "text": "<Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:sys=\"clr-namespace:System;assembly=mscorlib\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" >\n\n <!-- This contains our real grid, and a reference grid for binding the layout-->\n <Grid x:Name=\"Container\">\n\n <!-- hidden because it's behind the grid below -->\n <Grid x:Name=\"LayoutReference\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"*\"/>\n </Grid.ColumnDefinitions>\n <!-- We need the border, because the column doesn't have an ActualWidth -->\n <Border x:Name=\"ReferenceBorder\" \n Background=\"Black\" />\n <Border Background=\"White\" Grid.Column=\"1\" />\n <Border Background=\"Black\" Grid.Column=\"2\" />\n </Grid>\n\n <!-- I made this transparent, so we can see the reference -->\n <Grid Opacity=\"0.9\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition x:Name=\"Column1\" \n MaxWidth=\"{Binding ElementName=ReferenceBorder,Path=ActualWidth}\"/>\n <ColumnDefinition x:Name=\"Column2\" \n MinWidth=\"50\" />\n <ColumnDefinition x:Name=\"Column3\" \n Width=\"{ Binding ElementName=Column1, Path=Width }\"/>\n </Grid.ColumnDefinitions>\n\n <Label Grid.Column=\"0\" Background=\"Green\"/>\n <GridSplitter Grid.Column=\"0\" Width=\"5\" />\n <Label Grid.Column=\"1\" Background=\"Yellow\" />\n <Label Grid.Column=\"2\" Background=\"Red\" />\n </Grid>\n </Grid>\n\n</Page>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415/" ]
82,332
<p>I am using C# to process a message in my Outlook inbox that contains attachments. One of the attachments is of type olEmbeddeditem. I need to be able to process the contents of that attachment. From what I can tell I need to save the attachment to disk and use CreateItemFromTemplate which would return an object. </p> <p>The issue I have is that an olEmbeddeditem can be any of the Outlook object types MailItem, ContactItem, MeetingItem, etc. How do you know which object type a particular olEmbeddeditem attachment is going to be so that you know the object that will be returned by CreateItemFromTemplate?</p> <p>Alternatively, if there is a better way to get olEmbeddeditem attachment contents into an object for processing I'd be open to that too.</p>
[ { "answer_id": 96403, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Type t = SomeOutlookObject.GetType();\nstring messageClass = t.InvokeMember(\"MessageClass\",\n BindingFlags.Public | \n BindingFlags.GetField | \n BindingFlags.GetProperty,\n null,\n SomeOutlookObject,\n new object[]{}).ToString();\nConsole.WriteLine(\"\\tType: \" + messageClass);\n" }, { "answer_id": 13089961, "author": "Duane Wright", "author_id": 1759318, "author_profile": "https://Stackoverflow.com/users/1759318", "pm_score": 0, "selected": false, "text": "Outlook.Application mailApplication = new Outlook.Application();\nOutlook.NameSpace mailNameSpace = mailApplication.GetNamespace(“mapi”);\n// make sure it is an embedded item\nIf(myAttachment.Type == Outlook.OlAttachmentType.olEmbeddeditem)\n{\n myAttachment.Type.SaveAsFile(“temp.msg”);\n Outlook.MailItem attachedEmail = (Outlook.MailItem)mailNameSpace.OpenSharedItem(“temp.msg”);\n String customProperty = attachedEmail.PropertyAccessor.GetProperty(\n “http://schemas.microsoft.com/mapi/string/{00020329-0000-0000-c000-000000000046}/myProp\n}\n Outlook.MailItem attachedEmail = (Outlook.MailItem)mailApplication.CreateFromTemplate(“temp.msg”); \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8391/" ]
82,349
<p>It seems like the methods of Ruby's Net::HTTP are all or nothing when it comes to reading the body of a web page. How can I read, say, the just the first 100 bytes of the body? </p> <p>I am trying to read from a content server that returns a short error message in the body of the response if the file requested isn't available. I need to read enough of the body to determine whether the file is there. The files are huge, so I don't want to get the whole body just to check if the file is available.</p>
[ { "answer_id": 82579, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "HTTPResponse HTTPClientError HTTPNotFound Net::HTTP.value()" }, { "answer_id": 82663, "author": "Nathan de Vries", "author_id": 11109, "author_profile": "https://Stackoverflow.com/users/11109", "pm_score": 2, "selected": false, "text": "Net::HTTPResponse#read_body http.request_get('/large_resource') do |response|\n response.read_body do |segment|\n print segment\n end\nend\n" }, { "answer_id": 82711, "author": "Ian Dickinson", "author_id": 6716, "author_profile": "https://Stackoverflow.com/users/6716", "pm_score": 4, "selected": false, "text": "HEAD Net::HTTP::Head content-length content-range" }, { "answer_id": 84008, "author": "Roman", "author_id": 12695, "author_profile": "https://Stackoverflow.com/users/12695", "pm_score": 2, "selected": false, "text": "Net::HTTP#read_body Net::HTTP#read_body_0 read_body_0" }, { "answer_id": 8597488, "author": "Dustin Frazier", "author_id": 1072414, "author_profile": "https://Stackoverflow.com/users/1072414", "pm_score": 4, "selected": false, "text": "require 'net/http'\n\n# provide access to the actual socket\nclass Net::HTTPResponse\n attr_reader :socket\nend\n\nuri = URI(\"http://www.example.com/path/to/file\")\nbegin\n Net::HTTP.start(uri.host, uri.port) do |http|\n request = Net::HTTP::Get.new(uri.request_uri)\n # calling request with a block prevents body from being read\n http.request(request) do |response|\n # do whatever limited reading you want to do with the socket\n x = response.socket.read(100);\n # be sure to call finish before exiting the block\n http.finish\n end\n end\nrescue IOError\n # ignore\nend\n HTTPResponse IO BufferedIO IO readchar class Net::BufferedIO\n def readchar\n read(1)[0].ord\n end\nend\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3298/" ]
82,359
<p>I've just inherited some old Struts code.</p> <p>If Struts (1.3) follows the MVC pattern, how do the Action classes fill the View with variables to render in HTML ?</p> <p>So far, I've seen the Action classes push variables in <code>(1)</code> the HTTP request with</p> <pre><code>request.setAttribute("name", user.getName()) </code></pre> <p><code>(2)</code> in ActionForm classes, using methods specific to the application:</p> <pre><code>UserForm form = (UserForm) actionForm; form.setUserName(user.getName()); </code></pre> <p>and <code>(3)</code> a requestScope variable, that I see in the JSP layer (the view uses JSP), but I can't see in the Action classes.</p> <pre><code>&lt;p style='color: red'&gt;&lt;c:out value='${requestScope.userName}' /&gt;&lt;/p&gt; </code></pre> <p>So, which of these is considered old-school, and what's the recommended way of pushing variables in the View in Struts ?</p>
[ { "answer_id": 82517, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 1, "selected": true, "text": "Struts 1.3" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649/" ]
82,365
<p>I'm using the ProgressBar control in a WPF application and I'm getting this old, Windows 3.1 Progress<em>Blocks</em> thing. In VB6, there was a property to show a <em>smooth</em> ProgressBar. Is there such a thing for WPF?</p>
[ { "answer_id": 1048269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " Enum appThemes\n Aero\n Luna\n LunaMettalic\n LunaHomestead\n Royale\n End Enum\n\nPrivate Sub Application_Startup(ByVal sender As Object, ByVal e As System.Windows.StartupEventArgs) Handles Me.Startup\n\n setTheme(appThemes.Aero)\n\n End Sub\n\n ''' <summary>\n ''' Function to set the default theme of this application\n ''' </summary>\n ''' <param name=\"Theme\">\n ''' Theme of type appThemes\n ''' </param>\n ''' <remarks></remarks>\n Public Sub setTheme(ByVal Theme As appThemes)\n\n Dim uri As Uri\n\n Select Case Theme\n Case appThemes.Aero\n ' Vista Aero Theme\n uri = New Uri(\"PresentationFramework.Aero;V3.0.0.0;31bf3856ad364e35;component\\\\themes/Aero.NormalColor.xaml\", UriKind.Relative)\n\n Case appThemes.Luna\n ' Luna Theme\n uri = New Uri(\"PresentationFramework.Luna;V3.0.0.0;31bf3856ad364e35;component\\\\themes/Luna.NormalColor.xaml\", UriKind.Relative)\n\n Case appThemes.LunaHomestead\n ' Luna Mettalic\n uri = New Uri(\"PresentationFramework.Luna;V3.0.0.0;31bf3856ad364e35;component\\\\themes/Luna.Metallic.xaml\", UriKind.Relative)\n\n Case appThemes.LunaMettalic\n ' Luna Homestead\n uri = New Uri(\"PresentationFramework.Luna;V3.0.0.0;31bf3856ad364e35;component\\\\themes/Luna.Homestead.xaml\", UriKind.Relative)\n\n Case appThemes.Royale\n ' Royale Theme\n uri = New Uri(\"PresentationFramework.Royale;V3.0.0.0;31bf3856ad364e35;component\\\\themes/Royale.NormalColor.xaml\", UriKind.Relative)\n\n End Select\n\n ' Set the Theme\n Resources.MergedDictionaries.Add(Application.LoadComponent(uri))\n\n End Sub\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
82,380
<p>I need to do a multilingual website, with urls like</p> <pre><code>www.domain.com/en/home.aspx for english www.domain.com/es/home.aspx for spanish </code></pre> <p>In the past, I would set up two virtual directories in IIS, and then detect the URL in global.aspx and change the language according to the URL</p> <pre><code>Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) Dim lang As String If HttpContext.Current.Request.Path.Contains("/en/") Then lang = "en" Else lang = "es" End If Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang) End Sub </code></pre> <p>The solution is more like a hack. I'm thinking about using Routing for a new website. </p> <p><strong>Do you know a better or more elegant way to do it?</strong></p> <p>edit: The question is about the URL handling, not about resources, etc.</p>
[ { "answer_id": 87156, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 4, "selected": true, "text": "Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)\n ' Code that runs on application startup\n RegisterRoutes(RouteTable.Routes)\nEnd Sub\n\n\nPublic Sub RegisterRoutes(ByVal routes As RouteCollection)\n Dim reportRoute As Route\n Dim DefaultLang As String = \"es\"\n\n reportRoute = New Route(\"{lang}/{page}\", New LangRouteHandler)\n '* if you want, you can contrain the values\n 'reportRoute.Constraints = New RouteValueDictionary(New With {.lang = \"[a-z]{2}\"})\n reportRoute.Defaults = New RouteValueDictionary(New With {.lang = DefaultLang, .page = \"home\"})\n\n routes.Add(reportRoute)\nEnd Sub\n Public Class LangRouteHandler\n Implements IRouteHandler\n\n Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler _\n Implements System.Web.Routing.IRouteHandler.GetHttpHandler\n\n 'Fill the context with the route data, just in case some page needs it\n For Each value In requestContext.RouteData.Values\n HttpContext.Current.Items(value.Key) = value.Value\n Next\n\n Dim VirtualPath As String\n VirtualPath = \"~/\" + requestContext.RouteData.Values(\"page\") + \".aspx\"\n\n Dim redirectPage As IHttpHandler\n redirectPage = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, GetType(Page))\n Return redirectPage\n\n End Function\nEnd Class\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)\n Dim DefaultLang As String = \"es\"\n Dim SupportedLangs As String() = {\"en\", \"es\"}\n Dim BrowserLang As String = Mid(Request.UserLanguages(0).ToString(), 1, 2).ToLower\n If SupportedLangs.Contains(BrowserLang) Then DefaultLang = BrowserLang\n\n Response.Redirect(DefaultLang + \"/\")\nEnd Sub\n" }, { "answer_id": 186773, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "CultureInfo.CurrentUICulture\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ]
82,391
<p>It is advisable to use tables in HTML pages (now that we have CSS)?</p> <p>What are the applications of tables? What features/abilities does tables have that are not in CSS?</p> <h1>Related Questions</h1> <ul> <li><a href="https://stackoverflow.com/questions/30251/tables-instead-of-divs">Tables instead of DIVs</a></li> <li><a href="https://stackoverflow.com/questions/83073/div-vs-table">DIV vs TABLE</a> <ul> <li><a href="https://stackoverflow.com/questions/96137/divs-vs-tables-a-rebuttal-please">DIVs vs. TABLEs a rebuttal please</a></li> </ul> </li> </ul>
[ { "answer_id": 82422, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "<TABLE> <DIV> <SPAN>" }, { "answer_id": 82487, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "table" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
82,398
<p>How would one go about spotting URIs in a block of text?</p> <p>The idea is to turn such runs of texts into links. This is pretty simple to do if one only considered the http(s) and ftp(s) schemes; however, I am guessing the general problem (considering tel, mailto and other URI schemes) is much more complicated (if it is even possible).</p> <p>I would prefer a solution in C# if possible. Thank you.</p>
[ { "answer_id": 82546, "author": "Victor", "author_id": 14514, "author_profile": "https://Stackoverflow.com/users/14514", "pm_score": 0, "selected": false, "text": "(http|https|ftp|mailto|tel):\\S+[/a-zA-Z0-9]\n" }, { "answer_id": 82618, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": -1, "selected": false, "text": "/\\w+:\\/\\/[\\w][\\w\\.\\/]*/\n" }, { "answer_id": 83378, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 3, "selected": false, "text": "\\w+:\\/{2}[\\d\\w-]+(\\.[\\d\\w-]+)*(?:(?:\\/[^\\s/]*))* http://example.com/foo/bar-baz ftp://192.168.0.1/foo/file.txt mailto:[email protected] // @ ftp://192.168.0.1.2 ftp://1000.120.0.1 nonexistantscheme://obvious.false.positive http://www.google.com/search?q=uri+regular+expression \\s(\\w:\\S+)\\s" }, { "answer_id": 87917, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 0, "selected": false, "text": "findURLs: function(text) {\n var urls = [];\n var matches = text.match(/(\\S+\\.{1}[^\\s\\,\\.\\!]+)/g);\n if (matches) {\n for each (var match in matches) {\n urls.push(match);\n }\n }\n return urls;\n},\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
82,404
<p>Given the problem that a stored procedure on SQL Server 2005, which is looping through a cursor, must be run once an hour and it takes about 5 minutes to run, but it takes up a large chunk of processor time:</p> <p>edit: I'd remove the cursor if I could, unfortunatly, I have to be doing a bunch of processing and running other stored procs/queries based on the row.</p> <p>Can I use WAITFOR DELAY '0:0:0.1' before each fetch to act as SQL's version of .Net's Thread.Sleep? Thus allowing the other processes to complete faster at the cost of this procedure's execution time.</p> <p>Or is there another solution I'm not seeing?</p> <p>Thanks</p>
[ { "answer_id": 83229, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "declare @minid int, @maxid int, @somevalue int \nselect @minid = 1, @maxid = 5\nwhile @minid <= @maxid\nbegin\n set @somevalue = null\n select @somevalue = somefield from sometable where id = @minid\n print @somevalue\n set @minid = @minid + 1\n waitfor delay '00:00:00.1'\nend\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9610/" ]
82,409
<p>If I have a table in my database called 'Users', there will be a class generated by LINQtoSQL called 'User' with an already declared empty constructor.</p> <p>What is the best practice if I want to override this constructor and add my own logic to it?</p>
[ { "answer_id": 82470, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 2, "selected": false, "text": "// Add new partial class to extend functionality\npublic partial class User {\n\n // Add additional constructor\n public User(int id) {\n ID = id;\n }\n\n // Add static method to initialize new object\n public User GetNewUser() {\n // functionality\n User user = new User();\n user.Name = \"NewName\";\n return user;\n }\n}\n User user1 = new User(1);\nUser user2 = User.GetNewUser();\n" }, { "answer_id": 83844, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 5, "selected": true, "text": "OnCreated OnCreated MyDataClasses.cs partial void OnCreated()\n{\n Name = \"\";\n}\n" }, { "answer_id": 22935888, "author": "Baga", "author_id": 2742356, "author_profile": "https://Stackoverflow.com/users/2742356", "pm_score": 1, "selected": false, "text": "Partial Class MyDataContext \n Public Sub New() \n MyBase.New(ConfigurationManager.ConnectionStrings(\"MyConnectionString\").ConnectionString, mappingSource)\n OnCreated() \n End Sub \nEnd Class\n" }, { "answer_id": 51161554, "author": "CoolBreeze", "author_id": 1303233, "author_profile": "https://Stackoverflow.com/users/1303233", "pm_score": 0, "selected": false, "text": "public partial class PENCILS_LinqToSql_DataClassesDataContext\n{\n public PENCILS_LinqToSql_DataClassesDataContext() : base(ConnectionString(), mappingSource)\n {\n }\n\n public static String ConnectionString()\n {\n String CS;\n String Key;\n\n Key = System.Configuration.ConfigurationManager.AppSettings[\"DefaultConnectionString\"].ToString();\n\n /// Get the actual connection string.\n CS = System.Configuration.ConfigurationManager.ConnectionStrings[Key].ToString();\n\n return CS;\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15717/" ]
82,417
<p>Is it possible to hide or exclude certain data from a report if it's being rendered in a particular format (csv, xml, excel, pdf, html). The problem is that I want hyperlinks to other reports to not be rendered when the report is generated in Excel format - but they should be there when the report is rendered in HTML format.</p>
[ { "answer_id": 86991, "author": "Liron Yahdav", "author_id": 62, "author_profile": "https://Stackoverflow.com/users/62", "pm_score": 3, "selected": true, "text": "ReportViewer1.ServerReport.SetParameters(New ReportParameter() {New ReportParameter(\"ExportView\", \"True\")})\nReportViewer1.ServerReport.Refresh()\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15428/" ]
82,429
<p>My understanding of Hibernate is that as objects are loaded from the DB they are added to the Session. At various points, depending on your configuration, the session is flushed. At this point, modified objects are written to the database.</p> <p>How does Hibernate decide which objects are 'dirty' and need to be written?</p> <p>Do the proxies generated by Hibernate intercept assignments to fields, and add the object to a dirty list in the Session?</p> <p>Or does Hibernate look at each object in the Session and compare it with the objects original state?</p> <p>Or something completely different?</p>
[ { "answer_id": 82946, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 6, "selected": true, "text": "org.hibernate.engine.EntityEntry.requiresDirtyCheck() SessionImpl.flush() onFlush() SessionImpl.list() autoFlushIfRequired() onAutoFlush() AbstractFlushingEventListener.flushEverythingToExecutions() flushEntities() source.getPersistenceContext().getEntityEntries() DefaultFlushEntityEventListener.onFlushEntity() dirtyCheck()" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11002/" ]
82,431
<p>Is there a detailed guide which explains how to host a website on your own server on linux. I have currently hosted it on one of the commerical web-hosts. Also the domain is registered to a different vendor.</p> <p>Thanks</p>
[ { "answer_id": 82486, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 1, "selected": false, "text": "sudo apt-get install apache2\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396527/" ]
82,437
<p>Why is the following C# code not allowed:</p> <pre><code>public abstract class BaseClass { public abstract int Bar { get;} } public class ConcreteClass : BaseClass { public override int Bar { get { return 0; } set {} } } </code></pre> <blockquote> <p>CS0546 'ConcreteClass.Bar.set': cannot override because 'BaseClass.Bar' does not have an overridable set accessor</p> </blockquote>
[ { "answer_id": 82473, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": true, "text": "public class BarProvider\n{ BaseClass _source;\n Bar _currentBar;\n\n public void setSource(BaseClass b)\n {\n _source = b;\n _currentBar = b.Bar;\n }\n\n public Bar getBar()\n { return _currentBar; }\n}\n" }, { "answer_id": 82649, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "public new int Bar \n{ \n get { return 0; }\n set {} \n}\n\nint IBase.Bar { \n get { return Bar; }\n}\n" }, { "answer_id": 107900, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 2, "selected": false, "text": "public class ConcreteClass : BaseClass\n{\n public override int Bar\n {\n get;\n private set;\n }\n}\n" }, { "answer_id": 2571197, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 5, "selected": false, "text": "public override int MyProperty { get { ... } set { ... } }\n get set set public int MyProperty\n{\n override get { ... } // not valid C#\n set { ... }\n}\n public int MyProperty { override get; set; } // not valid C#\n" }, { "answer_id": 3538759, "author": "mbolt35", "author_id": 427137, "author_profile": "https://Stackoverflow.com/users/427137", "pm_score": -1, "selected": false, "text": "namespace {\n public class Base {\n private int _baseProperty = 0;\n\n public virtual int BaseProperty {\n get {\n return _baseProperty;\n }\n }\n\n }\n\n public class Test : Base {\n private int _testBaseProperty = 5;\n\n public new int BaseProperty {\n get {\n return _testBaseProperty;\n }\n set {\n _testBaseProperty = value;\n }\n }\n }\n}\n" }, { "answer_id": 3678456, "author": "JJJ", "author_id": 5547, "author_profile": "https://Stackoverflow.com/users/5547", "pm_score": 4, "selected": false, "text": "interface ITest\n{\n // Other stuff\n string Prop { get; }\n}\n\n// Implements other stuff\nabstract class ATest : ITest\n{\n abstract public string Prop { get; }\n}\n\n// This implementation of ITest needs the user to set the value of Prop\nclass BTest : ATest\n{\n string foo = \"BTest\";\n public override string Prop\n {\n get { return foo; }\n set { foo = value; } // Not allowed. 'BTest.Prop.set': cannot override because 'ATest.Prop' does not have an overridable set accessor\n }\n}\n\n// This implementation of ITest generates the value for Prop itself\nclass CTest : ATest\n{\n string foo = \"CTest\";\n public override string Prop\n {\n get { return foo; }\n // set; // Not needed\n }\n}\n" }, { "answer_id": 12414581, "author": "T.Tobler", "author_id": 1669770, "author_profile": "https://Stackoverflow.com/users/1669770", "pm_score": 4, "selected": false, "text": " class BaseType\n {\n public virtual T LastRequest { get {...} }\n }\n\n class DerivedTypeStrategy1\n {\n /// get or set the value returned by the LastRequest property.\n public bool T LastRequestValue { get; set; }\n\n public override T LastRequest { get { return LastRequestValue; } }\n }\n\n class DerivedTypeStrategy2\n {\n /// set the value returned by the LastRequest property.\n public bool SetLastRequest( T value ) { this._x = value; }\n\n public override T LastRequest { get { return _x; } }\n\n private bool _x;\n }\n" }, { "answer_id": 17267865, "author": "user2514880", "author_id": 2514880, "author_profile": "https://Stackoverflow.com/users/2514880", "pm_score": 0, "selected": false, "text": "var UpdatedGiftItem = // object value to update;\n\nforeach (var proInfo in UpdatedGiftItem.GetType().GetProperties())\n{\n var updatedValue = proInfo.GetValue(UpdatedGiftItem, null);\n var targetpropInfo = this.GiftItem.GetType().GetProperty(proInfo.Name);\n targetpropInfo.SetValue(this.GiftItem, updatedValue,null);\n}\n" }, { "answer_id": 22210422, "author": "Nat", "author_id": 1755715, "author_profile": "https://Stackoverflow.com/users/1755715", "pm_score": 5, "selected": false, "text": "new get set override get get get set get set public abstract class A // Pre-existing class; can't modify\n{\n public abstract int X { get; } // You want a setter, but can't add it.\n}\npublic class B : A // Pre-existing class; can't modify\n{\n public override int X { get { return 0; } }\n}\n override get get set override get set public class C : B\n{\n private int _x;\n public override int X\n {\n get { return _x; }\n set { _x = value; } // Won't compile\n }\n}\n abstract override get set new get set override get get abstract public abstract class C : B\n{\n // Seal off the old getter. From now on, its only job\n // is to alias the new getter in the base classes.\n public sealed override int X { get { return this.XGetter; } }\n protected abstract int XGetter { get; }\n}\n override get new public class D : C\n{\n private int _x;\n public new virtual int X\n {\n get { return this._x; }\n set { this._x = value; }\n }\n\n // Ensure base classes (A,B,C) use the new get method.\n protected sealed override int XGetter { get { return this.X; } }\n}\n var d = new D();\n\nvar a = d as A;\nvar b = d as B;\nvar c = d as C;\n\nPrint(a.X); // Prints \"0\", the default value of an int.\nPrint(b.X); // Prints \"0\", the default value of an int.\nPrint(c.X); // Prints \"0\", the default value of an int.\nPrint(d.X); // Prints \"0\", the default value of an int.\n\n// a.X = 7; // Won't compile: A.X doesn't have a setter.\n// b.X = 7; // Won't compile: B.X doesn't have a setter.\n// c.X = 7; // Won't compile: C.X doesn't have a setter.\nd.X = 7; // Compiles, because D.X does have a setter.\n\nPrint(a.X); // Prints \"7\", because 7 was set through D.X.\nPrint(b.X); // Prints \"7\", because 7 was set through D.X.\nPrint(c.X); // Prints \"7\", because 7 was set through D.X.\nPrint(d.X); // Prints \"7\", because 7 was set through D.X.\n set get get set get set abstract class get set get set set get" }, { "answer_id": 33289850, "author": "Suamere", "author_id": 1831054, "author_profile": "https://Stackoverflow.com/users/1831054", "pm_score": 0, "selected": false, "text": "public int GetBar(){}\n public abstract class BaseClass\n{\n public abstract int Bar { get; }\n}\n\npublic class ConcreteClass : BaseClass\n{\n private int _bar;\n public override int Bar\n {\n get { return _bar; }\n }\n public void SetBar(int value)\n {\n _bar = value;\n }\n}\n public abstract class BaseClass {\n protected int _bar;\n public int Bar { get { return _bar; } }\n protected void DoBaseStuff()\n {\n SetBar();\n //Do something with _bar;\n }\n protected abstract void SetBar();\n}\n\npublic class ConcreteClass : BaseClass {\n protected override void SetBar() { _bar = 5; }\n}\n {get;} public abstract class BaseClass\n{\n public int Bar { get; }\n}\n public abstract class BaseClass\n{\n private int _bar;\n public int Bar { \n get{\n return _bar;\n }}\n public void SetBar(int value) { _bar = value; }\n}\n public abstract class BaseClass\n{\n private int _foo;\n private int _baz;\n private int _wtf;\n private int _kthx;\n private int _lawl;\n\n public int Bar\n {\n get { return _foo * _baz + _kthx; }\n }\n public bool TryDoSomethingBaz(MyEnum whatever, int input)\n {\n switch (whatever)\n {\n case MyEnum.lol:\n _baz = _lawl + input;\n return true;\n case MyEnum.wtf:\n _baz = _wtf * input;\n break;\n }\n return false;\n }\n public void TryBlowThingsUp(DateTime when)\n {\n //Some Crazy Madeup Code\n _kthx = DaysSinceEaster(when);\n }\n public int DaysSinceEaster(DateTime when)\n {\n return 2; //<-- calculations\n }\n}\npublic enum MyEnum\n{\n lol,\n wtf,\n}\n int Bar" }, { "answer_id": 46651924, "author": "lxa", "author_id": 167195, "author_profile": "https://Stackoverflow.com/users/167195", "pm_score": 0, "selected": false, "text": "public abstract class BaseClass\n{\n public abstract int Bar { get; }\n}\n\npublic class ConcreteClass : BaseClass\n{\n public override int Bar { get; }\n\n public ConcreteClass(int bar)\n {\n Bar = bar;\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
82,442
<p>Inspired by the MVC storefront the latest project I'm working on is using extension methods on IQueryable to filter results.</p> <p>I have this interface;</p> <pre><code>IPrimaryKey { int ID { get; } } </code></pre> <p>and I have this extension method</p> <pre><code>public static IPrimaryKey GetByID(this IQueryable&lt;IPrimaryKey&gt; source, int id) { return source(obj =&gt; obj.ID == id); } </code></pre> <p>Let's say I have a class, SimpleObj which implements IPrimaryKey. When I have an IQueryable of SimpleObj the GetByID method doesn't exist, unless I explicitally cast as an IQueryable of IPrimaryKey, which is less than ideal.</p> <p>Am I missing something here?</p>
[ { "answer_id": 85461, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "public interface IPrimaryKey<T> where T : IPrimaryKey<T>\n{\n int Id { get; }\n}\n\npublic static class IPrimaryKeyTExtension\n{\n public static IPrimaryKey<T> GetById<T>(this IQueryable<T> source, int id) where T : IPrimaryKey<T>\n {\n return source.Where(pk => pk.Id == id).SingleOrDefault();\n }\n}\n\npublic class Person : IPrimaryKey<Person>\n{\n public int Id { get; set; }\n}\n var people = new List<Person>\n{\n new Person { Id = 1 },\n new Person { Id = 2 },\n new Person { Id = 3 }\n};\n\nvar personOne = people.AsQueryable().GetById(1);\n" }, { "answer_id": 85503, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "IPrimaryKey public static IPrimaryKey GetByID<T>(this IQueryable<T> source, int id) where T : IPrimaryKey\n{\n return source(obj => obj.ID == id);\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691/" ]
82,454
<p>Here's one from the "No question's too dumb" department:</p> <p>Well, as the subject says: Is there an impact? If so, how much? Will all the string literals I have in my code and in my DFM resources now take up twice as much space inside the compiled binaries? What about runtime memory usage of compiled applications? Will all the string variables now take up twice as much RAM? Should I even bother?</p> <p>I remember something like this being asked during one of the early pre-release webcasts but I can't remember the answer. And as the trial is only 14 days I'm not going to just try it myself before the third-party libraries I need have been updated (supposedly in about a month).</p>
[ { "answer_id": 345608, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 0, "selected": false, "text": "{$STRINGCHECKS}" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9784/" ]
82,468
<p>How can I figure out the state of the files in my client, I want to know if the file needs an updated, or patched, or modified etc. In CVS, I used to simply run "cvs -n -q update . > file". Later look for M,U,P,C attributes to get the current status of the file.</p> <p>In perforce, "p4 sync -n" doesn't give output like "cvs -n -q update". How can I see the current status of files, in case of Perforce?</p>
[ { "answer_id": 82684, "author": "tenpn", "author_id": 11801, "author_profile": "https://Stackoverflow.com/users/11801", "pm_score": 1, "selected": false, "text": "p4 resolve -n\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5794/" ]
82,483
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/219594/net-whats-the-best-way-to-implement-a-catch-all-exceptions-handler">.NET - What’s the best way to implement a “catch all exceptions handler”</a> </p> </blockquote> <p>I have a .NET console app app that is crashing and displaying a message to the user. All of my code is in a <code>try{&lt;code&gt;} catch(Exception e){&lt;stuff&gt;}</code> block, but still errors are occasionally displayed.</p> <p>In a Win32 app, you can capture all possible exceptions/crashes by installing various exception handlers:</p> <pre><code>/* C++ exc handlers */ _set_se_translator SetUnhandledExceptionFilter _set_purecall_handler set_terminate set_unexpected _set_invalid_parameter_handler </code></pre> <p>What is the equivalent in the .NET world so I can handle/log/quiet all possible error cases?</p>
[ { "answer_id": 82536, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 3, "selected": false, "text": "protected void Application_Error(Object sender, EventArgs e)\n" }, { "answer_id": 83745, "author": "Dario Solera", "author_id": 16026, "author_profile": "https://Stackoverflow.com/users/16026", "pm_score": 2, "selected": false, "text": "AppDomain.CurrentDomain.UnhandledException\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442/" ]
82,495
<p>I was checking out Intel's "whatif" site and their Transactional Memory compiler (each thread has to make atomic commits or rollback the system's memory, like a Database would). </p> <p>It seems like a promising way to replace locks and mutexes but I can't find many testimonials. Does anyone here have any input?</p>
[ { "answer_id": 49615143, "author": "Alexander Granin", "author_id": 455610, "author_profile": "https://Stackoverflow.com/users/455610", "pm_score": 2, "selected": false, "text": "STML TVars retry Context Dining Philosophers STML<bool> takeFork(const TVar<Fork>& tFork)\n{\n STML<bool> alreadyTaken = withTVar(tFork, isForkTaken);\n STML<Unit> takenByUs = modifyTVar(tFork, setForkTaken);\n STML<bool> success = sequence(takenByUs, pure(true));\n STML<bool> fail = pure(false);\n STML<bool> result = ifThenElse(alreadyTaken, fail, success);\n return result;\n};\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
82,509
<p>Let's say I want a web page that contains a Flash applet and I'd like to drag and drop some objects from or to the rest of the web page, is this at all possible?</p> <p>Bonus if you know a website somewhere that does that!</p>
[ { "answer_id": 84737, "author": "jessegavin", "author_id": 5651, "author_profile": "https://Stackoverflow.com/users/5651", "pm_score": 2, "selected": false, "text": "import flash.display.Sprite;\nimport flash.external.ExternalInterface;\nimport flash.net.URLLoader;\nimport flash.net.URLRequest;\n\nif (ExternalInterface.available) {\n ExternalInterface.addCallback(\"handleDroppedImage\", myDroppedImageHandler);\n}\n\nprivate function myDroppedImageHandler(url:String, x:Number, y:Number):void {\n\n var container:Sprite = new Sprite();\n container.x = x;\n container.y = y;\n addChild(container);\n\n var loader:Loader = new Loader();\n var request:URLRequest = new URLRequest(url);\n loader.load(request);\n\n container.addChild(loader);\n}\n <html>\n<head>\n <title>XHTML 1.0 Transitional Template</title>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.2/jquery-ui.min.js\"></script>\n <script type=\"text/javascript\">\n $(function() {\n $(\"#dragIcon\").draggable();\n\n $(\"#flash\").droppable({ \n tolerance : \"intersect\",\n drop: function(e,ui) {\n\n // Get the X,Y coords relative to to the flash movie\n var x = $(this).offset().left - ui.draggable.offset().left;\n var y = $(this).offset().top - ui.draggable.offset().top;\n\n // Get the url of the dragged image\n var url = ui.draggable.attr(\"src\");\n\n // Get access to the swf\n var swf = ($.browser.msie) ? document[\"MyFlashMovie\"] : window[\"MyFlashMovie\"];\n\n // Call the ExternalInterface function\n swf.handleDroppedImage(url, x, y);\n\n // remove the swf from the javascript DOM\n ui.draggable.remove();\n }\n });\n });\n </script>\n</head>\n<body>\n\n <img id=\"dragIcon\" width=\"16\" height=\"16\" alt=\"drag me\" />\n\n <div id=\"flash\">\n <object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"\n id=\"MyFlashMovie\" width=\"500\" height=\"375\"\n codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab\">\n <param name=\"movie\" value=\"MyFlashMovie.swf\" />\n <param name=\"quality\" value=\"high\" />\n <param name=\"bgcolor\" value=\"#869ca7\" />\n <param name=\"allowScriptAccess\" value=\"sameDomain\" />\n <embed src=\"MyFlashMovie.swf\" quality=\"high\" bgcolor=\"#869ca7\"\n width=\"500\" height=\"375\" name=\"MyFlashMovie\" align=\"middle\"\n play=\"true\" loop=\"false\" quality=\"high\" allowScriptAccess=\"sameDomain\"\n type=\"application/x-shockwave-flash\"\n pluginspage=\"http://www.macromedia.com/go/getflashplayer\">\n </embed>\n </object>\n </div>\n\n</body>\n</html>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15695/" ]
82,530
<p>I'm on laptop (Ubuntu) with a network that use HTTP proxy (only http connections allowed).<br> When I use svn up for url like 'http://.....' everything is cool (google chrome repository works perfect), but right now I need to svn up from server with 'svn://....' and I see connection refused.<br> I've set proxy configuration in /etc/subversion/servers but it doesn't help.<br> Anyone have opinion/solution?<br></p>
[ { "answer_id": 82587, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "SSHs -L -R 127.0.0.1:3690 svn co svn://127.0.0.1/....\n" }, { "answer_id": 82600, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 7, "selected": true, "text": "/etc/subversion/servers http-proxy-host svn:// svnserve svn+ssh:// connect-tunnel connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690\n svn checkout svn://localhost:10234/path/to/trunk\n" }, { "answer_id": 3789496, "author": "dillera", "author_id": 457556, "author_profile": "https://Stackoverflow.com/users/457556", "pm_score": 6, "selected": false, "text": "$ sudo vi /etc/subversion/servers\n [Global]\nhttp-proxy-host=my.proxy.com\nhttp-proxy-port=3128\n svn" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15752/" ]