qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
236,354
<p>I am a beginner in c++ and I have a small problem:</p> <p>my code displays a simple menu to the user providing three options:</p> <pre><code>cout &lt;&lt; "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout &lt;&lt; "\n &lt;r&gt; Give new coefficients"; cout &lt;&lt; "\n &lt;c&gt; Calculate equations solutions"; cout &lt;&lt; "\n &lt;t&gt; Terminate the program"; </code></pre> <p>What I want is now is that, when a user enters:</p> <ul> <li>aer ->invalid input entered, try again </li> <li>1 or any other number->invalid input entered, try again </li> <li>rt ->invalid input entered,try again (here the first character is correct but he entered 2 characters)</li> <li>cf ->invalid input entered, try again</li> </ul> <p>ONLY IF THE USER ENTERS CORRECTLY ONE OF THE 3 SIMPLE CHARACTERS (r,c,t NONSENSITIVE CASE) to do sth. Otherwise a massage for invalid input should be printed and then the main menu should appear again</p> <p>I tried this but it doesnt work:</p> <pre><code>char displayMainMenu() { char mainMenuChoice; cout &lt;&lt; "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout &lt;&lt; "\n &lt;r&gt; Give new coefficients"; cout &lt;&lt; "\n &lt;c&gt; Calculate equations solutions"; cout &lt;&lt; "\n &lt;t&gt; Terminate the program"; cout&lt;&lt;"Enter choice : "; cin&gt;&gt;mainMenuChoice; return mainMenuChoice; } int main() { bool done = false; while(!done) { char choice = displayMainMenu(); if( isalpha(choice) ) { switch(tolower(choice)) { case 'r': DoSTH1(); break; case 'c': DoSTH2(); break; case 't': DoSTH3(); break; default: cout&lt;&lt;"Invalid choice!\n"&lt;&lt;endl; } } } return 0; } </code></pre> <p>I hope u can help me</p> <p>ADDED: When i enter by mistake for example: cbbbbbb it takes it as if it was 'c'</p>
[ { "answer_id": 236366, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "<p>Change this line:</p>\n\n<pre><code>cout&lt;&lt;\"Enter choice : \" &lt;&lt; std::endl;\n // ^^^^^^^^^^^^^^^\n</code></pre>\n\n<p>This print '\\n' then forces the buffer to flush to the output so it can be read.</p>\n\n<p>If you just want to flush the buffer:</p>\n\n<pre><code>cout&lt;&lt;\"Enter choice : \" &lt;&lt; std::flush;\n</code></pre>\n\n<p>Drop the if statement. It's not needed you do the error checking with the switch.</p>\n\n<pre><code>// if( isalpha(choice) )\n</code></pre>\n" }, { "answer_id": 236369, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": "<p>First, leave out the <code>if( isalpha(choice) )</code>. It is not needed, since any input but <code>r</code>, <code>c</code> or <code>t</code> will fall through to <code>default</code>. </p>\n\n<p>Actually, it may be the cause of your problem. If the character entered is not alphanumeric, the function will end without displaying your error message.</p>\n\n<p>In general my advice is: Don't think too complicated. The beauty of a switch is that you can act on exact matches, and <em>all others</em> will fall through to <code>default</code></p>\n" }, { "answer_id": 236373, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 1, "selected": false, "text": "<p>What does \"I tried this but it doesn't work\" mean? What output are you getting? Do you mean it doesn't compile? (it won't in the state you're showing it). Do you mean that there's more to the program then what we see but it's producing unexpected results? There's not enough for us to debug this. For what it's worth, I didn't see anything wrong (aside from it obviously being incomplete):</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nchar displayMainMenu() {\n char mainMenuChoice;\n cout &lt;&lt; \"\\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: \";\n cout &lt;&lt; \"\\n &lt;r&gt; Give new coefficients\";\n cout &lt;&lt; \"\\n &lt;c&gt; Calculate equations solutions\";\n cout &lt;&lt; \"\\n &lt;t&gt; Terminate the program\";\n cout&lt;&lt;\"\\nEnter choice : \";\n cin&gt;&gt;mainMenuChoice;\n return mainMenuChoice;\n}\n\nint main() {\n bool done = false;\n while(!done) {\n char choice = displayMainMenu();\n\n if( isalpha(choice) ) {\n\n switch(tolower(choice))\n {\n case 'r':\n cout &lt;&lt; \"got 'r'\\n\";\n break;\n case 'c':\n cout &lt;&lt; \"got 'c'\\n\";\n break;\n case 't':\n cout &lt;&lt; \"got 't'\\n\";\n done = true;\n break;\n default:\n cout&lt;&lt;\"Invalid choice!\\n\"&lt;&lt;endl;\n }\n }\n }\n return 0;\n}\n</code></pre>\n\n<p>And the output:</p>\n\n<pre><code>~ $ g++ input.cc -o input\n~ $ ./input\n\nQuadratic equation: a*X^2 + b*X + c = 0 main menu:\n &lt;r&gt; Give new coefficients\n &lt;c&gt; Calculate equations solutions\n &lt;t&gt; Terminate the program\nEnter choice : a\nInvalid choice!\n\n\nQuadratic equation: a*X^2 + b*X + c = 0 main menu:\n &lt;r&gt; Give new coefficients\n &lt;c&gt; Calculate equations solutions\n &lt;t&gt; Terminate the program\nEnter choice : c\ngot 'c'\n\nQuadratic equation: a*X^2 + b*X + c = 0 main menu:\n &lt;r&gt; Give new coefficients\n &lt;c&gt; Calculate equations solutions\n &lt;t&gt; Terminate the program\nEnter choice : t\ngot 't'\n~ $\n</code></pre>\n\n<p><strong>Update</strong> I see it doesn't give the 'Invalid choice' message for non-numerics, but that can be fixed with removing the 'isalpha' check.</p>\n" }, { "answer_id": 236598, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 2, "selected": false, "text": "<p>To get past the \"cbbb\" being accepted as 'c', you'll have to read in a line using getline() instead. Then you can check that only one character was entered, and then check which character that was.</p>\n\n<p>If you use cin to read a char, it will only read the first character available in the input stream.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am a beginner in c++ and I have a small problem: my code displays a simple menu to the user providing three options: ``` cout << "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout << "\n <r> Give new coefficients"; cout << "\n <c> Calculate equations solutions"; cout << "\n <t> Terminate the program"; ``` What I want is now is that, when a user enters: * aer ->invalid input entered, try again * 1 or any other number->invalid input entered, try again * rt ->invalid input entered,try again (here the first character is correct but he entered 2 characters) * cf ->invalid input entered, try again ONLY IF THE USER ENTERS CORRECTLY ONE OF THE 3 SIMPLE CHARACTERS (r,c,t NONSENSITIVE CASE) to do sth. Otherwise a massage for invalid input should be printed and then the main menu should appear again I tried this but it doesnt work: ``` char displayMainMenu() { char mainMenuChoice; cout << "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout << "\n <r> Give new coefficients"; cout << "\n <c> Calculate equations solutions"; cout << "\n <t> Terminate the program"; cout<<"Enter choice : "; cin>>mainMenuChoice; return mainMenuChoice; } int main() { bool done = false; while(!done) { char choice = displayMainMenu(); if( isalpha(choice) ) { switch(tolower(choice)) { case 'r': DoSTH1(); break; case 'c': DoSTH2(); break; case 't': DoSTH3(); break; default: cout<<"Invalid choice!\n"<<endl; } } } return 0; } ``` I hope u can help me ADDED: When i enter by mistake for example: cbbbbbb it takes it as if it was 'c'
To get past the "cbbb" being accepted as 'c', you'll have to read in a line using getline() instead. Then you can check that only one character was entered, and then check which character that was. If you use cin to read a char, it will only read the first character available in the input stream.
236,359
<p>I know most of the ins and outs of Python's approach to private variables/members/functions/...</p> <p>However, I can't make my mind up on how to distinguish between methods for external use or subclassing use.</p> <p>Consider the following example:</p> <pre><code>class EventMixin(object): def subscribe(self, **kwargs): '''kwargs should be a dict of event -&gt; callable, to be specialized in the subclass''' def event(self, name, *args, **kwargs): ... def _somePrivateMethod(self): ... </code></pre> <p>In this example, I want to make it clear that subscribe is a method to be used by external users of the class/object, while event is a method that should not be called from the outside, but rather by subclass implementations.</p> <p>Right now, I consider both part of the public API, hence don't use any underscores. However, for this particular situation, it would feel cleaner to, for example, use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API. However, that would become unwieldy because then the internal API would need to be invoked as</p> <pre><code>self._EventMixin__somePrivateMethod() </code></pre> <p>So, what are your conventions, coding-wise, documentationwise, or otherwise ?</p>
[ { "answer_id": 236402, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "<pre><code>use no underscores for the external API,\none underscore for the subclassable API,\nand two underscores for the private/internal API\n</code></pre>\n\n<p>This is a reasonable and relatively common way of doing it, yes. The double-underline-for-actually-private (as opposed to ‘protected’ in C++ terms) is in practice pretty rare. You never really know what behaviours a subclass might want to override, so assuming ‘protected’ is generally a good bet unless there's a really good reason why messing with a member might be particularly dangerous.</p>\n\n<pre><code>However, that would become unwieldy because then the internal API would\nneed to be invoked as self._EventMixin__somePrivateMethod()\n</code></pre>\n\n<p>Nope, you can just use the double-underlined version and it will be munged automatically. It's ugly but it works.</p>\n" }, { "answer_id": 236596, "author": "Kozyarchuk", "author_id": 52490, "author_profile": "https://Stackoverflow.com/users/52490", "pm_score": 2, "selected": false, "text": "<p>I generally find using double __ to be more trouble that they are worth, as it makes unit testing very painful. using single _ as convention for methods/attributes that are not intended to be part of the public interface of a particular class/module is my preferred approach. </p>\n" }, { "answer_id": 237976, "author": "mithrandi", "author_id": 31490, "author_profile": "https://Stackoverflow.com/users/31490", "pm_score": 2, "selected": false, "text": "<p>I'd like to make the suggestion that when you find yourself encountering this kind of distinction, it may be a good idea to consider using composition instead of inheritance; in other words, instantiating <code>EventMixin</code> (presumably the name would change) instead of inheriting it.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ]
I know most of the ins and outs of Python's approach to private variables/members/functions/... However, I can't make my mind up on how to distinguish between methods for external use or subclassing use. Consider the following example: ``` class EventMixin(object): def subscribe(self, **kwargs): '''kwargs should be a dict of event -> callable, to be specialized in the subclass''' def event(self, name, *args, **kwargs): ... def _somePrivateMethod(self): ... ``` In this example, I want to make it clear that subscribe is a method to be used by external users of the class/object, while event is a method that should not be called from the outside, but rather by subclass implementations. Right now, I consider both part of the public API, hence don't use any underscores. However, for this particular situation, it would feel cleaner to, for example, use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API. However, that would become unwieldy because then the internal API would need to be invoked as ``` self._EventMixin__somePrivateMethod() ``` So, what are your conventions, coding-wise, documentationwise, or otherwise ?
``` use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API ``` This is a reasonable and relatively common way of doing it, yes. The double-underline-for-actually-private (as opposed to ‘protected’ in C++ terms) is in practice pretty rare. You never really know what behaviours a subclass might want to override, so assuming ‘protected’ is generally a good bet unless there's a really good reason why messing with a member might be particularly dangerous. ``` However, that would become unwieldy because then the internal API would need to be invoked as self._EventMixin__somePrivateMethod() ``` Nope, you can just use the double-underlined version and it will be munged automatically. It's ugly but it works.
236,362
<p>I have a web application that makes heavy use of the Session state to store information about the current user, their personal settings, record their session history and so on. </p> <p>I have found myself retrieving this session information in my business layer, like so:</p> <pre><code>((UserSession)HttpContext.Current.Session["UserSession"]).User.Info </code></pre> <p>This poses a problem - at some point in the future my application will have a Windows client which obviously cannot reference the web Session state. So I need a host or customized session class that I can reference in my business layer that is agnostic of whether the application is running on the web or desktop. Something like:</p> <pre><code>IHost.User.Info </code></pre> <p>Behind the scenes, the web implementation will obviously utilize the Session state to store information, but I need to hide this away from my business layer. Has anyone solved this problem or got any practival advice on how best to approach this?</p> <p>Help appreciated. </p>
[ { "answer_id": 236377, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": -1, "selected": false, "text": "<p>I guess you need to create a webservice or RESTfull service. The service will return an XML file representing your user information. You will be able to invoke the service wither from you windows or web application. </p>\n" }, { "answer_id": 236454, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": true, "text": "<p>Assuming that the business layer is a separate DLL, I would never add a reference to <code>System.Web</code> and in consequence I would never use the <code>Session</code> object directly. This would lead to a different design of the business layer and of the exposed interfaces to a client (either web or winforms). </p>\n\n<p>That said, as a quick workaround I would suggest to write a wrapper class in your business layer that hides the <code>Session</code> object from your code. Your calls from code will be something like this:</p>\n\n<pre><code>((UserSession) DualContext.Current[\"UserSession\"]).User.Info\n</code></pre>\n\n<p>and the wrapper implementation will be something like this (not completed and tested):</p>\n\n<pre><code>public class DualContext \n{\n private Dictionary&lt;string, object&gt; winFormsSession = new Dictionary&lt;string, object&gt;();\n private static readonly DualContext instance = new DualContext();\n\n public static DualContext Current\n {\n get { return instance; }\n }\n\n public object this[string key]\n {\n get \n {\n if (HttpContext.Current != null)\n return HttpContext.Current.Session[key];\n else\n return winFormsSession[key];\n }\n set \n {\n if (HttpContext.Current != null)\n HttpContext.Current.Session[key] = value;\n else\n winFormsSession[key] = value;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 236516, "author": "Rob Windsor", "author_id": 28785, "author_profile": "https://Stackoverflow.com/users/28785", "pm_score": 2, "selected": false, "text": "<p>It would take some re-architecting, but if you switch from using Session State to User Profiles you could then use Client Application Services to share the information.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb384297.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb384297.aspx</a></p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
I have a web application that makes heavy use of the Session state to store information about the current user, their personal settings, record their session history and so on. I have found myself retrieving this session information in my business layer, like so: ``` ((UserSession)HttpContext.Current.Session["UserSession"]).User.Info ``` This poses a problem - at some point in the future my application will have a Windows client which obviously cannot reference the web Session state. So I need a host or customized session class that I can reference in my business layer that is agnostic of whether the application is running on the web or desktop. Something like: ``` IHost.User.Info ``` Behind the scenes, the web implementation will obviously utilize the Session state to store information, but I need to hide this away from my business layer. Has anyone solved this problem or got any practival advice on how best to approach this? Help appreciated.
Assuming that the business layer is a separate DLL, I would never add a reference to `System.Web` and in consequence I would never use the `Session` object directly. This would lead to a different design of the business layer and of the exposed interfaces to a client (either web or winforms). That said, as a quick workaround I would suggest to write a wrapper class in your business layer that hides the `Session` object from your code. Your calls from code will be something like this: ``` ((UserSession) DualContext.Current["UserSession"]).User.Info ``` and the wrapper implementation will be something like this (not completed and tested): ``` public class DualContext { private Dictionary<string, object> winFormsSession = new Dictionary<string, object>(); private static readonly DualContext instance = new DualContext(); public static DualContext Current { get { return instance; } } public object this[string key] { get { if (HttpContext.Current != null) return HttpContext.Current.Session[key]; else return winFormsSession[key]; } set { if (HttpContext.Current != null) HttpContext.Current.Session[key] = value; else winFormsSession[key] = value; } } } ```
236,381
<p>I have a web application that requires a server based component to periodically access POP3 email boxes and retrieve emails. The service then needs to process the emails which will involve:</p> <ul> <li>Validating the email against some business rules (does it contain a valid reference in the subject line, which user sent the mail, etc.)</li> <li>Analysing and saving any attachments to disk</li> <li>Take the email body and attachment details and create a new item in the database</li> <li>Or update an existing item where the reference matches the incoming email subject line</li> </ul> <p>What is the best way to approach this? I really don't want to have to write a POP3 client from scratch, but I need to be able to customize the processing of emails. Ideally I would be able to plug in some component that does the access and retrieval for me, returning arrays of attachments, body text, subject line, etc. ready for my processing...</p> <p><strong>[ UPDATE: Reviews ]</strong></p> <p>OK, so I have spent a fair amount of time looking into (mainly free) .NET POP3 libraries so I thought I'd provide a short review of some of those mentioned below and a few others:</p> <ul> <li><a href="http://weblogs.shockbyte.com.ar/rodolfof/archive/2008/07/07/pop3.net-library.aspx" rel="noreferrer">Pop3.net</a> - free - works OK, very basic in terms of functionality provided. This is pretty much just the POP3 commands and some base64 encoding, but it's very straight forward - probably a good introduction</li> <li><a href="http://www.componentsource.com/products/seekford-net-pop3-wizard/index.html" rel="noreferrer">Pop3 Wizard</a> - commercial / some open source code - couldn't get this to build, missing DLLs, I wouldn't bother with this </li> <li><a href="http://www.codeplex.com/csharpmail" rel="noreferrer">C#Mail</a> - free for personal use - works well, comes with Mime parser and SMTP client, however the comments are in Japanese (not a big deal) and it didn't work with SSL 'out of the box' - I had to change the SslStream constructor after which it worked no problem</li> <li><a href="http://sourceforge.net/projects/hpop/" rel="noreferrer">OpenPOP</a> - free - hasn't been updated for about 5 years so it's current state is .NET 1.0, doesn't support SSL but that was no problem to resolve - I just replaced the existing stream with an SslStream and it worked. Comes with Mime parser.</li> </ul> <p>Of the free libraries, I'd go for C#Mail or OpenPOP.</p> <p>I looked at a few commercial libraries: <a href="http://www.chilkatsoft.com/" rel="noreferrer">Chillkat</a>, <a href="http://www.rebex.net/" rel="noreferrer">Rebex</a>, <a href="http://remobjects.com/" rel="noreferrer">RemObjects</a>, <a href="http://tech.dimac.net/default2.asp?M=Products/MenuDOTNET.asp&amp;P=Products/JMaildotnet/start.htm" rel="noreferrer">JMail.net</a>. Based on features, price and impression of the company I would probably go for Rebex and may in the future if my requirements change or I run into production issues with either of C#Mail or OpenPOP.</p> <p>In case anyone's needs it, this is the replacement SslStream constructor that I used to enable SSL with C#Mail and OpenPOP:</p> <pre><code>SslStream stream = new SslStream(clientSocket.GetStream(), false, delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) { return true; }); </code></pre>
[ { "answer_id": 236393, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 1, "selected": false, "text": "<p>There are several POP3 client implementations around at codeproject.com. I have not evaluated them, but maybe you can find what you need there. If not, I can say that POP3 is quite a simple protocol. You can even read your POP3 box with telnet if you know 4-5 commands.</p>\n\n<p>You actually just need <a href=\"http://www.pnambic.com/Goodies/POP3Ref.html\" rel=\"nofollow noreferrer\">this</a> commands and maybe some base64 decoding for attachments. That's it.</p>\n" }, { "answer_id": 236397, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.dimac.net\" rel=\"nofollow noreferrer\">Jmail.NET</a>. Don't look further. Note that the free version doesn't include POP3. You'll want to take the Standard version (or more). Don't worry, it's not expensive.</p>\n" }, { "answer_id": 236409, "author": "Dan F", "author_id": 11569, "author_profile": "https://Stackoverflow.com/users/11569", "pm_score": 0, "selected": false, "text": "<p>If you don't mind paying for a component, we've had great success with chilkat in the past. For a couple of hundred bucks you get a library that's jam packed full of goodness. </p>\n" }, { "answer_id": 236521, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.codeplex.com/csharpmail\" rel=\"nofollow noreferrer\">C# Mail</a> is available on Codeplex and is pretty easy to use.</p>\n" }, { "answer_id": 236531, "author": "Jason Kester", "author_id": 27214, "author_profile": "https://Stackoverflow.com/users/27214", "pm_score": 3, "selected": false, "text": "<p>I did an implementation of <a href=\"http://sourceforge.net/projects/hpop/\" rel=\"noreferrer\">OpenPop</a> for a project recently, and was happy with it. It does what it says on the tin. (and it's free.)</p>\n" }, { "answer_id": 236728, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "<p>Take a look at the POP3 integration in my open source app BugTracker.NET at <a href=\"http://ifdefined.com/bugtrackernet.html\" rel=\"nofollow noreferrer\">http://ifdefined.com/bugtrackernet.html</a>. All free and open source. The hardest part, the mime parsing, is done in BugTracker.NET by SharpMimeTools at <a href=\"http://anmar.eu.org/projects/sharpmimetools/\" rel=\"nofollow noreferrer\">http://anmar.eu.org/projects/sharpmimetools/</a></p>\n\n<p>The important files that show how I'm using the POP3 and MIME logic are POP3Client.cs and insert_bug.aspx.</p>\n" }, { "answer_id": 236741, "author": "Nic Wise", "author_id": 2947, "author_profile": "https://Stackoverflow.com/users/2947", "pm_score": 1, "selected": false, "text": "<p>DasBlog uses a good (and free) one - grab the source package. I've used it (but I can't remember who wrote it, and I'm not on my laptop - Pavel L I think?). It's not perfect, and it doesn't do SSL, but it works nicely otherwise.</p>\n" }, { "answer_id": 346011, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I made my own Mime parser and added it to CodePlex because I kept running into unhandled exceptions with the other ones when it came to strange encodings og weird combinations of attachments. The pop3 client implementation is crude, just made for testing purposes, but handles that ok. The Mime parser part populates the standard MailMessage object, so that you can easily forward it at it is. I can expand/improve it on request, but for now it does the job ok for my needs. Feel free to check it out.</p>\n\n<p><a href=\"http://www.codeplex.com/mimeParser\" rel=\"nofollow noreferrer\">http://www.codeplex.com/mimeParser</a></p>\n" }, { "answer_id": 349647, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.lumisoft.ee/lsWWW/Download/Downloads/Net/\" rel=\"nofollow noreferrer\">Lumisoft</a> is open-source and includes a POP client (among other stuff). It's been around for many years, very stable.</p>\n" }, { "answer_id": 391584, "author": "Higty", "author_id": 48905, "author_profile": "https://Stackoverflow.com/users/48905", "pm_score": 3, "selected": false, "text": "<p>The constructor of SslStream class was modified and uploaded.\nRecommended version have no problem to use.</p>\n" }, { "answer_id": 1114703, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you need SSL to access gmail.. here is some modifications to the OpenPOP.net library that gives it SSL support.</p>\n\n<p><a href=\"http://trixcomp.blogspot.com/2009/07/c-pop3-library-with-ssl-for-gmail.html\" rel=\"nofollow noreferrer\">OpenPop.net modified to include SSL support for accessing Gmail</a> </p>\n" }, { "answer_id": 2856484, "author": "Pawel Lesnikowski", "author_id": 80894, "author_profile": "https://Stackoverflow.com/users/80894", "pm_score": 2, "selected": false, "text": "<p>You may want to include <a href=\"http://www.lesnikowski.com/mail/\" rel=\"nofollow noreferrer\">Mail.dll .NET mail component</a> in your ranking.\nIt has SSL support, Unicode, and multi-national email support:</p>\n\n<pre><code>using(Pop3 pop3 = new Pop3())\n{\n pop3.Connect(\"mail.host.com\"); // Connect to server\n pop3.Login(\"user\", \"password\"); // Login\n\n foreach(string uid in pop3.GetAll())\n {\n IMail email = new MailBuilder()\n .CreateFromEml(pop3.GetMessageByUID(uid));\n\n Console.WriteLine(email.Subject);\n }\n pop3.Close(true); \n}\n</code></pre>\n\n<p>IMAP protocol is also supported.</p>\n\n<p>Please note that this is a <strong>commercial</strong> product I've created.</p>\n\n<p>You can download it here: <a href=\"http://www.lesnikowski.com/mail/\" rel=\"nofollow noreferrer\">http://www.lesnikowski.com/mail</a></p>\n" }, { "answer_id": 4530194, "author": "foens", "author_id": 477854, "author_profile": "https://Stackoverflow.com/users/477854", "pm_score": 5, "selected": false, "text": "<p>I am one of the main developers of <a href=\"http://sourceforge.net/projects/hpop/\">OpenPop.NET</a>. I just fell over this review, and had to come with some comments regarding the current state of OpenPop.NET as the review seems outdated with the development.</p>\n\n<p>OpenPop.NET is back into active development. SSL has been introduced a half year back. The project had a major refactoring and is now much more stable and easy to use. When I took over the project it had a lot of bugs in it, and as of now I currently know none. A lot of extra features have been implemented, mainly in the MIME parser part. The project is backed by unit tests, and each time a bug is found, a unit test is created to show this bug before fixing it. An <a href=\"http://hpop.sourceforge.net/\">accompanying website</a> with examples now exists. There has also been other updates, but I do not want to mention them all.</p>\n\n<p>Also, OpenPop.NET's license has been changed from <a href=\"http://www.gnu.org/licenses/lgpl-3.0.txt\">LGPL</a> to <a href=\"http://en.wikipedia.org/wiki/Public_domain\">Public Domain</a> (aka, no restrictions). This I think is a major improvement for commercial users.</p>\n" }, { "answer_id": 5118655, "author": "JP Hellemons", "author_id": 169714, "author_profile": "https://Stackoverflow.com/users/169714", "pm_score": 1, "selected": false, "text": "<p>Since I had to automate some email processing things. I took OpenPop.net\nI was searching how I could forward mailmessages with this library and came across this amazing function: <a href=\"http://hpop.sourceforge.net/documentation/OpenPop~OpenPop.Mime.Message.ToMailMessage.html\" rel=\"nofollow\">http://hpop.sourceforge.net/documentation/OpenPop~OpenPop.Mime.Message.ToMailMessage.html</a> </p>\n\n<p>to summarize, I have chosen <strong>OpenPop.Net</strong> and recommend it!</p>\n\n<p>best regards,\nJP</p>\n" }, { "answer_id": 25416470, "author": "Oran Dennison", "author_id": 71262, "author_profile": "https://Stackoverflow.com/users/71262", "pm_score": 2, "selected": false, "text": "<p>A new option (as of 2014) is <a href=\"https://github.com/jstedfast/MailKit\" rel=\"nofollow\">MailKit</a> from Xamarin, available under the MIT license. It parses messages from disk 25x faster than OpenPOP.NET. It includes support of IMAP, POP3, and SMTP and seems to be very fast and robust.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
I have a web application that requires a server based component to periodically access POP3 email boxes and retrieve emails. The service then needs to process the emails which will involve: * Validating the email against some business rules (does it contain a valid reference in the subject line, which user sent the mail, etc.) * Analysing and saving any attachments to disk * Take the email body and attachment details and create a new item in the database * Or update an existing item where the reference matches the incoming email subject line What is the best way to approach this? I really don't want to have to write a POP3 client from scratch, but I need to be able to customize the processing of emails. Ideally I would be able to plug in some component that does the access and retrieval for me, returning arrays of attachments, body text, subject line, etc. ready for my processing... **[ UPDATE: Reviews ]** OK, so I have spent a fair amount of time looking into (mainly free) .NET POP3 libraries so I thought I'd provide a short review of some of those mentioned below and a few others: * [Pop3.net](http://weblogs.shockbyte.com.ar/rodolfof/archive/2008/07/07/pop3.net-library.aspx) - free - works OK, very basic in terms of functionality provided. This is pretty much just the POP3 commands and some base64 encoding, but it's very straight forward - probably a good introduction * [Pop3 Wizard](http://www.componentsource.com/products/seekford-net-pop3-wizard/index.html) - commercial / some open source code - couldn't get this to build, missing DLLs, I wouldn't bother with this * [C#Mail](http://www.codeplex.com/csharpmail) - free for personal use - works well, comes with Mime parser and SMTP client, however the comments are in Japanese (not a big deal) and it didn't work with SSL 'out of the box' - I had to change the SslStream constructor after which it worked no problem * [OpenPOP](http://sourceforge.net/projects/hpop/) - free - hasn't been updated for about 5 years so it's current state is .NET 1.0, doesn't support SSL but that was no problem to resolve - I just replaced the existing stream with an SslStream and it worked. Comes with Mime parser. Of the free libraries, I'd go for C#Mail or OpenPOP. I looked at a few commercial libraries: [Chillkat](http://www.chilkatsoft.com/), [Rebex](http://www.rebex.net/), [RemObjects](http://remobjects.com/), [JMail.net](http://tech.dimac.net/default2.asp?M=Products/MenuDOTNET.asp&P=Products/JMaildotnet/start.htm). Based on features, price and impression of the company I would probably go for Rebex and may in the future if my requirements change or I run into production issues with either of C#Mail or OpenPOP. In case anyone's needs it, this is the replacement SslStream constructor that I used to enable SSL with C#Mail and OpenPOP: ``` SslStream stream = new SslStream(clientSocket.GetStream(), false, delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) { return true; }); ```
I am one of the main developers of [OpenPop.NET](http://sourceforge.net/projects/hpop/). I just fell over this review, and had to come with some comments regarding the current state of OpenPop.NET as the review seems outdated with the development. OpenPop.NET is back into active development. SSL has been introduced a half year back. The project had a major refactoring and is now much more stable and easy to use. When I took over the project it had a lot of bugs in it, and as of now I currently know none. A lot of extra features have been implemented, mainly in the MIME parser part. The project is backed by unit tests, and each time a bug is found, a unit test is created to show this bug before fixing it. An [accompanying website](http://hpop.sourceforge.net/) with examples now exists. There has also been other updates, but I do not want to mention them all. Also, OpenPop.NET's license has been changed from [LGPL](http://www.gnu.org/licenses/lgpl-3.0.txt) to [Public Domain](http://en.wikipedia.org/wiki/Public_domain) (aka, no restrictions). This I think is a major improvement for commercial users.
236,387
<p>I'm not sure if the title is very clear, but basically what I have to do is read a line of text from a file and split it up into 8 different string variables. Each line will have the same 8 chunks in the same order (title, author, price, etc). So for each line of text, I want to end up with 8 strings.</p> <p>The first problem is that the last two fields in the line may or may not be present, so I need to do something with stringTokenizer.hasMoreTokens, otherwise it will die messily when fields 7 and 8 are not present.</p> <p>I would ideally like to do it in one while of for loop, but I'm not sure how to tell that loop what the order of the fields is going to be so it can fill all 8 (or 6) strings correctly. Please tell me there's a better way that using 8 nested if statements! </p> <p>EDIT: The String.split solution seems definitely part of it, so I will use that instead of stringTokenizer. However, I'm still not sure what the best way of feeding the individual strings into the constructor. Would the best way be to have the class expecting an array, and then just do something like this in the constructor:</p> <pre><code>line[1] = isbn; line[2] = title; </code></pre>
[ { "answer_id": 236389, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "<p>Would a regular expression with capture groups work for you? You can certainly make parts of the expression optional.</p>\n\n<p>An example line of data or three might be helpful.</p>\n" }, { "answer_id": 236392, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 0, "selected": false, "text": "<p>Is this a CSV or similar file by any chance? If so, there are libraries to help you, for example <a href=\"http://commons.apache.org/sandbox/csv/\" rel=\"nofollow noreferrer\">Apache Commons CSV</a> (link to alternatives on their page too). It will get you a String[] for each line in the file. Just check the array size to know what optional fields are present.</p>\n" }, { "answer_id": 236396, "author": "banjollity", "author_id": 29620, "author_profile": "https://Stackoverflow.com/users/29620", "pm_score": 2, "selected": false, "text": "<p>Regular expression is the way. You can convert your incoming String into an array of String using the split method</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)</a></p>\n" }, { "answer_id": 236425, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": true, "text": "<p>The best way is to not use a StringTokenizer at all, but use String's <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)\" rel=\"nofollow noreferrer\">split</a> method. It returns an array of Strings, and you can get the length from that.</p>\n\n<p>For each line in your file you can do the following:</p>\n\n<pre><code>String[] tokens = line.split(\"#\");\n</code></pre>\n\n<p><code>tokens</code> will now have 6 - 8 Strings. Use <code>tokens.length()</code> to find out how many, then create your object from the array.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31429/" ]
I'm not sure if the title is very clear, but basically what I have to do is read a line of text from a file and split it up into 8 different string variables. Each line will have the same 8 chunks in the same order (title, author, price, etc). So for each line of text, I want to end up with 8 strings. The first problem is that the last two fields in the line may or may not be present, so I need to do something with stringTokenizer.hasMoreTokens, otherwise it will die messily when fields 7 and 8 are not present. I would ideally like to do it in one while of for loop, but I'm not sure how to tell that loop what the order of the fields is going to be so it can fill all 8 (or 6) strings correctly. Please tell me there's a better way that using 8 nested if statements! EDIT: The String.split solution seems definitely part of it, so I will use that instead of stringTokenizer. However, I'm still not sure what the best way of feeding the individual strings into the constructor. Would the best way be to have the class expecting an array, and then just do something like this in the constructor: ``` line[1] = isbn; line[2] = title; ```
The best way is to not use a StringTokenizer at all, but use String's [split](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)) method. It returns an array of Strings, and you can get the length from that. For each line in your file you can do the following: ``` String[] tokens = line.split("#"); ``` `tokens` will now have 6 - 8 Strings. Use `tokens.length()` to find out how many, then create your object from the array.
236,406
<p>Is one more preferred, or performs better over the other?</p>
[ { "answer_id": 236411, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://php.net/is_int\" rel=\"noreferrer\"><code>is_int()</code></a> returns true if the argument is an integer type, <a href=\"http://www.php.net/ctype_digit\" rel=\"noreferrer\"><code>ctype_digit()</code></a> takes a string argument and returns true if all the characters in the string are digits.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>┌──────────┬───────────┬────────────────┐\n│ │ is_int: │ ctype_digit: │\n├──────────┼───────────┼────────────────┤\n│ 123 │ true │ false │\n├──────────┼───────────┼────────────────┤\n│ 12.3 │ false │ false │\n├──────────┼───────────┼────────────────┤\n│ \"123\" │ false │ true │\n├──────────┼───────────┼────────────────┤\n│ \"12.3\" │ false │ false │\n├──────────┼───────────┼────────────────┤\n│ \"-1\" │ false │ false │\n├──────────┼───────────┼────────────────┤\n│ -1 │ true │ false │\n└──────────┴───────────┴────────────────┘\n</code></pre>\n" }, { "answer_id": 236417, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 2, "selected": false, "text": "<p>The last thing you should be worrying about is how fast one of these is. There is no way that checking a string for being an integer is going to be a bottleneck in your code.</p>\n" }, { "answer_id": 237931, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 1, "selected": false, "text": "<p>If you don't really care if the argument is a int type or a string with numbers, use is_numeric. It will return true for floats also, tho.</p>\n" }, { "answer_id": 7439191, "author": "esd", "author_id": 947947, "author_profile": "https://Stackoverflow.com/users/947947", "pm_score": 2, "selected": false, "text": "<p>ctype <strong>not</strong> always <em>return false</em> on integer type.</p>\n\n<pre><code>foreach(range(-1000 , 1000)as $num){\n if(ctype_digit($num)){\n echo $num . \", \";\n } \n}\n</code></pre>\n\n<p>ctype_digit return true for the following integer type number.</p>\n\n<p>-78,-77,-71,48,49,50,51,52,53,54,55,56,57,178,179,185,\n256,257,258,259,260,261,262,263,264,265,266,267,268,269,270 to 1000</p>\n\n<p>the base practice is to case every number to string e.q. strval($num) or (String) $num\nin this case negative value (-78) will always return false.</p>\n\n<p><br/>\nis_int will return you true on int type value between -2147483647 to 2147483647.\nany value exceed that number will return you false presuming it is running on 32bits system.\non 64bits it can go up to range of -9223372036854775807 to 9223372036854775807</p>\n\n<p><br/>\nin term of performance personally very hard to say. ctype_digit maybe faster than is_int but if you have to cast every value to string performance is reduced overall. </p>\n" }, { "answer_id": 17124362, "author": "masakielastic", "author_id": 531320, "author_profile": "https://Stackoverflow.com/users/531320", "pm_score": 0, "selected": false, "text": "<p>Ctype_digit returns false if the range of integer is in negative range or between 0 and 47 or between 58 and 255. You can check ctype_digit's behavior by using the following snippet.</p>\n\n<pre><code>setlocale(LC_ALL, 'en_US.UTF-8');\nvar_dump(\n true === array_every(range(-1000, -1), 'ctype_digit_returns_false'),\n true === array_every(range(0, 47), 'ctype_digit_returns_false'),\n true === array_every(range(48, 57), 'ctype_digit_returns_true'),\n true === array_every(range(58, 255), 'ctype_digit_returns_false'),\n true === array_every(range(256, 1000), 'ctype_digit_returns_true')\n);\n\n// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/every\nfunction array_every(array $array, $callable)\n{\n $count = count($array);\n\n for ($i = 0; $i &lt; $count; $i +=1) {\n\n if (!$callable($array[$i])) {\n\n return false;\n\n }\n\n }\n\n return true;\n}\n\nfunction ctype_digit_returns_true($v)\n{\n return true === ctype_digit($v);\n}\n\nfunction ctype_digit_returns_false($v)\n{\n return false === ctype_digit($v);\n}\n</code></pre>\n" }, { "answer_id": 37585691, "author": "Buksy", "author_id": 619616, "author_profile": "https://Stackoverflow.com/users/619616", "pm_score": 3, "selected": false, "text": "<p>There is also <a href=\"http://php.net/manual/en/function.is-numeric.php\" rel=\"noreferrer\"><code>is_numeric</code></a> which returns true if passed in value can be parsed as number.</p>\n\n<p><a href=\"https://i.stack.imgur.com/iwREU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iwREU.png\" alt=\"enter image description here\"></a></p>\n\n<p>If I try to compare performance of functions on <strong>PHP 5.5.30</strong> here are the results:</p>\n\n<p><a href=\"https://i.stack.imgur.com/apq2O.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/apq2O.png\" alt=\"enter image description here\"></a></p>\n\n<p>This is the code I used for benchmark</p>\n\n<pre><code>// print table cell and highlight if lowest value is used\nfunction wr($time1, $time2, $time3, $i) {\n if($i == 1) $time = $time1;\n if($i == 2) $time = $time2;\n if($i == 3) $time = $time3;\n\n echo('&lt;td&gt;');\n if(min($time1, $time2, $time3) === $time) printf('&lt;b&gt;%.4f&lt;/b&gt;', $time);\n else printf('%.4f', $time);\n echo('&lt;/td&gt;');\n}\n\n\n$test_cases = array( 123, 12.3, '123', true);\n$tests = 1000000;\n$result = true; // Used just to make sure cycles won't get optimized out\necho('&lt;table&gt;'.PHP_EOL);\necho('&lt;tr&gt;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&lt;th&gt;is_int&lt;/th&gt;&lt;th&gt;ctype_digit&lt;/th&gt;&lt;th&gt;is_numeric&lt;/th&gt;&lt;/tr&gt;');\nforeach($test_cases as $case) {\n echo('&lt;tr&gt;&lt;th&gt;'.gettype($case).'&lt;/th&gt;');\n\n $time = microtime(true);\n for($i = 0; $i &lt; $tests; $i++) {\n $result |= is_int((int)rand());\n }\n $time1 = microtime(true)-$time;\n\n $time = microtime(true);\n for($i = 0; $i &lt; $tests; $i++) {\n $result |= ctype_digit((int)rand());\n }\n $time2 = microtime(true)-$time;\n\n $time = microtime(true);\n for($i = 0; $i &lt; $tests; $i++) {\n $result |= is_numeric((int)rand());\n }\n $time3 = microtime(true)-$time;\n\n wr($time1, $time2, $time3, 1);\n wr($time1, $time2, $time3, 2);\n wr($time1, $time2, $time3, 3);\n echo('&lt;/tr&gt;'.PHP_EOL);\n}\n\necho('&lt;/table&gt;');\n\nexit();\n</code></pre>\n" }, { "answer_id": 42679183, "author": "Nono", "author_id": 584262, "author_profile": "https://Stackoverflow.com/users/584262", "pm_score": 2, "selected": false, "text": "<p>Well it's very interesting :) Here is all story:</p>\n\n<blockquote>\n <p><strong><code>is_numeric:</code></strong> — Finds whether a variable is a number or a numeric string, No matter value is negative or Boolean or String or any type\n of number, if value is purely number it will return <strong><code>'true'</code></strong> else <strong><code>'false'</code></strong>.</p>\n \n <p><strong>Remember: No Character Only Number any type :)</strong></p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><strong><code>is_init</code></strong>— Find whether the type of a variable is integer, if value is purely integer then it will return 'true' else 'false'.</p>\n \n <p><strong>Remember: No Character, Double or Negative, Only Integer</strong></p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><strong><code>in_integer</code></strong>— Alias of is_int()</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><strong><code>intval:</code></strong>— Get the integer value of a variable, it's take all kind of value and returns only Integer value, if values are negative then\n returns '<strong><code>-Integer</code></strong>' value. No matter values are Integer, Float,\n Negative or '<strong><code>NumberString</code></strong>' or '<strong><code>NumberStringCharacter</code></strong>'.\n It's subtract the Integer values from string \"<strong><code>If String Starts with\n Number</code></strong>\".</p>\n \n <ul>\n <li><strong>NumberString</strong> = A Number value in String Format</li>\n <li><strong>NumberStringCharacter</strong> = A String Start with Number</li>\n </ul>\n \n <p><strong>Remember: You will get Integer value from Number, Float, Negative or String which is starts with Number.</strong></p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><strong><code>ctype_digit</code></strong>— Check for numeric character(s), If a Whole Number supplied in String Format you will get '<strong><code>true</code></strong>' else '<strong><code>false</code></strong>'. It will\n work with only StringNumber, No Float, No Negative only Whole Number\n as String.</p>\n \n <p><strong>Remember: Whole Number as String, No Negative Number, No Float Number, No Number Type, No Character, Only Number as String.</strong></p>\n</blockquote>\n\n<p><strong>Birds Eye View:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/gQIGu.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gQIGu.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Thanks to <a href=\"http://php.net/\" rel=\"nofollow noreferrer\">http://php.net/</a></strong></p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is one more preferred, or performs better over the other?
[`is_int()`](http://php.net/is_int) returns true if the argument is an integer type, [`ctype_digit()`](http://www.php.net/ctype_digit) takes a string argument and returns true if all the characters in the string are digits. **Example:** ``` ┌──────────┬───────────┬────────────────┐ │ │ is_int: │ ctype_digit: │ ├──────────┼───────────┼────────────────┤ │ 123 │ true │ false │ ├──────────┼───────────┼────────────────┤ │ 12.3 │ false │ false │ ├──────────┼───────────┼────────────────┤ │ "123" │ false │ true │ ├──────────┼───────────┼────────────────┤ │ "12.3" │ false │ false │ ├──────────┼───────────┼────────────────┤ │ "-1" │ false │ false │ ├──────────┼───────────┼────────────────┤ │ -1 │ true │ false │ └──────────┴───────────┴────────────────┘ ```
236,412
<p>I have a web application that comprises the following:</p> <ul> <li>A web project (with a web.config file containing a connection string - but no data access code in the web project)</li> <li>A data access project that uses LINQ-SQL classes to provide entities to the web project UI (this project has a settings file and an app.config - both of which have connection strings)</li> </ul> <p>When I build and deploy, there is no settings file or app.config in the Bin directory with the data access .dll, but changing the connection string in the web.config file doesn't change the database accordingly - so the connection string must be compiled into the data access dll. </p> <p>What I need is one config file for my entire deployment - website, data access dlls, everything - that has one connection string which gets used. At the moment there appear to be multiple connection strings getting used or hardcoded all over the place. </p> <p>How do I best resolve this mess?</p> <p>Thanks for any help.</p>
[ { "answer_id": 236426, "author": "endian", "author_id": 25462, "author_profile": "https://Stackoverflow.com/users/25462", "pm_score": 0, "selected": false, "text": "<p>How about defining a ConnectionFactory object, that takes an enum as a parameter and returns a fully-formed connection object?</p>\n" }, { "answer_id": 236435, "author": "Robert Durgin", "author_id": 3132, "author_profile": "https://Stackoverflow.com/users/3132", "pm_score": 3, "selected": false, "text": "<p>The configuration file for the startup project will define the configuration settings for all included projects. For example if your web project is the startup project, any reference to \"appSettings\" will look for settings from web.config, this includes any references to \"appSettings\" from your data access project. So copy any config settings from the Data Access project's app.config to the web project's web.config.</p>\n" }, { "answer_id": 236437, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "<p>Here's one way to look at it. Which component should make the decision about which database to use? It's possible that the database (or at least the connection string) could change in the future. Does the website decide which database to use? Or, does the DAL decide?</p>\n\n<p>If you have dev, QA, UAT and prod databases, managing these connection strings is crucial.</p>\n\n<p>If the website decides, it should pass the connection string from its web.config to the DAL.\nIf the website isn't supposed to know or care where the data comes from, then the connection string belongs in the DAL.</p>\n" }, { "answer_id": 236440, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 0, "selected": false, "text": "<p>You could also have the web application provide the connection string when it needs to use the Data Access project. You could make it part of the constructor.</p>\n\n<p>Also, you could could just write your own logic to load a connection string from an external file when the data access project makes it's calls.</p>\n" }, { "answer_id": 236442, "author": "TGnat", "author_id": 25121, "author_profile": "https://Stackoverflow.com/users/25121", "pm_score": 2, "selected": false, "text": "<p>Your application will only use the config entries in the web.config file.\nYou can put dll config setting in the web.config file as long as they are structure properly. My example is VB specific using the My Namespace, but it gives you the general idea.</p>\n\n<p>In the configSections paret of the config file you will need an entry:</p>\n\n<pre><code>&lt;configSections&gt;\n &lt;sectionGroup name=\"applicationSettings\" type=\"System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" &gt;\n &lt;section name=\"YourAssembly.My.MySettings\" type=\"System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" /&gt;\n &lt;/sectionGroup&gt;&lt;/configSections&gt;\n</code></pre>\n\n<p>Then in the applicationSettings part of the config file you put the entries for each dll:</p>\n\n<pre><code> &lt;applicationSettings&gt;\n &lt;YourAssembly.My.MySettings&gt;\n &lt;setting name=\"DebugMode\" serializeAs=\"String\"&gt;\n &lt;value&gt;False&lt;/value&gt;\n &lt;/setting&gt;\n &lt;/YourAssembly.My.MySettings&gt;\n &lt;/applicationSettings&gt; \n</code></pre>\n" }, { "answer_id": 236457, "author": "Grant", "author_id": 407, "author_profile": "https://Stackoverflow.com/users/407", "pm_score": 0, "selected": false, "text": "<p>In a perfect world, I think you would refactor you data layer to pick up configuration settings via System.Configuration or relevant constructors/factories. Meaning, you either need to rewire its implicit configuration source, or explicitly set connections from its host/consumer. Another related pattern for centralizing these types of constants is to throw an readonly property into a static helper class and have that class manage the actual resolution from configs, etc. </p>\n\n<p>One place you can look that I think shows good examples of how to do this elegantly is NHibernate and its configuration/mappings management. Granted, it's a bit of xml hell, and Fluent NHib is more sugary, but most of the real world samples will show you how to reconcile configuration from a supporting assembly vs. the executing assembly.</p>\n" }, { "answer_id": 236464, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 5, "selected": true, "text": "<p>I've never had a problem with the <em>Data Access Layer</em> (DAL) being able to use the connection strings from my <code>web.config</code> file. Usually I just copy the connection strings section from the DAL and paste it into the <code>web.config</code>. I'm using the DBML designer to create the data context.</p>\n\n<p>If this won't work for you, you can specify the connection string in the data context constructor. In your web project have a static class that loads your settings, including your connection strings, and when you create your DAL object (or data context, if creating it directly) just pass it in to the constructor.</p>\n\n<pre><code>public static class GlobalSettings\n{\n private static string dalConnectionString;\n public static string DALConnectionString\n {\n get\n {\n if (dalConnectionString == null)\n {\n dalConnectionString = WebConfigurationManager\n .ConnectionStrings[\"DALConnectionString\"]\n .ConnectionString;\n }\n return dalConnectionString;\n }\n }\n}\n...\n\nusing (var context = new DALDataContext(GlobalSettings.DALConnectionString))\n{\n ...\n}\n</code></pre>\n" }, { "answer_id": 236486, "author": "Jason Kester", "author_id": 27214, "author_profile": "https://Stackoverflow.com/users/27214", "pm_score": 0, "selected": false, "text": "<p>Roll your own ConnectionFactory based on .config files: </p>\n\n<ul>\n<li>Define a custom config section to map key/connectionstring pairs</li>\n<li>Teach your ConnectionFactory to sniff into that config section using hostname or machinename as appropriate</li>\n<li>Populate key/connectionstring values for your various dev/qa/prod servers, and drop them into your various app.config, web.config etc. files.</li>\n</ul>\n\n<p>Pro:</p>\n\n<ul>\n<li>All lives inside the project, so no surprises</li>\n<li>Adding additional deployment target is a copy/paste operation in a .config file</li>\n</ul>\n\n<p>Con:</p>\n\n<ul>\n<li>Makes for big ugly XML sections, especially if you have a dozen production servers</li>\n<li>Needs to be duplicated between projects</li>\n<li>Needs code change &amp; redeploy to add new target</li>\n<li>Code needs to know about the environment in which it will live </li>\n</ul>\n" }, { "answer_id": 236512, "author": "Jason Kester", "author_id": 27214, "author_profile": "https://Stackoverflow.com/users/27214", "pm_score": 3, "selected": false, "text": "<p>Roll your own ConnectionFactory based on the Registry: </p>\n\n<ul>\n<li>add a registry key for your application under SOFTWARE/[YOUR_COMPANY]/[YOUR_APP]</li>\n<li>add a string value for ConnectionString</li>\n<li>Teach your ConnectionFactory to crack open the appropriate registry key (in a static constructor, not every page load!).</li>\n<li>export the registry info as a .reg file, add it to source control, modify and apply it as necessary to set up additional machines.</li>\n</ul>\n\n<p>Pro:</p>\n\n<ul>\n<li>Simple to set up</li>\n<li>Connectionstring lives in a single place</li>\n<li>Not in web/app.config, so no need to hardcode environment-specific settings.</li>\n<li>Not in web/app.config, so Junior Dev Jimmy can't accidentally tell your production server to look at the DEV database</li>\n</ul>\n\n<p>Con:</p>\n\n<ul>\n<li>Not immediately obvious that important things are living in the registry, so new devs will need instructions.</li>\n<li>Extra step when configuring a new deployment machine</li>\n<li>Registry is oldskool. Junior devs will mock you.</li>\n</ul>\n" }, { "answer_id": 236808, "author": "flesh", "author_id": 27805, "author_profile": "https://Stackoverflow.com/users/27805", "pm_score": 2, "selected": false, "text": "<p>Thanks for the responses.</p>\n\n<p>Those of you who say the app will use the setting in the web.config are correct for instances where I reference it in my own code:</p>\n\n<pre><code>_connectionString = ConfigurationManager.AppSettings[\"ConnectionString\"];\n</code></pre>\n\n<p>..but there is a different issue with LINQ-SQL datacontexts - I think they include connections strings in the compiled dll for use in the parameterless constructor. As tvanofosson says, I need to create datacontexts by passing in a reference to the connection string in the web.config. Which is where I was getting into a tangle :)</p>\n" }, { "answer_id": 780592, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I had a bit of a struggle with this issue too. I found a solution by using c# partial class definition and extending the datacontext created by dbml designer. This solution quite is similar to tvanfosson's answer. What you have to do is to create partial datacontext class with default constructor getting ConnectionString from settings and in dbml designer DC properties set connection to None. That way connection string will not be the compiled into dll. Datacontext will automatically get connection string from web.config connectionstring settings. I have not tested if this works with app.config also, but I think it should work fine.</p>\n\n<p>Here is sample of partial DC class:</p>\n\n<pre><code>namespace MyApplication {\n /// &lt;summary&gt;\n /// Summary description for MyDataContext\n /// &lt;/summary&gt;\n /// \n public partial class MyDataContext\n {\n public MyDataContext() :\n base(global::System.Configuration.ConfigurationManager.ConnectionStrings[\"MyConnectionString\"].ConnectionString, mappingSource)\n {\n OnCreated();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3486654, "author": "Seba Illingworth", "author_id": 93451, "author_profile": "https://Stackoverflow.com/users/93451", "pm_score": 2, "selected": false, "text": "<p>To keep it safe from anything in the auto generated code, override the connection info in the OnCreated() method of the data context:</p>\n\n<pre><code>using System.Configuration;\nnamespace MyApplication \n{\n partial void OnCreated()\n {\n // attempt to use named connection string from the calling config file\n var conn = ConfigurationManager.ConnectionStrings[\"MyConnectionString\"];\n if (conn != null) Connection.ConnectionString = conn.ConnectionString;\n }\n}\n</code></pre>\n\n<p>This way the dbml designer can do connection stuff its way (which isn't nice outside of a web project), but you grab final control of the connection when the application runs.</p>\n" }, { "answer_id": 4310454, "author": "Joe Niland", "author_id": 366965, "author_profile": "https://Stackoverflow.com/users/366965", "pm_score": 0, "selected": false, "text": "<p>I know this is old but here's how I do it (I quite like @Seba's way but I haven't tried that)</p>\n\n<p>This assumes your DBML file resides in its own class library, which I've found it most convenient when sharing entities and data access across multiple websites, and other class libraries. It also assumes you've named your connection string the same in each project. I use NAnt to set this when I deploy to different environments.</p>\n\n<p>I based this on the top answer above from @tvanfosson - kudos to that guy.</p>\n\n<ol>\n<li>Create your own base class, which derives from LinqDataContext</li>\n</ol>\n\n<p>Here's the VB code:</p>\n\n<pre><code> Imports System.Configuration\n\nPublic Class CustomDataContextBase\n Inherits System.Data.Linq.DataContext\n Implements IDisposable\n\n Private Shared overrideConnectionString As String\n\n Public Shared ReadOnly Property CustomConnectionString As String\n Get\n If String.IsNullOrEmpty(overrideConnectionString) Then\n overrideConnectionString = ConfigurationManager.ConnectionStrings(\"MyAppConnectionString\").ConnectionString\n End If\n\n Return overrideConnectionString\n End Get\n End Property\n\n Public Sub New()\n MyBase.New(CustomConnectionString)\n End Sub\n\n Public Sub New(ByVal connectionString As String)\n MyBase.New(CustomConnectionString)\n End Sub\n\n Public Sub New(ByVal connectionString As String, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)\n MyBase.New(CustomConnectionString, mappingSource)\n End Sub\n\n Public Sub New(ByVal connection As IDbConnection, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)\n MyBase.New(CustomConnectionString, mappingSource)\n End Sub\n\nEnd Class\n</code></pre>\n\n<ol>\n<li>Open your DBML file, and in the Properties, add the above class name to the Base Class property. </li>\n</ol>\n\n<p>Note, if you placed the custom data context class in the same assembly, simply include the class name, e.g. CustomDataContext.</p>\n\n<p>If they are in different assemblies, use the fully qualified name, e.g. MyCo.MyApp.Data.CustomDataContext</p>\n\n<ol>\n<li>To ensure the Designer stuff works properly, copy your connection string into the app.config file for the class library. This will not be used apart from in the IDE.</li>\n</ol>\n\n<p>That's it. </p>\n\n<p>You'll need to name your connection string the same</p>\n\n<p>What you are essentially doing is forcing the data context to ignore the connection info set in the DBML file. Using the ConfigurationManager methods will mean that it will pick up the connection string from the calling assembly.</p>\n\n<p>HTH</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
I have a web application that comprises the following: * A web project (with a web.config file containing a connection string - but no data access code in the web project) * A data access project that uses LINQ-SQL classes to provide entities to the web project UI (this project has a settings file and an app.config - both of which have connection strings) When I build and deploy, there is no settings file or app.config in the Bin directory with the data access .dll, but changing the connection string in the web.config file doesn't change the database accordingly - so the connection string must be compiled into the data access dll. What I need is one config file for my entire deployment - website, data access dlls, everything - that has one connection string which gets used. At the moment there appear to be multiple connection strings getting used or hardcoded all over the place. How do I best resolve this mess? Thanks for any help.
I've never had a problem with the *Data Access Layer* (DAL) being able to use the connection strings from my `web.config` file. Usually I just copy the connection strings section from the DAL and paste it into the `web.config`. I'm using the DBML designer to create the data context. If this won't work for you, you can specify the connection string in the data context constructor. In your web project have a static class that loads your settings, including your connection strings, and when you create your DAL object (or data context, if creating it directly) just pass it in to the constructor. ``` public static class GlobalSettings { private static string dalConnectionString; public static string DALConnectionString { get { if (dalConnectionString == null) { dalConnectionString = WebConfigurationManager .ConnectionStrings["DALConnectionString"] .ConnectionString; } return dalConnectionString; } } } ... using (var context = new DALDataContext(GlobalSettings.DALConnectionString)) { ... } ```
236,436
<p>I made previously a question: <a href="https://stackoverflow.com/questions/236354/error-handling-when-taking-user-input">error handling when taking user input</a></p> <p>and I made the suggested changes:</p> <pre><code>char displayMainMenu() { char mainMenuChoice; cout &lt;&lt; "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout &lt;&lt; "\n &lt;r&gt; Give new coefficients"; cout &lt;&lt; "\n &lt;c&gt; Calculate equations solutions"; cout &lt;&lt; "\n &lt;t&gt; Terminate the program"; cout&lt;&lt;"Enter choice : "; cin&gt;&gt;mainMenuChoice; return mainMenuChoice; } int main() { bool done = false; while(!done) { char choice = displayMainMenu(); switch(tolower(choice)) { case 'r': cout&lt;&lt;"Entered case 'r'"; break; case 'c': cout&lt;&lt;"Entered case 'c'"; break; case 't': cout&lt;&lt;"Entered case 't'"; break; default: cout&lt;&lt;"Invalid choice! Try again"&lt;&lt;endl; } } return 0; } </code></pre> <p>The new problem is that if the user enters by mistake lets say "ter" i get the following :( :</p> <pre><code>Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : ter Entered case 't' Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : Invalid choice! Try again Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : Invalid choice! Try again </code></pre> <p>How could I avoid this from happening??</p>
[ { "answer_id": 236461, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>In your <code>displayMainMenu()</code> function, instead of reading in a <code>char</code>, read in a string. Throw out (with a warning) any input that is greater than one character in length.</p>\n\n<p>You can use</p>\n\n<pre><code>char str[101]\nstd::cin.getline(str, 101);\n</code></pre>\n\n<p>in place of </p>\n\n<pre><code>cin &gt;&gt; mainMenuChoice;\n</code></pre>\n\n<p>in order to read the string.</p>\n" }, { "answer_id": 237022, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>string displayMainMenu()\n{\n string mainMenuChoice;\n cout &lt;&lt; \"\\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: \"; \n cout &lt;&lt; \"\\n &lt;r&gt; Give new coefficients\"; \n cout &lt;&lt; \"\\n &lt;c&gt; Calculate equations solutions\"; \n cout &lt;&lt; \"\\n &lt;t&gt; Terminate the program\";\n cout &lt;&lt; \"\\nEnter choice : \";\n getline(cin, mainMenuChoice);\n return mainMenuChoice;\n}\n\nint main()\n{\n bool done = false;\n while(!done)\n {\n string choice = displayMainMenu();\n if (choice.size() &gt; 1 || choice.size() &lt; 0)\n cout&lt;&lt;\"Invalid choice! Try again\"&lt;&lt;endl;\n\n switch(tolower(choice[0]))\n {\n case 'r':\n cout&lt;&lt;\"Entered case 'r'\";\n break;\n case 'c':\n cout&lt;&lt;\"Entered case 'c'\";\n break; \n case 't':\n cout&lt;&lt;\"Entered case 't'\";\n break;\n default:\n cout&lt;&lt;\"Invalid choice! Try again\"&lt;&lt;endl; \n }\n }\n return 0;\n}\n</code></pre>\n\n<p>Use getline(istream, string &amp;) to read in a full line at a time (not including the eol). Check that it's the right length, and then look at only the first character.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I made previously a question: [error handling when taking user input](https://stackoverflow.com/questions/236354/error-handling-when-taking-user-input) and I made the suggested changes: ``` char displayMainMenu() { char mainMenuChoice; cout << "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout << "\n <r> Give new coefficients"; cout << "\n <c> Calculate equations solutions"; cout << "\n <t> Terminate the program"; cout<<"Enter choice : "; cin>>mainMenuChoice; return mainMenuChoice; } int main() { bool done = false; while(!done) { char choice = displayMainMenu(); switch(tolower(choice)) { case 'r': cout<<"Entered case 'r'"; break; case 'c': cout<<"Entered case 'c'"; break; case 't': cout<<"Entered case 't'"; break; default: cout<<"Invalid choice! Try again"<<endl; } } return 0; } ``` The new problem is that if the user enters by mistake lets say "ter" i get the following :( : ``` Quadratic equation: a*X^2 + b*X + c = 0 main menu: <r> Give new coefficients <c> Calculate equations solutions <t> Terminate the program Enter choice : ter Entered case 't' Quadratic equation: a*X^2 + b*X + c = 0 main menu: <r> Give new coefficients <c> Calculate equations solutions <t> Terminate the program Enter choice : Invalid choice! Try again Quadratic equation: a*X^2 + b*X + c = 0 main menu: <r> Give new coefficients <c> Calculate equations solutions <t> Terminate the program Enter choice : Invalid choice! Try again ``` How could I avoid this from happening??
In your `displayMainMenu()` function, instead of reading in a `char`, read in a string. Throw out (with a warning) any input that is greater than one character in length. You can use ``` char str[101] std::cin.getline(str, 101); ``` in place of ``` cin >> mainMenuChoice; ``` in order to read the string.
236,463
<p>When I type the following code in Emacs ruby-mode, the "#{foo}" is fontified in a different color than the enclosing string. How do I do this in my own Emacs mode? I tried to decipher the ruby-mode source code but couldn't understand it in a reasonable amount of time.</p> <pre><code>"a #{foo} a" </code></pre>
[ { "answer_id": 236592, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 1, "selected": false, "text": "<p>Search for where ruby-mode.el sets <code>font-lock-syntactic-keywords</code>:</p>\n\n<pre><code>(setq ruby-font-lock-syntactic-keywords\n '(\n ;; #{ }, #$hoge, #@foo are not comments\n (\"\\\\(#\\\\)[{$@]\" 1 (1 . nil))\n</code></pre>\n\n<p>Here's some documentation on the similar <a href=\"http://www.delorie.com/gnu/docs/elisp-manual-21/elisp_367.html\" rel=\"nofollow noreferrer\"><code>font-lock-keywords</code></a> variable, which is what you should use to accomplish the same type of fontification.</p>\n" }, { "answer_id": 236601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Finally figured it out. The answer is that the \"override\" parameter in a fontification rule should be set to t, which means that the given face will override the string face. See the documentation for the variable \"font-lock-keywords\" for details. Here's an example:</p>\n\n<pre class=\"lang-el prettyprint-override\"><code>(define-derived-mode temp-mode fundamental-mode \"Temp\"\n \"Temporary major mode.\"\n (set (make-local-variable 'font-lock-defaults)\n '((temp-mode-font-lock-keywords) nil nil nil nil)))\n\n(defconst temp-mode-font-lock-keywords\n (list (list \"$[A-Za-z0-9]+\" 0 font-lock-variable-name-face t)))\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When I type the following code in Emacs ruby-mode, the "#{foo}" is fontified in a different color than the enclosing string. How do I do this in my own Emacs mode? I tried to decipher the ruby-mode source code but couldn't understand it in a reasonable amount of time. ``` "a #{foo} a" ```
Finally figured it out. The answer is that the "override" parameter in a fontification rule should be set to t, which means that the given face will override the string face. See the documentation for the variable "font-lock-keywords" for details. Here's an example: ```el (define-derived-mode temp-mode fundamental-mode "Temp" "Temporary major mode." (set (make-local-variable 'font-lock-defaults) '((temp-mode-font-lock-keywords) nil nil nil nil))) (defconst temp-mode-font-lock-keywords (list (list "$[A-Za-z0-9]+" 0 font-lock-variable-name-face t))) ```
236,530
<p>I'd like to do the same in C#. Is there anyway of using properties in C# with parameters in the same way I've done with the parameter 'Key' in this VB.NET example?</p> <blockquote> <pre><code>Private Shared m_Dictionary As IDictionary(Of String, Object) = New Dictionary(Of String, Object) </code></pre> </blockquote> <pre><code>Public Shared Property DictionaryElement(ByVal Key As String) As Object Get If m_Dictionary.ContainsKey(Key) Then Return m_Dictionary(Key) Else Return [String].Empty End If End Get Set(ByVal value As Object) If m_Dictionary.ContainsKey(Key) Then m_Dictionary(Key) = value Else m_Dictionary.Add(Key, value) End If End Set End Property </code></pre> <p>Thanks</p>
[ { "answer_id": 236539, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p>Is there anyway of using properties in C# with parameters</p>\n</blockquote>\n\n<p>No. You only can provide the <em>default</em> property in C# with an argument, to model indexed access (as in a dictionary):</p>\n\n<pre><code>public T this[string key] {\n get { return m_Dictionary[key]; }\n set { m_Dictionary[key] = value; }\n}\n</code></pre>\n\n<p>Other properties can't have arguments. Use a function instead. By the way, it's recommented to do the same in VB so other .NET languages (C# …) can use your code.</p>\n\n<p>By the way, your code is unnecessarily complicated. Four things:</p>\n\n<ul>\n<li>You don't need to escape the <code>String</code> identifier. Use the keyword directly.</li>\n<li>Why not use <code>\"\"</code>?</li>\n<li>Use <code>TryGetValue</code>, it's faster. You query the dictionary twice.</li>\n<li>Your setter doesn't have to test whether the value already exists.</li>\n</ul>\n\n<hr>\n\n<pre><code>Public Shared Property DictionaryElement(ByVal Key As String) As Object\n Get\n Dim ret As String\n If m_Dictionary.TryGetValue(Key, ret) Then Return ret\n Return \"\" ' Same as String.Empty! '\n End Get\n Set(ByVal value As Object)\n m_Dictionary(Key) = value\n End Set\nEnd Property\n</code></pre>\n" }, { "answer_id": 236548, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "<p>Your code sample strikes me as a very strange design and an abuse of what properties are intended for. Why not just an instance method <code>AddOrUpdateKey</code>:</p>\n\n<pre><code>Public Sub AddOrUpdateKey(ByVal Key As String, ByVal Value as Object)\n If m_Dictionary.ContainsKey(Key) Then\n m_Dictionary(Key) = Value\n Else\n m_Dictionary.Add(Key, Value)\n End If\nEnd Sub\n</code></pre>\n\n<p>Your property also returns <code>String.Empty</code> if the key does not exist, but claims to return an <code>Object</code>, nor a <code>String</code>.</p>\n" }, { "answer_id": 236731, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 2, "selected": false, "text": "<p>The \"proper\" way to do it in C# is to create child class specifically to access the collection. It should either hold the collection itself or have internal linkages to the parent class.</p>\n" }, { "answer_id": 236860, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 2, "selected": false, "text": "<p>Here is a sample for you (with changes along the lines of Grauenwolf's suggestions):</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\npublic class Test\n{\n public FakeIndexedPropertyInCSharp DictionaryElement { get; set; }\n\n public Test()\n {\n DictionaryElement = new FakeIndexedPropertyInCSharp();\n }\n\n public class FakeIndexedPropertyInCSharp\n {\n private Dictionary&lt;string, object&gt; m_Dictionary = new Dictionary&lt;string, object&gt;();\n\n public object this[string index]\n {\n get \n {\n object result;\n return m_Dictionary.TryGetValue(index, out result) ? result : null;\n }\n set \n {\n m_Dictionary[index] = value; \n }\n }\n }\n\n\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Test t = new Test();\n t.DictionaryElement[\"hello\"] = \"world\";\n Console.WriteLine(t.DictionaryElement[\"hello\"]);\n }\n}\n</code></pre>\n" }, { "answer_id": 238161, "author": "Javier", "author_id": 31434, "author_profile": "https://Stackoverflow.com/users/31434", "pm_score": 0, "selected": false, "text": "<p>Thanks Konrad, Alan, Grauenwolf, </p>\n\n<p>In conclusion, I can't use C# properties exactly in the same way that in VB.NET... :_( Anyway, your answers has been very usefull to me, and I´ll probably take this ideas to my C# code.</p>\n\n<p>In addition to the answers to the properties question, there are other good points. For example, </p>\n\n<blockquote>\n <ul>\n <li><em>Use TryGetValue, it's faster. You query the dictionary twice.</em></li>\n <li><em>Your setter doesn't have to test whether the value already exists.</em></li>\n </ul>\n</blockquote>\n\n<p>Thanks Sören, too, using a method don't fits well in my initial aims, but thanks very much.</p>\n" }, { "answer_id": 6313390, "author": "Mark Jones", "author_id": 703178, "author_profile": "https://Stackoverflow.com/users/703178", "pm_score": 2, "selected": false, "text": "<p>A more general-purpose, safer, and reusable solution to your problem might be implementing a generic, \"parameterized\" property class, like this:</p>\n\n<pre><code> // Generic, parameterized (indexed) \"property\" template\n public class Property&lt;T&gt;\n {\n // The internal property value\n private T PropVal = default(T);\n\n // The indexed property get/set accessor \n // (Property&lt;T&gt;[index] = newvalue; value = Property&lt;T&gt;[index];)\n public T this[object key]\n {\n get { return PropVal; } // Get the value\n set { PropVal = value; } // Set the value\n }\n }\n</code></pre>\n\n<p>You could then implement any number of properties within your public class so that clients could set/get the properties with an index, descriptor, security key, or whatever, like this:</p>\n\n<pre><code> public class ParameterizedProperties\n {\n // Parameterized properties\n private Property&lt;int&gt; m_IntProp = new Property&lt;int&gt;();\n private Property&lt;string&gt; m_StringProp = new Property&lt;string&gt;();\n\n // Parameterized int property accessor for client access\n // (ex: ParameterizedProperties.PublicIntProp[index])\n public Property&lt;int&gt; PublicIntProp\n {\n get { return m_IntProp; }\n }\n\n // Parameterized string property accessor\n // (ex: ParameterizedProperties.PublicStringProp[index])\n public Property&lt;string&gt; PublicStringProp\n {\n get { return m_StringProp; }\n }\n }\n</code></pre>\n\n<p>Finally, client code would access your public class's \"parameterized\" properties like this:</p>\n\n<pre><code> ParameterizedProperties parmProperties = new ParameterizedProperties();\n parmProperties.PublicIntProp[1] = 100;\n parmProperties.PublicStringProp[1] = \"whatever\";\n int ival = parmProperties.PublicIntProp[1];\n string strVal = parmProperties.PublicStringProp[1];\n</code></pre>\n\n<p>Sure, this seems weird, but it definitely does the trick. Besides, from a client-code perspective, it's not weird at all -- it's simple and intuitive and acts just like real properties. It doesn't break any C# rules, nor is it incompatible with other .NET managed languages. And from the class-implementer's perspective, creating a reusable, generic, \"parameterized\" property template class makes component coding a relative breeze, as shown here.</p>\n\n<p>NOTE: You can always override the generic property class to provide custom processing, such as indexed lookup, security-controlled property access, or whatever-the-heck you want.</p>\n\n<p>Cheers!</p>\n\n<p>Mark Jones</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31434/" ]
I'd like to do the same in C#. Is there anyway of using properties in C# with parameters in the same way I've done with the parameter 'Key' in this VB.NET example? > > > ``` > Private Shared m_Dictionary As IDictionary(Of String, Object) = New Dictionary(Of String, Object) > > ``` > > ``` Public Shared Property DictionaryElement(ByVal Key As String) As Object Get If m_Dictionary.ContainsKey(Key) Then Return m_Dictionary(Key) Else Return [String].Empty End If End Get Set(ByVal value As Object) If m_Dictionary.ContainsKey(Key) Then m_Dictionary(Key) = value Else m_Dictionary.Add(Key, value) End If End Set End Property ``` Thanks
> > Is there anyway of using properties in C# with parameters > > > No. You only can provide the *default* property in C# with an argument, to model indexed access (as in a dictionary): ``` public T this[string key] { get { return m_Dictionary[key]; } set { m_Dictionary[key] = value; } } ``` Other properties can't have arguments. Use a function instead. By the way, it's recommented to do the same in VB so other .NET languages (C# …) can use your code. By the way, your code is unnecessarily complicated. Four things: * You don't need to escape the `String` identifier. Use the keyword directly. * Why not use `""`? * Use `TryGetValue`, it's faster. You query the dictionary twice. * Your setter doesn't have to test whether the value already exists. --- ``` Public Shared Property DictionaryElement(ByVal Key As String) As Object Get Dim ret As String If m_Dictionary.TryGetValue(Key, ret) Then Return ret Return "" ' Same as String.Empty! ' End Get Set(ByVal value As Object) m_Dictionary(Key) = value End Set End Property ```
236,533
<p>I want to be able to selectively copy a list of files and preserve their directory structure. The problem is that there are quite a few files that their path exceeds 256 character. How is this problem usually handled?</p> <p>Edit: I should make it clear that I only want to selectively copy files, not folders. I don't think robocopy can be efficiently used to copy an individual file and it's folder structure effectively.</p>
[ { "answer_id": 236536, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "<p>I wrote a VBscript that checks path length and calls <code>subst</code>, as soon as a certain threshold is reached. These calls are stacked on each other so that in the middle of a recursion, this layout exists:</p>\n\n<pre><code>C:\\a\\very\\long\\path\nsubst K: \"C:\\a\\very\\long\\path\"\n\nK:\\another\\very\\long\\path\nsubst L: \"K:\\another\\very\\long\\path\"\n\nL:\\yet\\another\\very\\long\\path\nsubst M: \"L:\\yet\\another\\very\\long\\path\"\n\nxcopy M:\\*.* \"D:\\target\"\n</code></pre>\n\n<p>This way with each level of subst, a shorter path is generated. It also means, that you must copy your folders sequentially, to be able check for long paths before you issue the copy command.</p>\n\n<p>Once all files in a folder are copied, the recursion does jump back one level (<code>subst /d</code>), freeing up one drive letter.</p>\n\n<p>Using 4-5 drive letters, that subst each other when the path gets to deep I had been able to copy paths that had lengths waaaaay over the MAX_PATH limit.</p>\n\n<hr>\n\n<p>EDIT</p>\n\n<p>This describes the general procedure of doing it with subst. How you do it depends on your needs, I always used that little subst trick in a minimal, \"solves this single problem\" way. </p>\n\n<p>For example, copying to an equally deep target path means you need another stack of subst'ed drive letters. </p>\n\n<p>Unpacking all .zip files within a single, deeply nested directory structure may require only on stack, but you need to shorten the threshold a bit to account for folders in the .zip, etc.</p>\n" }, { "answer_id": 236541, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "<p>Robocopy, part of the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd\" rel=\"nofollow noreferrer\">Windows Resource Kit</a>, is designed to handle such cases.</p>\n" }, { "answer_id": 236695, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>Do you want to implement the copy procedure for yourself? If so, did you try UNC paths? I never had to work with them, but put simple you use a prefix and the path can be much longer than MAX_PATH, as described <a href=\"http://msdn.microsoft.com/en-us/library/aa365247.aspx\" rel=\"nofollow noreferrer\">in this MSDN article</a>.</p>\n" }, { "answer_id": 236759, "author": "John Dyer", "author_id": 2862, "author_profile": "https://Stackoverflow.com/users/2862", "pm_score": 1, "selected": false, "text": "<p>A hack from the old days is to assign a drive letter to part of the directory. </p>\n\n<p>One option is the SUBST command. That will allow you to substitute a drive letter for a drive letter and path combination. I have seen this done in install packages to get a shorter version of the directory.</p>\n\n<p>Alternativly you can use a shared folder and map it to a drive letter. Or you can use the an administrative share.</p>\n\n<p>But really if you have code that you can run, then handling it there is much better that these hacks.</p>\n" }, { "answer_id": 3320216, "author": "gonsalu", "author_id": 144399, "author_profile": "https://Stackoverflow.com/users/144399", "pm_score": 0, "selected": false, "text": "<p>As Sören suggested, try Robocopy:</p>\n\n<pre><code>robocopy empty_dir base_nested_dir /purge\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469014/" ]
I want to be able to selectively copy a list of files and preserve their directory structure. The problem is that there are quite a few files that their path exceeds 256 character. How is this problem usually handled? Edit: I should make it clear that I only want to selectively copy files, not folders. I don't think robocopy can be efficiently used to copy an individual file and it's folder structure effectively.
I wrote a VBscript that checks path length and calls `subst`, as soon as a certain threshold is reached. These calls are stacked on each other so that in the middle of a recursion, this layout exists: ``` C:\a\very\long\path subst K: "C:\a\very\long\path" K:\another\very\long\path subst L: "K:\another\very\long\path" L:\yet\another\very\long\path subst M: "L:\yet\another\very\long\path" xcopy M:\*.* "D:\target" ``` This way with each level of subst, a shorter path is generated. It also means, that you must copy your folders sequentially, to be able check for long paths before you issue the copy command. Once all files in a folder are copied, the recursion does jump back one level (`subst /d`), freeing up one drive letter. Using 4-5 drive letters, that subst each other when the path gets to deep I had been able to copy paths that had lengths waaaaay over the MAX\_PATH limit. --- EDIT This describes the general procedure of doing it with subst. How you do it depends on your needs, I always used that little subst trick in a minimal, "solves this single problem" way. For example, copying to an equally deep target path means you need another stack of subst'ed drive letters. Unpacking all .zip files within a single, deeply nested directory structure may require only on stack, but you need to shorten the threshold a bit to account for folders in the .zip, etc.
236,538
<p>How do I get the directory where the rakefile.rb is located?</p> <p>I want to use this as my root directory to locate everything off.</p>
[ { "answer_id": 236554, "author": "TonyLa", "author_id": 1295, "author_profile": "https://Stackoverflow.com/users/1295", "pm_score": 2, "selected": false, "text": "<p>If this is a RoR app your Rakefile.rb should be in your RAILS_ROOT directory. So in any script you can specify file location like </p>\n\n<pre><code> config.load_paths += %W( #{RAILS_ROOT}/extras )\n</code></pre>\n" }, { "answer_id": 236557, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 6, "selected": true, "text": "<p>use <code>__FILE__</code> to get the file name then you can get the directory from there:</p>\n\n<p>in <code>test.rb</code></p>\n\n<pre><code>puts __FILE__\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>/users/foo/test.rb\n</code></pre>\n\n<p><code>__FILE__</code> resolves to the full path of the file it is in. </p>\n\n<p>Use this to get the dir name:</p>\n\n<pre><code>File.dirname(__FILE__)\n</code></pre>\n" }, { "answer_id": 260137, "author": "Artem Tikhomirov", "author_id": 2313, "author_profile": "https://Stackoverflow.com/users/2313", "pm_score": 5, "selected": false, "text": "<p>You can get it by calling <strong>application.original_dir</strong> method. In task you can achieve <em>application</em> object using <strong>application</strong> method on task object.</p>\n" }, { "answer_id": 810654, "author": "Gordon Hartley", "author_id": 12726, "author_profile": "https://Stackoverflow.com/users/12726", "pm_score": 3, "selected": false, "text": "<p>Why not just use Dir.pwd</p>\n\n<p>?</p>\n" }, { "answer_id": 51484507, "author": "David Moles", "author_id": 27358, "author_profile": "https://Stackoverflow.com/users/27358", "pm_score": 2, "selected": false, "text": "<p>As of Ruby 2 you can use <a href=\"https://bogdanvlviv.com/posts/ruby/with-__dir__-we-can-restore-order-in-the-universe.html\" rel=\"nofollow noreferrer\"><code>__dir__</code> instead of <code>File.dirname(__FILE__)</code></a> to get the directory that contains the current script.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11755/" ]
How do I get the directory where the rakefile.rb is located? I want to use this as my root directory to locate everything off.
use `__FILE__` to get the file name then you can get the directory from there: in `test.rb` ``` puts __FILE__ ``` output: ``` /users/foo/test.rb ``` `__FILE__` resolves to the full path of the file it is in. Use this to get the dir name: ``` File.dirname(__FILE__) ```
236,555
<p>I built an application which displays the records from database in the window and checks the the database for new records every couple of seconds. The problem is that the window blinks each time I check for new records and I want to fix it. I have tried to compare the old datatable with the new one and refresh only if they are different. Does anyone know what is the best practice for such cases? I tried to do it the following way but it doesn't work:</p> <pre><code>private bool GetBelongingMessages() { bool result = false; DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID); if(dtTemp != dtMessages) { dtMessages = dtTemp; result = true; } else { result = false; } return result; } </code></pre>
[ { "answer_id": 236577, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": true, "text": "<p>First off, it's important to recognize that what you're comparing in your code is the <em>references</em> of the datatables, not the <em>contents</em> of the datatables. In order to determine if both datatables have the same contents, you're going to have to loop through all of the rows and columns and see if they're equal:</p>\n\n<pre><code>//This assumes the datatables have the same schema...\n public bool DatatablesAreSame(DataTable t1, DataTable t2) { \n if (t1.Rows.Count != t2.Rows.Count)\n return false;\n\n foreach (DataColumn dc in t1.Columns) {\n for (int i = 0; i &lt; t1.Rows.Count; i++) {\n if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {\n return false;\n }\n }\n }\n return true;\n }\n</code></pre>\n" }, { "answer_id": 236623, "author": "Niko Gamulin", "author_id": 22996, "author_profile": "https://Stackoverflow.com/users/22996", "pm_score": 0, "selected": false, "text": "<p>You have to cast objects t1.Rows[i][dc.ColumnName] and t1.Rows[i][dc.ColumnName] otherwise the statement t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName] is always true. I modified the code the following way:</p>\n\n<pre><code>for(int i = 0; i &lt; t1.Rows.Count; i++)\n {\n if((string)t1.Rows[i][1] != (string)t2.Rows[i][1])\n return false;\n }\n</code></pre>\n\n<p>and it works but it's not an elegant solution.</p>\n" }, { "answer_id": 761872, "author": "FlyinFish", "author_id": 88376, "author_profile": "https://Stackoverflow.com/users/88376", "pm_score": 1, "selected": false, "text": "<p>I've been trying to find a way to do DataTable comparison for a while and ended up writing up my own function, here is what I got:</p>\n\n<pre><code>bool tablesAreIdentical = true;\n\n// loop through first table\nforeach (DataRow row in firstTable.Rows)\n{\n foundIdenticalRow = false;\n\n // loop through tempTable to find an identical row\n foreach (DataRow tempRow in tempTable.Rows)\n {\n allFieldsAreIdentical = true;\n\n // compare fields, if any fields are different move on to next row in tempTable\n for (int i = 0; i &lt; row.ItemArray.Length &amp;&amp; allFieldsAreIdentical; i++)\n {\n if (!row[i].Equals(tempRow[i]))\n {\n allFieldsAreIdentical = false;\n }\n }\n\n // if an identical row is found, remove this row from tempTable \n // (in case of duplicated row exist in firstTable, so tempTable needs\n // to have the same number of duplicated rows to be considered equivalent)\n // and move on to next row in firstTable\n if (allFieldsAreIdentical)\n {\n tempTable.Rows.Remove(tempRow);\n foundIdenticalRow = true;\n break;\n }\n }\n // if no identical row is found for current row in firstTable, \n // the two tables are different\n if (!foundIdenticalRow)\n {\n tablesAreIdentical = false;\n break;\n }\n}\n\nreturn tablesAreIdentical;\n</code></pre>\n\n<p>Compared to Dave Markle's solution, mine treats two table with same records but in different orders as identical. Hope this helps whoever stumbles upon this thread again.</p>\n" }, { "answer_id": 18525907, "author": "Ganesh Rana", "author_id": 2515476, "author_profile": "https://Stackoverflow.com/users/2515476", "pm_score": 0, "selected": false, "text": "<pre><code> public Boolean CompareDataTables(DataTable table1, DataTable table2)\n {\n bool flag = true;\n DataRow[] row3 = table2.Select();\n int i = 0;// row3.Length;\n if (table1.Rows.Count == table2.Rows.Count)\n {\n foreach (DataRow row1 in table1.Rows)\n {\n if (!row1.ItemArray.SequenceEqual(row3[i].ItemArray))\n {\n flag = false;\n break;\n }\n i++;\n }\n\n }\n else\n {\n flag = false;\n }\n return flag;\n }\n</code></pre>\n\n<p>// here this function will gave boolean as result return true if both are same else return false if both are not same</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
I built an application which displays the records from database in the window and checks the the database for new records every couple of seconds. The problem is that the window blinks each time I check for new records and I want to fix it. I have tried to compare the old datatable with the new one and refresh only if they are different. Does anyone know what is the best practice for such cases? I tried to do it the following way but it doesn't work: ``` private bool GetBelongingMessages() { bool result = false; DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID); if(dtTemp != dtMessages) { dtMessages = dtTemp; result = true; } else { result = false; } return result; } ```
First off, it's important to recognize that what you're comparing in your code is the *references* of the datatables, not the *contents* of the datatables. In order to determine if both datatables have the same contents, you're going to have to loop through all of the rows and columns and see if they're equal: ``` //This assumes the datatables have the same schema... public bool DatatablesAreSame(DataTable t1, DataTable t2) { if (t1.Rows.Count != t2.Rows.Count) return false; foreach (DataColumn dc in t1.Columns) { for (int i = 0; i < t1.Rows.Count; i++) { if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) { return false; } } } return true; } ```
236,575
<p>Given an EmployeeId, how can I construct a Linq to Sql query to find all of the ancestors of the employee? Each EmployeeId has an associated SupervisorId (see below).</p> <p>For example, a query of the ancestors for EmployeeId 6 (Frank Black) should return Jane Doe, Bob Smith, Joe Bloggs, and Head Honcho.</p> <p>If necessary, I can cache the list of all employees to improve performance.</p> <p><strong>UPDATE:</strong></p> <p>I've created the following crude method to accomplish the task. It traverses the employee.Supervisor relationship all the way to the root node. However, this will issue one database call for each employee. Anyone have a more succinct or more performant method? Thanks.</p> <pre><code>private List&lt;Employee&gt; GetAncestors(int EmployeeId) { List&lt;Employee&gt; emps = new List&lt;Employee&gt;(); using (L2STestDataContext dc = new L2STestDataContext()) { Employee emp = dc.Employees.FirstOrDefault(p =&gt; p.EmployeeId == EmployeeId); if (emp != null) { while (emp.Supervisor != null) { emps.Add(emp.Supervisor); emp = emp.Supervisor; } } } return emps; } </code></pre>
[ { "answer_id": 236577, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": true, "text": "<p>First off, it's important to recognize that what you're comparing in your code is the <em>references</em> of the datatables, not the <em>contents</em> of the datatables. In order to determine if both datatables have the same contents, you're going to have to loop through all of the rows and columns and see if they're equal:</p>\n\n<pre><code>//This assumes the datatables have the same schema...\n public bool DatatablesAreSame(DataTable t1, DataTable t2) { \n if (t1.Rows.Count != t2.Rows.Count)\n return false;\n\n foreach (DataColumn dc in t1.Columns) {\n for (int i = 0; i &lt; t1.Rows.Count; i++) {\n if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {\n return false;\n }\n }\n }\n return true;\n }\n</code></pre>\n" }, { "answer_id": 236623, "author": "Niko Gamulin", "author_id": 22996, "author_profile": "https://Stackoverflow.com/users/22996", "pm_score": 0, "selected": false, "text": "<p>You have to cast objects t1.Rows[i][dc.ColumnName] and t1.Rows[i][dc.ColumnName] otherwise the statement t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName] is always true. I modified the code the following way:</p>\n\n<pre><code>for(int i = 0; i &lt; t1.Rows.Count; i++)\n {\n if((string)t1.Rows[i][1] != (string)t2.Rows[i][1])\n return false;\n }\n</code></pre>\n\n<p>and it works but it's not an elegant solution.</p>\n" }, { "answer_id": 761872, "author": "FlyinFish", "author_id": 88376, "author_profile": "https://Stackoverflow.com/users/88376", "pm_score": 1, "selected": false, "text": "<p>I've been trying to find a way to do DataTable comparison for a while and ended up writing up my own function, here is what I got:</p>\n\n<pre><code>bool tablesAreIdentical = true;\n\n// loop through first table\nforeach (DataRow row in firstTable.Rows)\n{\n foundIdenticalRow = false;\n\n // loop through tempTable to find an identical row\n foreach (DataRow tempRow in tempTable.Rows)\n {\n allFieldsAreIdentical = true;\n\n // compare fields, if any fields are different move on to next row in tempTable\n for (int i = 0; i &lt; row.ItemArray.Length &amp;&amp; allFieldsAreIdentical; i++)\n {\n if (!row[i].Equals(tempRow[i]))\n {\n allFieldsAreIdentical = false;\n }\n }\n\n // if an identical row is found, remove this row from tempTable \n // (in case of duplicated row exist in firstTable, so tempTable needs\n // to have the same number of duplicated rows to be considered equivalent)\n // and move on to next row in firstTable\n if (allFieldsAreIdentical)\n {\n tempTable.Rows.Remove(tempRow);\n foundIdenticalRow = true;\n break;\n }\n }\n // if no identical row is found for current row in firstTable, \n // the two tables are different\n if (!foundIdenticalRow)\n {\n tablesAreIdentical = false;\n break;\n }\n}\n\nreturn tablesAreIdentical;\n</code></pre>\n\n<p>Compared to Dave Markle's solution, mine treats two table with same records but in different orders as identical. Hope this helps whoever stumbles upon this thread again.</p>\n" }, { "answer_id": 18525907, "author": "Ganesh Rana", "author_id": 2515476, "author_profile": "https://Stackoverflow.com/users/2515476", "pm_score": 0, "selected": false, "text": "<pre><code> public Boolean CompareDataTables(DataTable table1, DataTable table2)\n {\n bool flag = true;\n DataRow[] row3 = table2.Select();\n int i = 0;// row3.Length;\n if (table1.Rows.Count == table2.Rows.Count)\n {\n foreach (DataRow row1 in table1.Rows)\n {\n if (!row1.ItemArray.SequenceEqual(row3[i].ItemArray))\n {\n flag = false;\n break;\n }\n i++;\n }\n\n }\n else\n {\n flag = false;\n }\n return flag;\n }\n</code></pre>\n\n<p>// here this function will gave boolean as result return true if both are same else return false if both are not same</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24358/" ]
Given an EmployeeId, how can I construct a Linq to Sql query to find all of the ancestors of the employee? Each EmployeeId has an associated SupervisorId (see below). For example, a query of the ancestors for EmployeeId 6 (Frank Black) should return Jane Doe, Bob Smith, Joe Bloggs, and Head Honcho. If necessary, I can cache the list of all employees to improve performance. **UPDATE:** I've created the following crude method to accomplish the task. It traverses the employee.Supervisor relationship all the way to the root node. However, this will issue one database call for each employee. Anyone have a more succinct or more performant method? Thanks. ``` private List<Employee> GetAncestors(int EmployeeId) { List<Employee> emps = new List<Employee>(); using (L2STestDataContext dc = new L2STestDataContext()) { Employee emp = dc.Employees.FirstOrDefault(p => p.EmployeeId == EmployeeId); if (emp != null) { while (emp.Supervisor != null) { emps.Add(emp.Supervisor); emp = emp.Supervisor; } } } return emps; } ```
First off, it's important to recognize that what you're comparing in your code is the *references* of the datatables, not the *contents* of the datatables. In order to determine if both datatables have the same contents, you're going to have to loop through all of the rows and columns and see if they're equal: ``` //This assumes the datatables have the same schema... public bool DatatablesAreSame(DataTable t1, DataTable t2) { if (t1.Rows.Count != t2.Rows.Count) return false; foreach (DataColumn dc in t1.Columns) { for (int i = 0; i < t1.Rows.Count; i++) { if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) { return false; } } } return true; } ```
236,593
<p>How to do svn update of multiple files located across different directories ? </p> <p>For committing multiple files from different directories, we can put them all up in a text file and give that file as an argument to svn commit and it will happily commit all those files. But <b>update</b> ?</p> <p><b>EDIT:</b> Mr. Fooz's answer is definitely an option whereby I can create a .bat or .sh file with all the svn updates. But I would like to know if there are any special arguments that svn provide that can be used instead of a file with loads of svn update commands in it. Please note that the file that is used by svn commit contains <i>only</i> the filenames and no svn commands. </p>
[ { "answer_id": 236600, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 1, "selected": false, "text": "<p>If you don't mind creating a separate file with a canned list of directories, you could make it a shell script or .bat file (depending on your platform) and place N individual svn update calls in it.</p>\n" }, { "answer_id": 236615, "author": "Jon Topper", "author_id": 6945, "author_profile": "https://Stackoverflow.com/users/6945", "pm_score": 0, "selected": false, "text": "<p>THe fact that you even want to do this suggests to me that you're perhaps not using subversion particularly sensibly.</p>\n" }, { "answer_id": 236626, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "<p>You can specify multiple <em>folders</em> in the update command:</p>\n\n<pre><code>svn update docs foo/bar/ /repos/bar\n</code></pre>\n\n<p>If you are really trying to limit yourself to updating individual files I have to agree with <a href=\"https://stackoverflow.com/questions/236593/svn-update-of-multiple-files#236615\">Jon Topper</a> that you might be off track.</p>\n" }, { "answer_id": 236992, "author": "rjray", "author_id": 6421, "author_profile": "https://Stackoverflow.com/users/6421", "pm_score": 4, "selected": true, "text": "<p>Given that there are valid reasons for selectively updating from a repository when there are a lot of downstream changes available, my question would be whether you're trying to do this on a UNIX/Linux/etc. system or Windows. If Windows, I don't know how to do an equivalent of the following:</p>\n\n<pre><code>svn update `cat list_of_files`\n</code></pre>\n\n<p>(There are corner-cases, similar to running \"find ... | xargs cmd ...\", where spaces or shell-sensitive characters in the file names could cause problems. You'll have to deal with those by properly escaping such problem-characters.)</p>\n\n<p>If, for some frightening reason, your list of files is so astronomically-large that it breaks the shell command-line-length limit, you can do this instead:</p>\n\n<pre><code>cat list_of_files | xargs svn update\n</code></pre>\n\n<p>Two things to keep in mind while using either of these:</p>\n\n<ol>\n<li>All file names will have to be either absolute, or relative to the point you're running the command from.</li>\n<li>If one of the \"files\" in your list is actually a directory, <strong><em>all</em></strong> the files in that directory that have changes available will be updated.</li>\n</ol>\n" }, { "answer_id": 236999, "author": "mithrandi", "author_id": 31490, "author_profile": "https://Stackoverflow.com/users/31490", "pm_score": 3, "selected": false, "text": "<p>Subversion has a \"changelists\" feature (new in 1.5, I believe) that allows you to define a named changelist by doing:</p>\n\n<pre><code>svn changelist yourlist file1 file2 file3 ...\n</code></pre>\n\n<p>Once defined, you can pass <code>--changelist</code> to several commands, including <code>svn update</code>, and they will only operate on the files associated with that changelist. For example:</p>\n\n<pre><code>svn update --changelist yourlist\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27474/" ]
How to do svn update of multiple files located across different directories ? For committing multiple files from different directories, we can put them all up in a text file and give that file as an argument to svn commit and it will happily commit all those files. But **update** ? **EDIT:** Mr. Fooz's answer is definitely an option whereby I can create a .bat or .sh file with all the svn updates. But I would like to know if there are any special arguments that svn provide that can be used instead of a file with loads of svn update commands in it. Please note that the file that is used by svn commit contains *only* the filenames and no svn commands.
Given that there are valid reasons for selectively updating from a repository when there are a lot of downstream changes available, my question would be whether you're trying to do this on a UNIX/Linux/etc. system or Windows. If Windows, I don't know how to do an equivalent of the following: ``` svn update `cat list_of_files` ``` (There are corner-cases, similar to running "find ... | xargs cmd ...", where spaces or shell-sensitive characters in the file names could cause problems. You'll have to deal with those by properly escaping such problem-characters.) If, for some frightening reason, your list of files is so astronomically-large that it breaks the shell command-line-length limit, you can do this instead: ``` cat list_of_files | xargs svn update ``` Two things to keep in mind while using either of these: 1. All file names will have to be either absolute, or relative to the point you're running the command from. 2. If one of the "files" in your list is actually a directory, ***all*** the files in that directory that have changes available will be updated.
236,599
<p>I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates).</p> <p>How can I create a Unit Test to be sure that my object is safely serializable?</p>
[ { "answer_id": 236602, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 5, "selected": true, "text": "<p>I have this in some unit test here at job:</p>\n\n<pre><code>MyComplexObject dto = new MyComplexObject();\nMemoryStream mem = new MemoryStream();\nBinaryFormatter b = new BinaryFormatter();\ntry\n{\n b.Serialize(mem, dto);\n}\ncatch (Exception ex)\n{\n Assert.Fail(ex.Message);\n}\n</code></pre>\n\n<p>Might help you... maybe other method can be better but this one works well.</p>\n" }, { "answer_id": 236608, "author": "Scott Weinstein", "author_id": 25201, "author_profile": "https://Stackoverflow.com/users/25201", "pm_score": 4, "selected": false, "text": "<p>In addition to the test above - which makes sure the serializer will accept your object, you need to do a round-trip test. Deserialize the results back to a new object and make sure the two instances are equivalent.</p>\n" }, { "answer_id": 236636, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>serialize the object (to memory or disk), deserialize it, use reflection to compare the two, then <em>run all of the unit tests for that object again</em> (except serialization of course)</p>\n\n<p>this assumes that your unit tests can accept an object as a target instead of making their own</p>\n" }, { "answer_id": 236698, "author": "GeverGever", "author_id": 31460, "author_profile": "https://Stackoverflow.com/users/31460", "pm_score": 6, "selected": false, "text": "<p>Here is a generic way:</p>\n\n<pre><code>public static Stream Serialize(object source)\n{\n IFormatter formatter = new BinaryFormatter();\n Stream stream = new MemoryStream();\n formatter.Serialize(stream, source);\n return stream;\n}\n\npublic static T Deserialize&lt;T&gt;(Stream stream)\n{\n IFormatter formatter = new BinaryFormatter();\n stream.Position = 0;\n return (T)formatter.Deserialize(stream);\n}\n\npublic static T Clone&lt;T&gt;(object source)\n{\n return Deserialize&lt;T&gt;(Serialize(source));\n}\n</code></pre>\n" }, { "answer_id": 4071843, "author": "Zaid Masud", "author_id": 374420, "author_profile": "https://Stackoverflow.com/users/374420", "pm_score": 2, "selected": false, "text": "<p>Here is a solution that recursively uses IsSerializable to check that the object and all its properties are Serializable.</p>\n\n<pre><code> private static void AssertThatTypeAndPropertiesAreSerializable(Type type)\n {\n // base case\n if (type.IsValueType || type == typeof(string)) return;\n\n Assert.IsTrue(type.IsSerializable, type + \" must be marked [Serializable]\");\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 AssertThatTypeAndPropertiesAreSerializable(genericArgument);\n }\n }\n else if (propertyInfo.GetType() != type) // base case for circularly referenced properties\n AssertThatTypeAndPropertiesAreSerializable(propertyInfo.PropertyType);\n }\n }\n</code></pre>\n" }, { "answer_id": 4464479, "author": "erikkallen", "author_id": 47161, "author_profile": "https://Stackoverflow.com/users/47161", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, you can't really test for this. Imagine this case:</p>\n\n<pre><code>[Serializable]\nclass Foo {\n public Bar MyBar { get; set; }\n}\n\n[Serializable]\nclass Bar {\n int x;\n}\n\nclass DerivedBar : Bar {\n}\n\npublic void TestSerializeFoo() {\n Serialize(new Foo()); // OK\n Serialize(new Foo() { MyBar = new Bar() }; // OK\n Serialize(new Foo() { MyBar = new DerivedBar() }; // Boom\n}\n</code></pre>\n" }, { "answer_id": 44877512, "author": "David Keaveny", "author_id": 319980, "author_profile": "https://Stackoverflow.com/users/319980", "pm_score": 2, "selected": false, "text": "<p>Probably a bit late in the day, but if you are using the <a href=\"http://fluentassertions.com/documentation.html\" rel=\"nofollow noreferrer\">FluentAssertions</a> library, then it has custom assertions for XML serialization, binary serialization, and data contract serialization.</p>\n\n<pre><code>theObject.Should().BeXmlSerializable();\ntheObject.Should().BeBinarySerializable();\ntheObject.Should().BeDataContractSerializable();\n\ntheObject.Should().BeBinarySerializable&lt;MyClass&gt;(\n options =&gt; options.Excluding(s =&gt; s.SomeNonSerializableProperty));\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21386/" ]
I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates). How can I create a Unit Test to be sure that my object is safely serializable?
I have this in some unit test here at job: ``` MyComplexObject dto = new MyComplexObject(); MemoryStream mem = new MemoryStream(); BinaryFormatter b = new BinaryFormatter(); try { b.Serialize(mem, dto); } catch (Exception ex) { Assert.Fail(ex.Message); } ``` Might help you... maybe other method can be better but this one works well.
236,624
<p>For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?</p> <pre><code>&lt;div id='header-inner'&gt; &lt;div class='titlewrapper'&gt; &lt;h1 class='title'&gt; Some text I want to change &lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Thanks!</p>
[ { "answer_id": 236655, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 6, "selected": true, "text": "<pre><code>function findFirstDescendant(parent, tagname)\n{\n parent = document.getElementById(parent);\n var descendants = parent.getElementsByTagName(tagname);\n if ( descendants.length )\n return descendants[0];\n return null;\n}\n\nvar header = findFirstDescendant(\"header-inner\", \"h1\");\n</code></pre>\n\n<p>Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on <code>descendants</code> to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).</p>\n" }, { "answer_id": 236659, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 3, "selected": false, "text": "<p>If you are sure that there is only one H1 element in your div:</p>\n\n<pre><code>var parent = document.getElementById('header-inner');\nvar element = parent.GetElementsByTagName('h1')[0];\n</code></pre>\n\n<p>Going through descendants,as Shog9 showed, is a good way too.</p>\n" }, { "answer_id": 236664, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 0, "selected": false, "text": "<p>Here I get the H1 elements value in a div where the H1 element which has CSS class=\"myheader\":</p>\n\n<pre><code>var nodes = document.getElementById(\"mydiv\")\n .getElementsByTagName(\"H1\");\n\nfor(i=0;i&lt;nodes.length;i++)\n{\n if(nodes.item(i).getAttribute(\"class\") == \"myheader\")\n alert(nodes.item(i).innerHTML);\n} \n</code></pre>\n\n<p>Here is the markup:</p>\n\n<pre><code>&lt;div id=\"mydiv\"&gt;\n &lt;h1 class=\"myheader\"&gt;Hello&lt;/h1&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>I would also recommend to use <a href=\"http://www.jquery.com\" rel=\"nofollow noreferrer\">jQuery</a> if you need a heavy parsing for your DOM.</p>\n" }, { "answer_id": 236667, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 1, "selected": false, "text": "<p>The simplest way of doing it with your current markup is:</p>\n\n<p><code>document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';</code></p>\n\n<p>This assumes your H1 tag is always the first one within the <code>'header-inner'</code> element.</p>\n" }, { "answer_id": 236671, "author": "RogueOne", "author_id": 31019, "author_profile": "https://Stackoverflow.com/users/31019", "pm_score": 1, "selected": false, "text": "<p>To get the children nodes, use <code>obj.childNodes</code>, that returns a collection object.</p>\n\n<p>To get the first child, use <code>list[0]</code>, that returns a node.</p>\n\n<p>So the complete code should be:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var div = document.getElementById('header-inner');\nvar divTitleWrapper = div.childNodes[0];\nvar h1 = divTitleWrapper.childNodes[0];\n</code></pre>\n\n<p>If you want to iterate over all the children, comparing if they are of class “title”, you can iterate using a for loop and the <code>className</code> attribute.</p>\n\n<p>The code should be:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var h1 = null;\nvar nodeList = divTitleWrapper.childNodes;\nfor (i =0;i &lt; nodeList.length;i++){\n var node = nodeList[i];\n if(node.className == 'title' &amp;&amp; node.tagName == 'H1'){\n h1 = node;\n }\n}\n</code></pre>\n" }, { "answer_id": 236682, "author": "patmortech", "author_id": 19090, "author_profile": "https://Stackoverflow.com/users/19090", "pm_score": 3, "selected": false, "text": "<p>If you were to use <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a> as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):</p>\n\n<pre><code>var element = $('#header-inner h1');\n</code></pre>\n\n<p>Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.</p>\n" }, { "answer_id": 72916985, "author": "Heretic Monkey", "author_id": 215552, "author_profile": "https://Stackoverflow.com/users/215552", "pm_score": 2, "selected": false, "text": "<p>It's been a few years since this question was asked and answered. In modern DOM, you could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector\" rel=\"nofollow noreferrer\"><code>querySelector</code></a>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.querySelector('#header-inner h1').textContent = 'Different text';</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id='header-inner'&gt; \n &lt;div class='titlewrapper'&gt; \n &lt;h1 class='title'&gt; \n Some text I want to change\n &lt;/h1&gt; \n &lt;/div&gt; \n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311500/" ]
For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)? ``` <div id='header-inner'> <div class='titlewrapper'> <h1 class='title'> Some text I want to change </h1> </div> </div> ``` Thanks!
``` function findFirstDescendant(parent, tagname) { parent = document.getElementById(parent); var descendants = parent.getElementsByTagName(tagname); if ( descendants.length ) return descendants[0]; return null; } var header = findFirstDescendant("header-inner", "h1"); ``` Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on `descendants` to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).
236,629
<p>I may be in the minority here, but I very much enjoy <a href="https://perldoc.perl.org/perlform" rel="nofollow noreferrer">Perl's formats</a>. I especially like being able to wrap a long piece of text within a column (&quot;~~ ^&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot; type stuff). Are there any other programming languages that have similar features, or libraries that implement similar features? I am especially interested in any libraries that implement something similar for Ruby, but I'm also curious about any other options.</p>
[ { "answer_id": 236651, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 2, "selected": false, "text": "<p>There is the <a href=\"http://gigamonkeys.com/book/a-few-format-recipes.html\" rel=\"nofollow noreferrer\">Lisp <code>(format ...)</code> function</a>. It supports looping, conditionals, and a whole bunch of other fun stuff.</p>\n\n<p>for example (copied from above link):</p>\n\n<pre><code>(defparameter *english-list*\n \"~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~}\")\n\n(format nil *english-list* '()) ;' ==&gt; \"\"\n(format nil *english-list* '(1)) ;' ==&gt; \"1\"\n(format nil *english-list* '(1 2)) ;' ==&gt; \"1 and 2\"\n(format nil *english-list* '(1 2 3)) ;' ==&gt; \"1, 2, and 3\"\n(format nil *english-list* '(1 2 3 4));' ==&gt; \"1, 2, 3, and 4\"\n</code></pre>\n" }, { "answer_id": 236654, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://formatr.rubyforge.org/\" rel=\"noreferrer\">FormatR</a> provides Perl-like formats for Ruby.</p>\n\n<p>Here is an example from the documentation:</p>\n\n<pre><code>require \"formatr\"\ninclude FormatR\n\ntop_ex = &lt;&lt;DOT\n Piggy Locations for @&lt;&lt; @#, @###\n month, day, year\n\nNumber: location toe size\n-------------------------------------------\nDOT\n\nex = &lt;&lt;TOD\n@) @&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; @#.##\nnum, location, toe_size\nTOD\n\nbody_fmt = Format.new (top_ex, ex)\n\nbody_fmt.setPageLength(10)\nnum = 1\n\nmonth = \"Sep\"\nday = 18\nyear = 2001\n[\"Market\", \"Home\", \"Eating Roast Beef\", \"Having None\", \"On the way home\"].each {|location|\n toe_size = (num * 3.5)\n body_fmt.printFormat(binding)\n num += 1\n}\n</code></pre>\n\n<p>Which produces:</p>\n\n<pre><code> Piggy Locations for Sep 18, 2001\n\nNumber: location toe size\n-------------------------------------------\n1) Market 3.50\n2) Home 7.00\n3) Eating Roast Beef 10.50\n4) Having None 14.00\n5) On the way home 17.50\n</code></pre>\n" }, { "answer_id": 237031, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 4, "selected": false, "text": "<p>I seem to recall something similar in Fortran when I used it many years ago (however, it may well have have been a third-party library).</p>\n<p>As for other options in Perl, have a look at <a href=\"http://search.cpan.org/perldoc/Perl6::Form\" rel=\"nofollow noreferrer\"><code>Perl6::Form</code></a>.</p>\n<p>The <code>form</code> function replaces <a href=\"http://perldoc.perl.org/functions/format.html\" rel=\"nofollow noreferrer\"><code>format</code></a> in Perl6. Damian Conway in &quot;<a href=\"http://google.com/search?btnI=&amp;q=%22Perl+Best+Practices%22\" rel=\"nofollow noreferrer\">Perl Best Practices</a>&quot; recommends using <a href=\"http://search.cpan.org/perldoc/Perl6::Form\" rel=\"nofollow noreferrer\"><code>Perl6::Form</code></a> with Perl5 citing the following issues with <a href=\"http://perldoc.perl.org/perlform.html\" rel=\"nofollow noreferrer\"><code>format</code></a>....</p>\n<ul>\n<li>statically defined</li>\n<li>rely on global variables for configuration and pkg variables for data they format on</li>\n<li>uses named filehandles (only)</li>\n<li>not recursive or re-entrant</li>\n</ul>\n<p>Here is a <a href=\"http://search.cpan.org/perldoc/Perl6::Form\" rel=\"nofollow noreferrer\"><code>Perl6::Form</code></a> variation on the Ruby example by Robert Gamble....</p>\n<pre><code>use Perl6::Form;\n\nmy ( $month, $day, $year ) = qw'Sep 18 2001';\nmy ( $num, $numb, $location, $toe_size );\n\nfor ( &quot;Market&quot;, &quot;Home&quot;, &quot;Eating Roast Beef&quot;, &quot;Having None&quot;, &quot;On the way home&quot; ) {\n push @$numb, ++$num;\n push @$location, $_;\n push @$toe_size, $num * 3.5;\n}\n\nprint form\n ' Piggy Locations for {&gt;&gt;&gt;}{&gt;&gt;}, {&lt;&lt;&lt;&lt;}',\n $month, $day, $year ,\n &quot;&quot;,\n ' Number: location toe size',\n ' --------------------------------------',\n '{]}) {[[[[[[[[[[[[[[[} {].0} ',\n $numb, $location, $toe_size;\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5922/" ]
I may be in the minority here, but I very much enjoy [Perl's formats](https://perldoc.perl.org/perlform). I especially like being able to wrap a long piece of text within a column ("~~ ^<<<<<<<<<<<<<<<<" type stuff). Are there any other programming languages that have similar features, or libraries that implement similar features? I am especially interested in any libraries that implement something similar for Ruby, but I'm also curious about any other options.
[FormatR](http://formatr.rubyforge.org/) provides Perl-like formats for Ruby. Here is an example from the documentation: ``` require "formatr" include FormatR top_ex = <<DOT Piggy Locations for @<< @#, @### month, day, year Number: location toe size ------------------------------------------- DOT ex = <<TOD @) @<<<<<<<<<<<<<<<< @#.## num, location, toe_size TOD body_fmt = Format.new (top_ex, ex) body_fmt.setPageLength(10) num = 1 month = "Sep" day = 18 year = 2001 ["Market", "Home", "Eating Roast Beef", "Having None", "On the way home"].each {|location| toe_size = (num * 3.5) body_fmt.printFormat(binding) num += 1 } ``` Which produces: ``` Piggy Locations for Sep 18, 2001 Number: location toe size ------------------------------------------- 1) Market 3.50 2) Home 7.00 3) Eating Roast Beef 10.50 4) Having None 14.00 5) On the way home 17.50 ```
236,632
<p>Please help me with a sanity check. Assuming a many-to-many relationship:</p> <p><a href="http://www.codingthewheel.com/pics/many_to_many.gif" rel="nofollow noreferrer">Post, PostTagAssoc, Tag http://www.codingthewheel.com/pics/many_to_many.gif</a></p> <p>What's the most succinct way (using LINQ to SQL) to get a result set showing, for <strong>each</strong> tag (or post), the aggregate number of posts (or tags) assigned to it?</p> <p>Thanks!</p>
[ { "answer_id": 236680, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "<pre><code> from pta in db.PostTagAssoc\n group pta by pta.PostID into t\n select new {PostID = t.Key, TagCount=t.Count()}\n</code></pre>\n" }, { "answer_id": 625608, "author": "netterdotter", "author_id": 59284, "author_profile": "https://Stackoverflow.com/users/59284", "pm_score": 0, "selected": false, "text": "<p>This will also show those posts with 0 tags, and is a bit clearer in my opinion.</p>\n\n<pre><code>from p in db.Post\nselect new {PostID = p.ID, TagCount = t.PostTagAssoc.Count}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Please help me with a sanity check. Assuming a many-to-many relationship: [Post, PostTagAssoc, Tag http://www.codingthewheel.com/pics/many\_to\_many.gif](http://www.codingthewheel.com/pics/many_to_many.gif) What's the most succinct way (using LINQ to SQL) to get a result set showing, for **each** tag (or post), the aggregate number of posts (or tags) assigned to it? Thanks!
``` from pta in db.PostTagAssoc group pta by pta.PostID into t select new {PostID = t.Key, TagCount=t.Count()} ```
236,644
<p>I created the setup project for the application and I can see that the later modifications of the configuration file (Application.exe.config) don't affect the application execution.</p> <p>I am developing an application with the database file included and I want to enable users to move the database file and modify connection strings.</p> <p>Does anyone know what's the best practice for the deployment of the application with the database file?</p>
[ { "answer_id": 236657, "author": "Alexandre Brisebois", "author_id": 18619, "author_profile": "https://Stackoverflow.com/users/18619", "pm_score": 0, "selected": false, "text": "<p>did you make sure to remove the settings default values? These are compiled and fetched from the dll and not from the config file.</p>\n" }, { "answer_id": 236822, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 3, "selected": true, "text": "<p>It should work, provided that you use the exact same connection string setting in your DB access DLL's Settings.settings file and in your application's config file.</p>\n\n<p>An example that works well for me:</p>\n\n<pre><code> &lt;connectionStrings&gt;\n &lt;add name=\"YourApp.Properties.Settings.DatabaseConnectionString\"\n connectionString=\"Data Source=localhost;Initial Catalog=xxx;Integrated Security=True;\"\n providerName=\"System.Data.SqlClient\" /&gt;\n &lt;/connectionStrings&gt;\n</code></pre>\n\n<p>When entered appropriately in both locations (ie. the dll's Settings.settings and the exe's App.config files), this does allow me to change the database connection in YourApp.exe.config before the app runs.</p>\n\n<p>(I assume you already know that you need to change the application's config file, as DLL's do not support the app.config mechanism directly.)</p>\n" }, { "answer_id": 240748, "author": "Will Rickards", "author_id": 290835, "author_profile": "https://Stackoverflow.com/users/290835", "pm_score": 1, "selected": false, "text": "<p>Have you checked out using a <a href=\"http://support.microsoft.com/kb/308426\" rel=\"nofollow noreferrer\">UDL file</a>?\nIf you save your connection string in the udl file, the user can change the connection via an interface by simply double clicking that file.\nYou can set your connection string in the app to point to the udl file.\nYou can also launch the udl interface programmatically if you want.\nThe only downside to these is if the user saves their password to the file, it is saved as plain text. But this isn't an issue if you are using windows authentication.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
I created the setup project for the application and I can see that the later modifications of the configuration file (Application.exe.config) don't affect the application execution. I am developing an application with the database file included and I want to enable users to move the database file and modify connection strings. Does anyone know what's the best practice for the deployment of the application with the database file?
It should work, provided that you use the exact same connection string setting in your DB access DLL's Settings.settings file and in your application's config file. An example that works well for me: ``` <connectionStrings> <add name="YourApp.Properties.Settings.DatabaseConnectionString" connectionString="Data Source=localhost;Initial Catalog=xxx;Integrated Security=True;" providerName="System.Data.SqlClient" /> </connectionStrings> ``` When entered appropriately in both locations (ie. the dll's Settings.settings and the exe's App.config files), this does allow me to change the database connection in YourApp.exe.config before the app runs. (I assume you already know that you need to change the application's config file, as DLL's do not support the app.config mechanism directly.)
236,668
<p>I have been slowly learning SQL the last few weeks. I've picked up all of the relational algebra and the basics of how relational databases work. What I'm trying to do now is learn how it's implemented.</p> <p>A stumbling block I've come across in this, is foreign keys in MySQL. I can't seem to find much about the other than that they exist in the <a href="http://en.wikipedia.org/wiki/InnoDB" rel="noreferrer">InnoDB</a> storage schema that MySQL has.</p> <p>What is a simple example of foreign keys implemented in MySQL?</p> <p>Here's part of a schema I wrote that doesn't seem to be working if you would rather point out my flaw than show me a working example.</p> <pre><code>CREATE TABLE `posts` ( `pID` bigint(20) NOT NULL auto_increment, `content` text NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `uID` bigint(20) NOT NULL, `wikiptr` bigint(20) default NULL, `cID` bigint(20) NOT NULL, PRIMARY KEY (`pID`), Foreign Key(`cID`) references categories, Foreign Key(`uID`) references users ) ENGINE=InnoDB; </code></pre>
[ { "answer_id": 236677, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html\" rel=\"nofollow noreferrer\">This</a> has some code showing how to create foreign keys by themselves, and in CREATE TABLE.</p>\n\n<p>Here's one of the simpler examples from that:</p>\n\n<pre><code>CREATE TABLE parent (\n id INT NOT NULL,\n PRIMARY KEY (id)\n) ENGINE=INNODB;\n\nCREATE TABLE child (\n id INT, \n parent_id INT,\n INDEX par_ind (parent_id),\n FOREIGN KEY (parent_id) REFERENCES parent(id)\n ON DELETE CASCADE\n) ENGINE=INNODB;\n</code></pre>\n" }, { "answer_id": 236684, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 6, "selected": true, "text": "<p>Assuming your categories and users table already exist and contain cID and uID respectively as primary keys, this should work:</p>\n\n<pre><code>CREATE TABLE `posts` (\n`pID` bigint(20) NOT NULL auto_increment,\n`content` text NOT NULL,\n`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n`uID` bigint(20) NOT NULL,\n`wikiptr` bigint(20) default NULL,\n`cID` bigint(20) NOT NULL,\nPRIMARY KEY (`pID`),\nForeign Key(`cID`) references categories(`cID`),\nForeign Key(`uID`) references users(`uID`)\n) ENGINE=InnoDB;\n</code></pre>\n\n<p>The column name is required in the <code>references</code> clause.</p>\n" }, { "answer_id": 236693, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>I agree with Robert. You are missing the name of the column in the references clause (and you should be getting the error 150). I'll add that you can check how the tables got created in reality with:</p>\n\n<pre><code>SHOW CREATE TABLE posts;\n</code></pre>\n" }, { "answer_id": 236750, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "<p><strong>Edited:</strong> Robert and Vinko state that you need to declare the name of the referenced column in the foreign key constraint. This is necessary in InnoDB, although in standard SQL you're permitted to omit the referenced column name if it's the same name in the parent table.</p>\n\n<p>One idiosyncrasy I've encountered in MySQL is that foreign key declaration will fail silently in several circumstances:</p>\n\n<ul>\n<li>Your MySQL installation doesn't include the innodb engine</li>\n<li>Your MySQL config file doesn't enable the innodb engine</li>\n<li>You don't declare your table with the ENGINE=InnoDB table modifier</li>\n<li>The foreign key column isn't exactly the same data type as the primary key column in the referenced table</li>\n</ul>\n\n<p>Unfortunately, MySQL gives no message that it has failed to create the foreign key constraint. It simply ignores the request, and creates the table without the foreign key (if you SHOW CREATE TABLE posts, you may see no foreign key declaration). I've always thought this is a bad feature of MySQL!</p>\n\n<p><strong>Tip:</strong> the integer argument for integer data types (e.g. BIGINT(20)) is not necessary. It has nothing to do with the storage size or range of the column. BIGINT is always the same size regardless of the argument you give it. The number refers to how many digits MySQL will pad the column if you use the ZEROFILL column modifier.</p>\n" }, { "answer_id": 236931, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": false, "text": "<p>The previous answers deal with the foreign key constraint. While the foreign key constraint is definitely useful to maintain referential integrity, the concept of \"foreign key\" itself is fundamental to the relational model of data, regardless of whether you use the constraint or not.</p>\n\n<p>Whenever you do an <a href=\"http://en.wikipedia.org/wiki/Join_%28SQL%29#Equi-join\" rel=\"nofollow noreferrer\">equijoin</a>, you are equating a foreign key to something, usually the key it references. Example:</p>\n\n<pre><code>select *\nfrom \n Students\ninner join\n StudentCourses\non Students.StudentId = StudentCourses.StudentId\n</code></pre>\n\n<p>StudentCourses.StudentId is a foreign key referencing Students.StudentId.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1063/" ]
I have been slowly learning SQL the last few weeks. I've picked up all of the relational algebra and the basics of how relational databases work. What I'm trying to do now is learn how it's implemented. A stumbling block I've come across in this, is foreign keys in MySQL. I can't seem to find much about the other than that they exist in the [InnoDB](http://en.wikipedia.org/wiki/InnoDB) storage schema that MySQL has. What is a simple example of foreign keys implemented in MySQL? Here's part of a schema I wrote that doesn't seem to be working if you would rather point out my flaw than show me a working example. ``` CREATE TABLE `posts` ( `pID` bigint(20) NOT NULL auto_increment, `content` text NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `uID` bigint(20) NOT NULL, `wikiptr` bigint(20) default NULL, `cID` bigint(20) NOT NULL, PRIMARY KEY (`pID`), Foreign Key(`cID`) references categories, Foreign Key(`uID`) references users ) ENGINE=InnoDB; ```
Assuming your categories and users table already exist and contain cID and uID respectively as primary keys, this should work: ``` CREATE TABLE `posts` ( `pID` bigint(20) NOT NULL auto_increment, `content` text NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `uID` bigint(20) NOT NULL, `wikiptr` bigint(20) default NULL, `cID` bigint(20) NOT NULL, PRIMARY KEY (`pID`), Foreign Key(`cID`) references categories(`cID`), Foreign Key(`uID`) references users(`uID`) ) ENGINE=InnoDB; ``` The column name is required in the `references` clause.
236,675
<p>How to cancel a keypress event in a textbox after pressing the return key.</p>
[ { "answer_id": 236687, "author": "lacop", "author_id": 894, "author_profile": "https://Stackoverflow.com/users/894", "pm_score": 3, "selected": true, "text": "<p>Set the Handled property of KeyPressEventArgs handler parameter to true.</p>\n\n<p>Example from msdn:</p>\n\n<pre><code>private void keypressed(Object o, KeyPressEventArgs e)\n{\n if (e.KeyChar == (char)Keys.Return)\n {\n e.Handled = true;\n }\n}\n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.handled.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.handled.aspx</a> for more info.</p>\n" }, { "answer_id": 236694, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": "<p>Do you mean, you want it to ignore the enter key ?</p>\n\n<p>You could add a keydown event and ignore the enter key there...</p>\n\n<pre><code>private void textBox1_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.KeyCode == Keys.Enter)\n {\n e.SuppressKeyPress = true;\n }\n }\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26087/" ]
How to cancel a keypress event in a textbox after pressing the return key.
Set the Handled property of KeyPressEventArgs handler parameter to true. Example from msdn: ``` private void keypressed(Object o, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Return) { e.Handled = true; } } ``` See <http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.handled.aspx> for more info.
236,676
<p>I have an IList of type Breadcrumb which is just a lightweight class that has NavigationTitle, NavigationUrl and IsCurrent properties. It is cached on the webserver. I have a method that builds out the current breadcrumb trail up until the first Breadcrumb that has IsCurrent set to true... using the code below. Its very ugly and definitely a quick dirtbag willie solution, but I was curious, can this be easily refactored into LINQ? </p> <pre><code>IList&lt;Breadcrumb&gt; crumbs = new List&lt;Breadcrumb&gt;(); bool foundCurrent = false; for (int a = 0; a &lt; cachedCrumbs.Count; a++) { crumbs.Add(crumbs[a]); if (foundCurrent) { break; } foundCurrent = (crumbs[a + 1] != null &amp;&amp; ((Breadcrumb)crumbs[a + 1]).IsCurrent); } </code></pre>
[ { "answer_id": 236701, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>First of all, that code doesn't work. I'm gonna guess that some of those places where you used \"crumbs\" you meant \"cachedCrumbs\". If so, the code can be reduced to:</p>\n\n<pre><code>IList&lt;Breadcrumb&gt; crumbs = new List&lt;Breadcrumb&gt;();\nfor (int a = 0; a &lt; cachedCrumbs.Count; a++)\n{\n crumbs.Add(cachedCrumbs[a]);\n if (cachedCrumbs[a] != null &amp;&amp; cachedCrumbs[a].IsCurrent)\n {\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 236705, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>I'm typing this as I think, so that it shows a train of thought as well as just an answer.</p>\n\n<ul>\n<li>Your source is just cachedCrumbs</li>\n<li>You want to add the first crumb which <em>does</em> have IsCurrent set, but nothing afterwards</li>\n<li>TakeWhile sounds like the way to go, but getting the \"previous value had IsCurrent\" is a bit of a pain</li>\n<li>We can use a closure to effectively keep a variable determining whether the last value had IsCurrent set</li>\n<li>We can do a somewhat \"no-op\" select to keep the TakeWhile separate from the working out of whether to keep going</li>\n</ul>\n\n<p>So, we end up with:</p>\n\n<pre><code>bool foundCurrent = false;\n\nvar crumbs = cachedCrumbs.TakeWhile(crumb =&gt; !foundCurrent)\n .Select(crumb =&gt; { \n foundCurrent = crumb == null || !crumb.IsCurrent; \n return crumb; });\n</code></pre>\n\n<p>I haven't tried this, but I <em>think</em> it should work... there might be a simpler way though.</p>\n\n<p>EDIT: I'd argue that actually a straight foreach loop <em>is</em> simpler in this case. Having said that, you could write another extension method which acted like TakeWhile except it <em>also</em> returned the element which caused the condition to fail. Then it would be as simple as:</p>\n\n<pre><code>var crumbs = cachedCrumbs.NewMethod(crumb =&gt; crumb == null || !crumb.IsCurrent);\n</code></pre>\n\n<p>(I can't think of a decent name for the method at the moment, hence <code>NewMethod</code> !)</p>\n" }, { "answer_id": 236707, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>An alternative answer based on James Curran's - this can certainly be improved using a foreach statement:</p>\n\n<pre><code>IList&lt;Breadcrumb&gt; crumbs = new List&lt;BreadCrumb&gt;();\nforeach (Breadcrumb crumb in cachedCrumbs)\n{\n crumbs.Add(crumb);\n if (crumb != null &amp;&amp; crumb.IsCurrent)\n {\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 236739, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "<p>How about...</p>\n\n<pre><code>// find the current item\nvar currentItem = cachedCrumbs.First(c =&gt; c.IsCurrent);\nvar currentIdx = cachedCrumbs.IndexOf(currentItem);\n\n// get all items upto current item\nvar crumbs = cachedCrumbs.Take(currentIdx + 2);\n</code></pre>\n\n<p>And you can turn this into a TakeUpto method which takes all items upto the one which matched the predicates you supply.</p>\n\n<p>How about:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; TakeUpto&lt;T&gt;(this IList&lt;T&gt; theList, Func&lt;T, bool&gt; predicate)\n{\n var targetItem = theList.First(predicate);\n var targetIdx = theList.IndexOf(targetItem);\n\n return theList.Take(targetIdx + 2);\n}\n</code></pre>\n\n<p>Then you could use it this way:</p>\n\n<pre><code>var crumbs = cachedCrumbs.TakeUpto(c =&gt; c.IsCurrent);\n</code></pre>\n\n<p>Much cleaner!</p>\n\n<p>Havn't check the nulls and off-by-one cases and IList/IEnumerable differences, but you should get the idea.</p>\n" }, { "answer_id": 236874, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>This answer is an alternative implementation of chakrit's TakeUpTo:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; TakeUpto&lt;T&gt;(this IEnumerable&lt;T&gt; theList, Func&lt;T, bool&gt; predicate)\n{\n foreach (T element in theList)\n {\n yield return element;\n if (predicate(element))\n {\n break;\n }\n }\n}\n</code></pre>\n\n<p>This only iterates through the list once, which could be relevant in various cases. (Suppose the upstream sequence is the result of an OrderBy clause - you really don't want it to have to sort the results multiple times for no good reason.)</p>\n\n<p>It also allows any <code>IEnumerable&lt;T&gt;</code> as the source, which makes it more flexible.</p>\n\n<p>One of the wonderful things about LINQ is the multiple ways of achieving the same goal.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
I have an IList of type Breadcrumb which is just a lightweight class that has NavigationTitle, NavigationUrl and IsCurrent properties. It is cached on the webserver. I have a method that builds out the current breadcrumb trail up until the first Breadcrumb that has IsCurrent set to true... using the code below. Its very ugly and definitely a quick dirtbag willie solution, but I was curious, can this be easily refactored into LINQ? ``` IList<Breadcrumb> crumbs = new List<Breadcrumb>(); bool foundCurrent = false; for (int a = 0; a < cachedCrumbs.Count; a++) { crumbs.Add(crumbs[a]); if (foundCurrent) { break; } foundCurrent = (crumbs[a + 1] != null && ((Breadcrumb)crumbs[a + 1]).IsCurrent); } ```
I'm typing this as I think, so that it shows a train of thought as well as just an answer. * Your source is just cachedCrumbs * You want to add the first crumb which *does* have IsCurrent set, but nothing afterwards * TakeWhile sounds like the way to go, but getting the "previous value had IsCurrent" is a bit of a pain * We can use a closure to effectively keep a variable determining whether the last value had IsCurrent set * We can do a somewhat "no-op" select to keep the TakeWhile separate from the working out of whether to keep going So, we end up with: ``` bool foundCurrent = false; var crumbs = cachedCrumbs.TakeWhile(crumb => !foundCurrent) .Select(crumb => { foundCurrent = crumb == null || !crumb.IsCurrent; return crumb; }); ``` I haven't tried this, but I *think* it should work... there might be a simpler way though. EDIT: I'd argue that actually a straight foreach loop *is* simpler in this case. Having said that, you could write another extension method which acted like TakeWhile except it *also* returned the element which caused the condition to fail. Then it would be as simple as: ``` var crumbs = cachedCrumbs.NewMethod(crumb => crumb == null || !crumb.IsCurrent); ``` (I can't think of a decent name for the method at the moment, hence `NewMethod` !)
236,692
<p>I have a device that supports 4-color graphics (much like CGA in the old days).</p> <p>I wanted to use <a href="http://www.pythonware.com/products/pil/" rel="noreferrer">PIL</a> to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people have tried to do so and failed.</p> <p>A simple python example would be much appreciated!</p> <p>Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)</p>
[ { "answer_id": 237193, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": true, "text": "<p>First: your four colour palette (black, green, red, yellow) has <em>no</em> blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with.</p>\n\n<p>Try this code:</p>\n\n<pre><code>import Image\n\ndef estimate_color(c, bit, c_error):\n c_new= c - c_error\n if c_new &gt; 127:\n c_bit= bit\n c_error= 255 - c_new\n else:\n c_bit= 0\n c_error= -c_new\n return c_bit, c_error\n\ndef image2cga(im):\n \"Produce a sequence of CGA pixels from image im\"\n im_width= im.size[0]\n for index, (r, g, b) in enumerate(im.getdata()):\n if index % im_width == 0: # start of a line\n r_error= g_error= 0\n r_bit, r_error= estimate_color(r, 1, r_error)\n g_bit, g_error= estimate_color(g, 2, g_error)\n yield r_bit|g_bit\n\ndef cvt2cga(imgfn):\n \"Convert an RGB image to (K, R, G, Y) CGA image\"\n inp_im= Image.open(imgfn) # assume it's RGB\n out_im= Image.new(\"P\", inp_im.size, None)\n out_im.putpalette( (\n 0, 0, 0,\n 255, 0, 0,\n 0, 255, 0,\n 255, 255, 0,\n ) )\n out_im.putdata(list(image2cga(inp_im)))\n return out_im\n\nif __name__ == \"__main__\":\n import sys, os\n\n for imgfn in sys.argv[1:]:\n im= cvt2cga(imgfn)\n dirname, filename= os.path.split(imgfn)\n name, ext= os.path.splitext(filename)\n newpathname= os.path.join(dirname, \"cga-%s.png\" % name)\n im.save(newpathname)\n</code></pre>\n\n<p>This creates a PNG palette image with only the first four palette entries set to your colours. This sample image:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BBxf1.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BBxf1.jpg\" width=\"320\"></a></p>\n\n<p>becomes</p>\n\n<p><a href=\"https://i.stack.imgur.com/QxtCD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QxtCD.png\" width=\"320\"></a></p>\n\n<p>It's trivial to take the output of <code>image2cga</code> (yields a sequence of 0-3 values) and pack every four values to a byte.</p>\n\n<p>If you need help about what the code does, please ask and I will explain.</p>\n\n<h3>EDIT1: Do not reinvent the wheel</h3>\n\n<p>Of course, turns out I was too enthusiastic and —as Thomas discovered— the Image.quantize method can take a palette image as argument and do the quantization with far better results than my ad-hoc method above:</p>\n\n<pre><code>def cga_quantize(image):\n pal_image= Image.new(\"P\", (1,1))\n pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252)\n return image.convert(\"RGB\").quantize(palette=pal_image)\n</code></pre>\n\n<h3>EDIT1, cont: Pack the pixels into bytes</h3>\n\n<p>For \"added value\", here follows code to produce the packed string (4 pixels per byte):</p>\n\n<pre><code>import itertools as it\n\n# setup: create a map with tuples [(0,0,0,0)‥(3,3,3,3)] as keys\n# and values [chr(0)‥chr(255)], because PIL does not yet support\n# 4 colour palette images\n\nTUPLE2CHAR= {}\n\n# Assume (b7, b6) are pixel0, (b5, b4) are pixel1…\n# Call it \"big endian\"\n\nKEY_BUILDER= [\n (0, 64, 128, 192), # pixel0 value used as index\n (0, 16, 32, 48), # pixel1\n (0, 4, 8, 12), # pixel2\n (0, 1, 2, 3), # pixel3\n]\n# For \"little endian\", uncomment the following line\n## KEY_BUILDER.reverse()\n\n# python2.6 has itertools.product, but for compatibility purposes\n# let's do it verbosely:\nfor ix0, px0 in enumerate(KEY_BUILDER[0]):\n for ix1, px1 in enumerate(KEY_BUILDER[1]):\n for ix2, px2 in enumerate(KEY_BUILDER[2]):\n for ix3, px3 in enumerate(KEY_BUILDER[3]):\n TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3)\n\n# Another helper function, copied almost verbatim from itertools docs\ndef grouper(n, iterable, padvalue=None):\n \"grouper(3, 'abcdefg', 'x') --&gt; ('a','b','c'), ('d','e','f'), ('g','x','x')\"\n return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n)\n\n# now the functions\ndef seq2str(seq):\n \"\"\"Takes a sequence of [0..3] values and packs them into bytes\n using two bits per value\"\"\"\n return ''.join(\n TUPLE2CHAR[four_pixel]\n for four_pixel in grouper(4, seq, 0))\n\n# and the image related function\n# Note that the following function is correct,\n# but is not useful for Windows 16 colour bitmaps,\n# which start at the *bottom* row…\ndef image2str(img):\n return seq2str(img.getdata())\n</code></pre>\n" }, { "answer_id": 237747, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 3, "selected": false, "text": "<p>John, I found that first link as well, but it didn't directly help me with the problem. It did make me look deeper into quantize though.</p>\n\n<p>I came up with this yesterday before going to bed:</p>\n\n<pre><code>import sys\n\nimport PIL\nimport Image\n\nPALETTE = [\n 0, 0, 0, # black, 00\n 0, 255, 0, # green, 01\n 255, 0, 0, # red, 10\n 255, 255, 0, # yellow, 11\n] + [0, ] * 252 * 3\n\n# a palette image to use for quant\npimage = Image.new(\"P\", (1, 1), 0)\npimage.putpalette(PALETTE)\n\n# open the source image\nimage = Image.open(sys.argv[1])\nimage = image.convert(\"RGB\")\n\n# quantize it using our palette image\nimagep = image.quantize(palette=pimage)\n\n# save\nimagep.save('/tmp/cga.png')\n</code></pre>\n\n<p>TZ.TZIOY, your solution seems to work along the same principles. Kudos, I should have stopped working on it and waited for your reply. Mine is a bit simpler, although definately not more logical than yours. PIL is cumbersome to use. Yours explains what's going on to do it.</p>\n" }, { "answer_id": 44673651, "author": "Lady_F", "author_id": 8193638, "author_profile": "https://Stackoverflow.com/users/8193638", "pm_score": 1, "selected": false, "text": "<pre><code>import sys\nimport PIL\nfrom PIL import Image\n\ndef quantizetopalette(silf, palette, dither=False):\n \"\"\"Convert an RGB or L mode image to use a given P image's palette.\"\"\"\n\n silf.load()\n\n # use palette from reference image\n palette.load()\n if palette.mode != \"P\":\n raise ValueError(\"bad mode for palette image\")\n if silf.mode != \"RGB\" and silf.mode != \"L\":\n raise ValueError(\n \"only RGB or L mode images can be quantized to a palette\"\n )\n im = silf.im.convert(\"P\", 1 if dither else 0, palette.im)\n # the 0 above means turn OFF dithering\n return silf._makeself(im)\n\nif __name__ == \"__main__\":\n import sys, os\n\nfor imgfn in sys.argv[1:]:\n palettedata = [ 0, 0, 0, 0, 255, 0, 255, 0, 0, 255, 255, 0,] \n palimage = Image.new('P', (16, 16))\n palimage.putpalette(palettedata + [0, ] * 252 * 3)\n oldimage = Image.open(sys.argv[1])\n newimage = quantizetopalette(oldimage, palimage, dither=False)\n dirname, filename= os.path.split(imgfn)\n name, ext= os.path.splitext(filename)\n newpathname= os.path.join(dirname, \"cga-%s.png\" % name)\n newimage.save(newpathname)\n</code></pre>\n\n<p>For those that wanted NO dithering to get solid colors. i modded: <a href=\"https://stackoverflow.com/questions/29433243/convert-image-to-specific-palette-using-pil-without-dithering\">Convert image to specific palette using PIL without dithering</a>\nwith the two solutions in this thread. Even though this thread is old, some of us want that information. Kudios</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ]
I have a device that supports 4-color graphics (much like CGA in the old days). I wanted to use [PIL](http://www.pythonware.com/products/pil/) to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people have tried to do so and failed. A simple python example would be much appreciated! Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)
First: your four colour palette (black, green, red, yellow) has *no* blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with. Try this code: ``` import Image def estimate_color(c, bit, c_error): c_new= c - c_error if c_new > 127: c_bit= bit c_error= 255 - c_new else: c_bit= 0 c_error= -c_new return c_bit, c_error def image2cga(im): "Produce a sequence of CGA pixels from image im" im_width= im.size[0] for index, (r, g, b) in enumerate(im.getdata()): if index % im_width == 0: # start of a line r_error= g_error= 0 r_bit, r_error= estimate_color(r, 1, r_error) g_bit, g_error= estimate_color(g, 2, g_error) yield r_bit|g_bit def cvt2cga(imgfn): "Convert an RGB image to (K, R, G, Y) CGA image" inp_im= Image.open(imgfn) # assume it's RGB out_im= Image.new("P", inp_im.size, None) out_im.putpalette( ( 0, 0, 0, 255, 0, 0, 0, 255, 0, 255, 255, 0, ) ) out_im.putdata(list(image2cga(inp_im))) return out_im if __name__ == "__main__": import sys, os for imgfn in sys.argv[1:]: im= cvt2cga(imgfn) dirname, filename= os.path.split(imgfn) name, ext= os.path.splitext(filename) newpathname= os.path.join(dirname, "cga-%s.png" % name) im.save(newpathname) ``` This creates a PNG palette image with only the first four palette entries set to your colours. This sample image: [![](https://i.stack.imgur.com/BBxf1.jpg)](https://i.stack.imgur.com/BBxf1.jpg) becomes [![](https://i.stack.imgur.com/QxtCD.png)](https://i.stack.imgur.com/QxtCD.png) It's trivial to take the output of `image2cga` (yields a sequence of 0-3 values) and pack every four values to a byte. If you need help about what the code does, please ask and I will explain. ### EDIT1: Do not reinvent the wheel Of course, turns out I was too enthusiastic and —as Thomas discovered— the Image.quantize method can take a palette image as argument and do the quantization with far better results than my ad-hoc method above: ``` def cga_quantize(image): pal_image= Image.new("P", (1,1)) pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252) return image.convert("RGB").quantize(palette=pal_image) ``` ### EDIT1, cont: Pack the pixels into bytes For "added value", here follows code to produce the packed string (4 pixels per byte): ``` import itertools as it # setup: create a map with tuples [(0,0,0,0)‥(3,3,3,3)] as keys # and values [chr(0)‥chr(255)], because PIL does not yet support # 4 colour palette images TUPLE2CHAR= {} # Assume (b7, b6) are pixel0, (b5, b4) are pixel1… # Call it "big endian" KEY_BUILDER= [ (0, 64, 128, 192), # pixel0 value used as index (0, 16, 32, 48), # pixel1 (0, 4, 8, 12), # pixel2 (0, 1, 2, 3), # pixel3 ] # For "little endian", uncomment the following line ## KEY_BUILDER.reverse() # python2.6 has itertools.product, but for compatibility purposes # let's do it verbosely: for ix0, px0 in enumerate(KEY_BUILDER[0]): for ix1, px1 in enumerate(KEY_BUILDER[1]): for ix2, px2 in enumerate(KEY_BUILDER[2]): for ix3, px3 in enumerate(KEY_BUILDER[3]): TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3) # Another helper function, copied almost verbatim from itertools docs def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n) # now the functions def seq2str(seq): """Takes a sequence of [0..3] values and packs them into bytes using two bits per value""" return ''.join( TUPLE2CHAR[four_pixel] for four_pixel in grouper(4, seq, 0)) # and the image related function # Note that the following function is correct, # but is not useful for Windows 16 colour bitmaps, # which start at the *bottom* row… def image2str(img): return seq2str(img.getdata()) ```
236,713
<p>Please help, I am stuck here ---</p> <pre><code>irb&gt; a = "line of text\n line two\n line three" irb&gt; system("cat &gt; test_file &lt;&lt; #{a}") cat: of: No such file or directory cat: text: No such file or directory =&gt; false </code></pre>
[ { "answer_id": 236727, "author": "Ivan", "author_id": 16957, "author_profile": "https://Stackoverflow.com/users/16957", "pm_score": 3, "selected": true, "text": "<p>You need to quote the interpolated parameter:</p>\n\n<pre><code>system(\"cat &gt; test_file &lt;&lt; \\\"#{a}\\\"\")\n</code></pre>\n\n<p>And, cat is expecting a filename, not some text to append to test_file, so, this would work as I think you intended:</p>\n\n<pre><code>system(\"echo \\\"#{a}\\\" &gt;&gt; test_file\")\n</code></pre>\n\n<p>If you want to do this in pure Ruby let me know and I'll give you an example.</p>\n" }, { "answer_id": 236729, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>Write a to a file called \"testfile\":</p>\n\n<pre><code>File.open(\"testfile\", \"w\") do |io| io.print a done\n</code></pre>\n" }, { "answer_id": 236757, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>Writing to a file directly has already been covered by JesperE. To write to a process (in this case a \"cat\" process) use popen.</p>\n\n<pre><code>IO.popen(\"cat &gt; foo\", \"w\") do\n |f|\n f.write(\"line1\\nline2\\n\")\nend\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31347/" ]
Please help, I am stuck here --- ``` irb> a = "line of text\n line two\n line three" irb> system("cat > test_file << #{a}") cat: of: No such file or directory cat: text: No such file or directory => false ```
You need to quote the interpolated parameter: ``` system("cat > test_file << \"#{a}\"") ``` And, cat is expecting a filename, not some text to append to test\_file, so, this would work as I think you intended: ``` system("echo \"#{a}\" >> test_file") ``` If you want to do this in pure Ruby let me know and I'll give you an example.
236,715
<p>I am using Ruby on Rails.</p> <p>I want to create a filter field on a page such that whenever the input field's value changes I filter a list shown below via ajax. (Exaclty like the Users search works in Stackoverflow)</p> <p>For now, I made it run with a form_remote_tag containing a text_field_tag and a submit_tag, and it filters my list when I push the submit button. I would like to remove the submit button and execute the filtering every time the value of the text input changes. How can I trigger a form submit every time the text in an input field changes?</p> <p>I tried inside my form</p> <p><code>&lt;%= text_field_tag (:filter), "" , :onchange =&gt; "alert ('This is a Javascript Alert')" %&gt;</code></p> <p>just to get the onchange event, but somehow not even this alert appears...</p>
[ { "answer_id": 236721, "author": "Ricardo Acras", "author_id": 19224, "author_profile": "https://Stackoverflow.com/users/19224", "pm_score": 3, "selected": true, "text": "<p>Use <strong>observe_field</strong> helper with a single input, like the code bellow:</p>\n\n<pre><code>&lt;%= text_field_tag 'filter' %&gt;\n&lt;%= observe_field 'filter', \n :url =&gt; {:controller =&gt; 'your_controller', :action =&gt; 'filter'},\n :frequency =&gt; 1.2,\n :update =&gt; 'results',\n :with =&gt; \"'typed_filter=' + $('filter').value\" %&gt;\n</code></pre>\n\n<p>And then just write a controller that, given a param named 'typed_filter', renders the results, wich will be shown in the element with id 'results' (probably a div).</p>\n" }, { "answer_id": 236826, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>In general for text inputs you want to use onkeypress, onkeyup, onkeydown events, not onchange for this type of autocomplete. @Ricardo Acras solution is far better than writing your own, but I thought you might want to know that onchange doesn't work because it doesn't fire until you navigate out of the text input (and the text has been changed).</p>\n\n<p>I find that w3schools.com is a great resource for this kind of info. <a href=\"http://w3schools.com/js/js_obj_htmldom.asp\" rel=\"nofollow noreferrer\">Here</a> is there page on Javascript HTML DOM. And <a href=\"http://w3schools.com/htmldom/dom_obj_event.asp\" rel=\"nofollow noreferrer\">here</a> is the event reference.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534/" ]
I am using Ruby on Rails. I want to create a filter field on a page such that whenever the input field's value changes I filter a list shown below via ajax. (Exaclty like the Users search works in Stackoverflow) For now, I made it run with a form\_remote\_tag containing a text\_field\_tag and a submit\_tag, and it filters my list when I push the submit button. I would like to remove the submit button and execute the filtering every time the value of the text input changes. How can I trigger a form submit every time the text in an input field changes? I tried inside my form `<%= text_field_tag (:filter), "" , :onchange => "alert ('This is a Javascript Alert')" %>` just to get the onchange event, but somehow not even this alert appears...
Use **observe\_field** helper with a single input, like the code bellow: ``` <%= text_field_tag 'filter' %> <%= observe_field 'filter', :url => {:controller => 'your_controller', :action => 'filter'}, :frequency => 1.2, :update => 'results', :with => "'typed_filter=' + $('filter').value" %> ``` And then just write a controller that, given a param named 'typed\_filter', renders the results, wich will be shown in the element with id 'results' (probably a div).
236,737
<p>Perl and PHP do this with backticks. For example,</p> <pre><code>$output = `ls`; </code></pre> <p>Returns a directory listing. A similar function, <code>system("foo")</code>, returns the operating system return code for the given command foo. I'm talking about a variant that returns whatever foo prints to stdout.</p> <p>How do other languages do this? Is there a canonical name for this function? (I'm going with "backtick"; though maybe I could coin "syslurp".)</p>
[ { "answer_id": 236740, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 3, "selected": true, "text": "<p>Perl:</p>\n\n<pre><code>$output = `foo`;\n</code></pre>\n\n<p>ADDED: This is really a multi-way tie. The above is also valid PHP, and Ruby, for example, uses the same backtick notation as well.</p>\n" }, { "answer_id": 236742, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 2, "selected": false, "text": "<p>Mathematica:</p>\n\n<pre><code>output = Import[\"!foo\", \"Text\"];\n</code></pre>\n" }, { "answer_id": 236754, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 4, "selected": false, "text": "<p>Python:</p>\n\n<pre><code>import os\noutput = os.popen(\"foo\").read()\n</code></pre>\n" }, { "answer_id": 236764, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p>In shell</p>\n\n<pre><code>OUTPUT=`ls`\n</code></pre>\n\n<p>or alternatively</p>\n\n<pre><code>OUTPUT=$(ls)\n</code></pre>\n\n<p>This second method is better because it allows nesting, but isn't supported by all shells, unlike the first method.</p>\n" }, { "answer_id": 236769, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 3, "selected": false, "text": "<p>Ruby: either backticks or the '%x' builtin syntax.</p>\n\n<pre><code>puts `ls`;\nputs %x{ls};\n</code></pre>\n" }, { "answer_id": 236772, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>In PHP</p>\n\n<pre><code>$output = `ls`;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$output = shell_exec('ls');\n</code></pre>\n" }, { "answer_id": 236781, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p>An alternative method in perl</p>\n\n<pre><code>$output = qx/ls/;\n</code></pre>\n\n<p>This had the advantage that you can choose your delimiters, making it possible to use ` in the command (though IMHO you should reconsider your design if you really need to do that). Another important advantage is that if you use single quotes as delimiter, variables will not be interpolated (a very useful)</p>\n" }, { "answer_id": 236787, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "<p>Erlang:</p>\n\n<pre><code>os:cmd(\"ls\")\n</code></pre>\n" }, { "answer_id": 236791, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p>Yet another way to do it in Perl (TIMTOWTDI)</p>\n\n<pre><code>$output = &lt;&lt;`END`;\nls\nEND\n</code></pre>\n\n<p>This is specially useful when embedding a relatively large shell script in a Perl program</p>\n" }, { "answer_id": 236873, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "<p>[At the request of <a href=\"https://stackoverflow.com/users/11289/axeman\">Alexman</a> and <a href=\"https://stackoverflow.com/users/4234/dreeves\">dreeves</a> -- see comments --, you will find at this <strong><a href=\"http://snippets.dzone.com/posts/show/6335\" rel=\"nofollow noreferrer\">DZones Java Snippet page</a></strong> a full version Os-independent for making, in this instance, a 'ls'. This is a direct answer to their <strong><em><a href=\"https://stackoverflow.com/questions/172184/are-you-elite-coder-enough-to-take-a-code-challenge-closed\">code-challenge</a></em></strong>.<br>\nWhat follows below is just the core: Runtime.exec, plus 2 thread to listen to stdout and stderr. ]</p>\n\n<p><strong><a href=\"http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4\" rel=\"nofollow noreferrer\">Java</a></strong> \"Simple!\":</p>\n\n<pre><code>E:\\classes\\com\\javaworld\\jpitfalls\\article2&gt;java GoodWindowsExec \"dir *.java\"\nExecuting cmd.exe /C dir *.java\n...\n</code></pre>\n\n<p>Or in java code</p>\n\n<pre><code>String output = GoodWindowsExec.execute(\"dir\");\n</code></pre>\n\n<p>But to do that, you need to code...<br>\n... this is embarrassing. </p>\n\n<pre><code>import java.util.*;\nimport java.io.*;\nclass StreamGobbler extends Thread\n{\n InputStream is;\n String type;\n StringBuffer output = new StringBuffer();\n\n StreamGobbler(InputStream is, String type)\n {\n this.is = is;\n this.type = type;\n }\n\n public void run()\n {\n try\n {\n InputStreamReader isr = new InputStreamReader(is);\n BufferedReader br = new BufferedReader(isr);\n String line=null;\n while ( (line = br.readLine()) != null)\n System.out.println(type + \"&gt;\" + line);\n output.append(line+\"\\r\\n\")\n } catch (IOException ioe)\n {\n ioe.printStackTrace(); \n }\n }\n public String getOutput()\n {\n return this.output.toString();\n }\n}\npublic class GoodWindowsExec\n{\n public static void main(String args[])\n {\n if (args.length &lt; 1)\n {\n System.out.println(\"USAGE: java GoodWindowsExec &lt;cmd&gt;\");\n System.exit(1);\n }\n }\n public static String execute(String aCommand)\n {\n String output = \"\";\n try\n { \n String osName = System.getProperty(\"os.name\" );\n String[] cmd = new String[3];\n if( osName.equals( \"Windows 95\" ) )\n {\n cmd[0] = \"command.com\" ;\n cmd[1] = \"/C\" ;\n cmd[2] = aCommand;\n }\n else if( osName.startsWith( \"Windows\" ) )\n {\n cmd[0] = \"cmd.exe\" ;\n cmd[1] = \"/C\" ;\n cmd[2] = aCommand;\n }\n\n Runtime rt = Runtime.getRuntime();\n System.out.println(\"Executing \" + cmd[0] + \" \" + cmd[1] \n + \" \" + cmd[2]);\n Process proc = rt.exec(cmd);\n // any error message?\n StreamGobbler errorGobbler = new \n StreamGobbler(proc.getErrorStream(), \"ERROR\"); \n\n // any output?\n StreamGobbler outputGobbler = new \n StreamGobbler(proc.getInputStream(), \"OUTPUT\");\n\n // kick them off\n errorGobbler.start();\n outputGobbler.start();\n\n // any error???\n int exitVal = proc.waitFor();\n System.out.println(\"ExitValue: \" + exitVal); \n\n output = outputGobbler.getOutput();\n System.out.println(\"Final output: \" + output); \n\n } catch (Throwable t)\n {\n t.printStackTrace();\n }\n return output;\n }\n}\n</code></pre>\n" }, { "answer_id": 236909, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "<h2>Python</h2>\n\n<pre><code>from subprocess import check_output as qx\n\noutput = qx(['ls', '-lt'])\n</code></pre>\n\n<h3>Python &lt;<a href=\"http://docs.python.org/dev/library/subprocess.html#subprocess.check_output\" rel=\"noreferrer\">2.7</a> or &lt;<a href=\"http://docs.python.org/py3k/library/subprocess.html#subprocess.check_output\" rel=\"noreferrer\">3.1</a></h3>\n\n<p>Extract <code>subprocess.check_output()</code> from <a href=\"http://svn.python.org/view/python/trunk/Lib/subprocess.py?view=markup\" rel=\"noreferrer\">subprocess.py</a> or adapt something similar to:</p>\n\n<pre><code>import subprocess\n\ndef cmd_output(args, **kwds):\n kwds.setdefault(\"stdout\", subprocess.PIPE)\n kwds.setdefault(\"stderr\", subprocess.STDOUT)\n p = subprocess.Popen(args, **kwds)\n return p.communicate()[0]\n\nprint cmd_output(\"ls -lt\".split())\n</code></pre>\n\n<p>The <a href=\"http://docs.python.org/library/subprocess.html\" rel=\"noreferrer\">subprocess</a> module has been in the stdlib since 2.4.</p>\n" }, { "answer_id": 236997, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 2, "selected": false, "text": "<p>Yet another way (or 2!) in Perl....</p>\n\n<pre><code>open my $pipe, 'ps |';\nmy @output = &lt; $pipe &gt;;\nsay @output;\n</code></pre>\n\n<p><a href=\"http://perldoc.perl.org/functions/open.html\" rel=\"nofollow noreferrer\">open</a> can also be written like so...</p>\n\n<pre><code>open my $pipe, '-|', 'ps'\n</code></pre>\n" }, { "answer_id": 241436, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>C (with <code>glibc</code> extension):</p>\n\n<pre><code>#define _GNU_SOURCE\n#include &lt;stdio.h&gt;\nint main() {\n char *s = NULL;\n FILE *p = popen(\"ls\", \"r\");\n getdelim(&amp;s, NULL, '\\0', p);\n pclose(p);\n printf(\"%s\", s);\n return 0;\n}\n</code></pre>\n\n<p>Okay, not really concise or clean. That's life in C...</p>\n" }, { "answer_id": 241445, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.jsoftware.com/\" rel=\"nofollow noreferrer\">J</a>:</p>\n\n<pre><code>output=:2!:0'ls'\n</code></pre>\n" }, { "answer_id": 241495, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "<p>Haskell:</p>\n\n<pre><code>import Control.Exception\nimport System.IO\nimport System.Process\nmain = bracket (runInteractiveCommand \"ls\") close $ \\(_, hOut, _, _) -&gt; do\n output &lt;- hGetContents hOut\n putStr output\n where close (hIn, hOut, hErr, pid) =\n mapM_ hClose [hIn, hOut, hErr] &gt;&gt; waitForProcess pid\n</code></pre>\n\n<p>With <a href=\"http://software.complete.org/software/projects/show/missingh\" rel=\"nofollow noreferrer\">MissingH</a> installed:</p>\n\n<pre><code>import System.Cmd.Utils\nmain = do\n (pid, output) &lt;- pipeFrom \"ls\" []\n putStr output\n forceSuccess pid\n</code></pre>\n\n<p>This is an easy operation in \"glue\" languages like Perl and Ruby, but Haskell isn't.</p>\n" }, { "answer_id": 251792, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 2, "selected": false, "text": "<p>Years ago I wrote a <a href=\"https://sourceforge.net/projects/jpop\" rel=\"nofollow noreferrer\">plugin</a> for <a href=\"http://jedit.org\" rel=\"nofollow noreferrer\">jEdit</a> that interfaced to a native application. This is what I used to get the streams off the running executable. Only thing left to do is <code>while((String s = stdout.readLine())!=null){...}</code>:</p>\n\n<pre><code>/* File: IOControl.java\n *\n * created: 10 July 2003\n * author: dsm\n */\npackage org.jpop.io;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.io.PrintStream;\n\n/**\n * Controls the I/O for a process. When using the std[in|out|err] streams, they must all be put on\n * different threads to avoid blocking!\n *\n * @author dsm\n * @version 1.5\n */\npublic class IOControl extends Object {\n private Process process;\n private BufferedReader stdout;\n private BufferedReader stderr;\n private PrintStream stdin;\n\n /**\n * Constructor for the IOControl object\n *\n * @param process The process to control I/O for\n */\n public IOControl(Process process) {\n this.process = process;\n this.stdin = new PrintStream(process.getOutputStream());\n this.stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));\n this.stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));\n }\n\n /**\n * Gets the stdin attribute of the IOControl object\n *\n * @return The stdin value\n */\n public PrintStream getStdin() {\n return this.stdin;\n }\n\n /**\n * Gets the stdout attribute of the IOControl object\n *\n * @return The stdout value\n */\n public BufferedReader getStdout() {\n return this.stdout;\n }\n\n /**\n * Gets the stderr attribute of the IOControl object\n *\n * @return The stderr value\n */\n public BufferedReader getStderr() {\n return this.stderr;\n }\n\n /**\n * Gets the process attribute of the IOControl object. To monitor the process (as opposed to\n * just letting it run by itself) its necessary to create a thread like this: &lt;pre&gt;\n *. IOControl ioc;\n *.\n *. new Thread(){\n *. public void run(){\n *. while(true){ // only necessary if you want the process to respawn\n *. try{\n *. ioc = new IOControl(Runtime.getRuntime().exec(\"procname\"));\n *. // add some code to handle the IO streams\n *. ioc.getProcess().waitFor();\n *. }catch(InterruptedException ie){\n *. // deal with exception\n *. }catch(IOException ioe){\n *. // deal with exception\n *. }\n *.\n *. // a break condition can be included here to terminate the loop\n *. } // only necessary if you want the process to respawn\n *. }\n *. }.start();\n * &lt;/pre&gt;\n *\n * @return The process value\n */\n public Process getProcess() {\n return this.process;\n }\n}\n</code></pre>\n" }, { "answer_id": 335221, "author": "Dave Ray", "author_id": 40310, "author_profile": "https://Stackoverflow.com/users/40310", "pm_score": 2, "selected": false, "text": "<p>Don't forget Tcl:</p>\n\n<pre><code>set result [exec ls]\n</code></pre>\n" }, { "answer_id": 364465, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 3, "selected": false, "text": "<p>Well, since this is system dependent, there are many languages that do not have a built-in wrapper for the various system calls needed.</p>\n\n<p>For example, Common Lisp itself was not designed to run on any specific system. SBCL (the Steel Banks Common Lisp implementation), though, does provide an extension for Unix-like systems, as do most other CL implementations. This is much more \"mighty\" than just getting the output, of course (you have control over the running process, can specify all kinds of stream directions, etc., confer to the SBCL manual, chapter 6.3), but it is easy to write a little macro for this specific purpose:</p>\n\n<pre>(defmacro with-input-from-command ((stream-name command args) &body body)\n \"Binds the output stream of command to stream-name, then executes the body\n in an implicit progn.\"\n `(with-open-stream\n (,stream-name\n (sb-ext:process-output (sb-ext:run-program ,command\n ,args\n :search t\n :output :stream)))\n ,@body))</pre>\n\n<p>Now, you can use it like this:</p>\n\n<pre>(with-input-from-command (ls \"ls\" '(\"-l\"))\n ;;do fancy stuff with the ls stream\n )</pre>\n\n<p>Perhaps you want to slurp it all into one string. The macro is trivial (though perhaps more concise code is possible):</p>\n\n<pre>\n(defmacro syslurp (command args)\n \"Returns the output from command as a string. command is to be supplied\n as string, args as a list of strings.\"\n (let ((istream (gensym))\n (ostream (gensym))\n (line (gensym)))\n `(with-input-from-command (,istream ,command ,args)\n (with-output-to-string (,ostream)\n (loop (let ((,line (read-line ,istream nil)))\n (when (null ,line) (return))\n (write-line ,line ,ostream)))))))\n</pre>\n\n<p>Now you can get a string with this call:</p>\n\n<pre>(syslurp \"ls\" '(\"-l\"))</pre>\n" }, { "answer_id": 372423, "author": "derobert", "author_id": 27727, "author_profile": "https://Stackoverflow.com/users/27727", "pm_score": 2, "selected": false, "text": "<p>Perl, another way:</p>\n\n<pre><code>use IPC::Run3\n\nmy ($stdout, $stderr);\nrun3 ['ls'], undef, \\$stdout, \\$stderr\n or die \"ls failed\";\n</code></pre>\n\n<p>Useful because you can feed the command input, and get back both stderr and stdout separately. Nowhere near as neat/scary/slow/disturbing as <code>IPC::Run</code>, which can set up pipes to subroutines.</p>\n" }, { "answer_id": 373080, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 2, "selected": false, "text": "<p>In C on Posix conformant systems:</p>\n\n<pre><code>#include &lt;stdio.h&gt; \n\nFILE* stream = popen(\"/path/to/program\", \"rw\");\nfprintf(stream, \"foo\\n\"); /* Use like you would a file stream. */\nfclose(stream);\n</code></pre>\n" }, { "answer_id": 373223, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "<p>Granted, it is not the smaller ( from all the languages available ) but it shouldn't be that verbose.</p>\n\n<p>This version is dirty. Exceptions should be handled, reading may be improved. This is just to show how a java version could start.</p>\n\n<pre><code>Process p = Runtime.getRuntime().exec( \"cmd /c \" + command );\nInputStream i = p.getInputStream();\nStringBuilder sb = new StringBuilder();\nfor( int c = 0 ; ( c = i.read() ) &gt; -1 ; ) {\n sb.append( ( char ) c );\n}\n</code></pre>\n\n<p>Complete program below. </p>\n\n<pre><code>import java.io.*;\n\npublic class Test { \n public static void main ( String [] args ) throws IOException { \n String result = execute( args[0] );\n System.out.println( result );\n }\n private static String execute( String command ) throws IOException { \n Process p = Runtime.getRuntime().exec( \"cmd /c \" + command );\n InputStream i = p.getInputStream();\n StringBuilder sb = new StringBuilder();\n for( int c = 0 ; ( c = i.read() ) &gt; -1 ; ) {\n sb.append( ( char ) c );\n }\n i.close();\n return sb.toString();\n }\n}\n</code></pre>\n\n<p>Sample ouput ( using the type command ) </p>\n\n<pre><code>C:\\oreyes\\samples\\java\\readinput&gt;java Test \"type hello.txt\"\nThis is a sample file\nwith some\nlines\n</code></pre>\n\n<p>Sample output ( dir ) </p>\n\n<pre><code> C:\\oreyes\\samples\\java\\readinput&gt;java Test \"dir\"\n El volumen de la unidad C no tiene etiqueta.\n El número de serie del volumen es:\n\n Directorio de C:\\oreyes\\samples\\java\\readinput\n\n12/16/2008 05:51 PM &lt;DIR&gt; .\n12/16/2008 05:51 PM &lt;DIR&gt; ..\n12/16/2008 05:50 PM 42 hello.txt\n12/16/2008 05:38 PM 1,209 Test.class\n12/16/2008 05:47 PM 682 Test.java\n 3 archivos 1,933 bytes\n 2 dirs 840 bytes libres\n</code></pre>\n\n<p>Try any</p>\n\n<pre><code>java Test netstat\njava Test tasklist\njava Test \"taskkill /pid 416\"\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>I must admit I'm not 100% sure this is the \"best\" way to do it. Feel free to post references and/or code to show how can it be improved or what's wrong with this.</p>\n" }, { "answer_id": 388176, "author": "Gant", "author_id": 12460, "author_profile": "https://Stackoverflow.com/users/12460", "pm_score": 2, "selected": false, "text": "<p>Why there is still no c# guy here :)</p>\n\n<p>This is how to do it in C#. The built-in way.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Diagnostics;\n\nnamespace TestConsole\n{\n class Program\n {\n static void Main(string[] args)\n {\n Process p = new Process();\n\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.CreateNoWindow = true;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.RedirectStandardError = true;\n p.StartInfo.FileName = \"cmd\";\n p.StartInfo.Arguments = \"/c dir\";\n p.Start();\n\n string res = p.StandardOutput.ReadToEnd();\n Console.WriteLine(res);\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 388218, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 2, "selected": false, "text": "<h3>Icon/Unicon:</h3>\n\n<pre><code>stream := open(\"ls\", \"p\")\nwhile line := read(stream) do { \n # stuff\n}\n</code></pre>\n\n<p>The docs call this a pipe. One of the good things is that it makes the output look like you're just reading a file. It also means you can write to the app's stdin, if you must.</p>\n" }, { "answer_id": 432847, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>C# 3.0, less verbose than <a href=\"https://stackoverflow.com/questions/236737/language-showdown-how-do-you-make-a-system-call-that-returns-the-stdout-output-a#388176\">this one</a>:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\n\nclass Program\n{\n static void Main()\n {\n var info = new ProcessStartInfo(\"cmd\", \"/c dir\") { UseShellExecute = false, RedirectStandardOutput = true };\n Console.WriteLine(Process.Start(info).StandardOutput.ReadToEnd());\n }\n}\n</code></pre>\n\n<p>Caveat: Production code should properly dispose the Process object...</p>\n" }, { "answer_id": 1371936, "author": "Donnie Cameron", "author_id": 160976, "author_profile": "https://Stackoverflow.com/users/160976", "pm_score": 2, "selected": false, "text": "<p>Here's another Lisp way:</p>\n\n<pre><code>(defun execute (program parameters &amp;optional (buffer-size 1000))\n (let ((proc (sb-ext:run-program program parameters :search t :output :stream))\n (output (make-array buffer-size :adjustable t :fill-pointer t \n :element-type 'character)))\n (with-open-stream (stream (sb-ext:process-output proc))\n (setf (fill-pointer output) (read-sequence output stream)))\n output))\n</code></pre>\n\n<p>Then, to get your string:</p>\n\n<pre><code>(execute \"cat\" '(\"/etc/hosts\"))\n</code></pre>\n\n<p>If you want to run a command that creates prints a great deal of info to STDOUT, you can run it like this:</p>\n\n<pre><code>(execute \"big-writer\" '(\"some\" \"parameters\") 1000000)\n</code></pre>\n\n<p>The last parameter preallocates a large amount of space for the output from big-writer. I'm guessing this function could be faster than reading the output stream one line at a time.</p>\n" }, { "answer_id": 1371990, "author": "Alexander Gladysh", "author_id": 6236, "author_profile": "https://Stackoverflow.com/users/6236", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://lua.org\" rel=\"nofollow noreferrer\">Lua</a>:</p>\n\n<pre><code> foo = io.popen(\"ls\"):read(\"*a\")\n</code></pre>\n" }, { "answer_id": 1372559, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 2, "selected": false, "text": "<p>Clozure Common Lisp:</p>\n\n<pre><code>(with-output-to-string (stream)\n (run-program \"ls\" '(\"-l\") :output stream))\n</code></pre>\n\n<p>LispWorks</p>\n\n<pre><code>(with-output-to-string (*standard-output*)\n (sys:call-system-showing-output \"ls -l\" :prefix \"\" :show-cmd nil))\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
Perl and PHP do this with backticks. For example, ``` $output = `ls`; ``` Returns a directory listing. A similar function, `system("foo")`, returns the operating system return code for the given command foo. I'm talking about a variant that returns whatever foo prints to stdout. How do other languages do this? Is there a canonical name for this function? (I'm going with "backtick"; though maybe I could coin "syslurp".)
Perl: ``` $output = `foo`; ``` ADDED: This is really a multi-way tie. The above is also valid PHP, and Ruby, for example, uses the same backtick notation as well.
236,749
<p>I have a bunch of ASP.NET web pages (that have a standard layout) that are product documentation. I want to create some sort of combination page that will pull all of the other page content in and concatenate them into one long page.</p> <p>IFrames won't work because I don't know the size of each page. I could have the combination page do a ton of #includes, and that would work, but I don't want to have to keep the master update to date (we have a database of page names that can change over time).</p> <p>Ultimately I'm after something that can get a list of pages, and for each one do the equivalent of a #include for that page into the current page.</p> <p>I hope that makes sense. Any thoughts?</p>
[ { "answer_id": 236767, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>What does your pages look like?</p>\n\n<p>I assume it's just plain HTMLs and have a consistent pattern across all pages, no? Like, it has proper HTML markup along with HEAD and BODY and such?</p>\n\n<p>In which case you can just read it like you'd read normal text files and do some string parsing on them to extract the part inside BODY tags and then you can just concatenate those and print them out ASP-#include style.</p>\n\n<p>To get the actual path name to a file on an ASP.NET website, you can use <code>Server.MapPath</code></p>\n\n<pre><code>var actualDiskFilename = Server.MapPath(\"~/somewhere/somepage.html\");\n</code></pre>\n\n<p>All the <code>System.IO</code> classes work the same in ASP.NET, to fetch a list of files in a virtual directory, you can do:</p>\n\n<pre><code>var virtualDir = \"~/somefolder/\";\nvar actualDir = Server.MapPath(virtualDir);\n\nvar files = Directory.GetFiles(actualDir);\n</code></pre>\n\n<p>Is that what you're looking for?</p>\n" }, { "answer_id": 236776, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": true, "text": "<p>Are your \"Documentation Pages\" static html or .aspx's also...</p>\n\n<p>if its just static content, you could do the following</p>\n\n<pre><code>//assume that the array of page names has come from the DB.\nprotected void Page_Load(object sender, EventArgs e)\n{\n string[] pages = new string [] { \"~/Default.html\", \n \"~/Default2.html\", \"~/Default3.html\", \"~/Default4.html\" };\n\n foreach (string p in pages)\n {\n Response.WriteFile(p);\n }\n}\n</code></pre>\n" }, { "answer_id": 236823, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 0, "selected": false, "text": "<p>If the pages are aspx-documents you can use <code>Server.Execute</code> to execute the page and return the generated html. Then you can parse the html and remove the head- and body-tags and concatenate the remaining html into your page.</p>\n" }, { "answer_id": 236839, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<p>You say IFRAMES won't work because you don't know the sizes? Well why not update the size of the IFRAMES according to the size.</p>\n\n<p>Create a default Size IFRAME and load the page, then by the aid of javascript update the size. You should look at some javascript framework like prototype or <a href=\"http://www.jquery.com\" rel=\"nofollow noreferrer\">jquery</a></p>\n" }, { "answer_id": 236924, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 0, "selected": false, "text": "<p>Sounds to me like you should rethink the format from the beginning, if possible. If you stored the content in the database or XML files, for instance, then your individual pages could serve up their section, and your conglomerate page could serve up any combination of the total that you want.</p>\n\n<p>Wouldn't be that hard to convert to if you're only talking a few pages (less than a dozen). Then keeping the documentation up to date is a matter of editing the content, not the display files (admittedly, XML is easier than a database in this respect).</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442/" ]
I have a bunch of ASP.NET web pages (that have a standard layout) that are product documentation. I want to create some sort of combination page that will pull all of the other page content in and concatenate them into one long page. IFrames won't work because I don't know the size of each page. I could have the combination page do a ton of #includes, and that would work, but I don't want to have to keep the master update to date (we have a database of page names that can change over time). Ultimately I'm after something that can get a list of pages, and for each one do the equivalent of a #include for that page into the current page. I hope that makes sense. Any thoughts?
Are your "Documentation Pages" static html or .aspx's also... if its just static content, you could do the following ``` //assume that the array of page names has come from the DB. protected void Page_Load(object sender, EventArgs e) { string[] pages = new string [] { "~/Default.html", "~/Default2.html", "~/Default3.html", "~/Default4.html" }; foreach (string p in pages) { Response.WriteFile(p); } } ```
236,778
<p>I have a table named Info of this schema:</p> <pre><code>int objectId; int time; int x, y; </code></pre> <p>There is a lot of redundant data in the system - that is, <code>objectId</code> is not UNIQUE. For each <code>objectId</code> there can be multiple entries of <code>time, x, y</code>.</p> <p>I want to retrieve a list of the latest position of each object. I started out with this query:</p> <pre><code>SELECT * FROM Info GROUP BY objectId </code></pre> <p>That got me just the kind of list I was looking for. However I want also to get just the latest times for each Object, so I tried:</p> <pre><code>SELECT * FROM Info GROUP BY objectId ORDER BY time DESC </code></pre> <p>This gave me a <code>time</code> descended list of Infos. However, <strong>I don't think it did what I want - that is return me the latest <code>time, x, y</code> for each object</strong>.</p> <p>Can anyone imagine a query to do what I want?</p> <p><strong>Update</strong> I have tried the top three solutions to see how they perform against each other on a dataset of about 50,000 Infos. Here are the results:</p> <pre><code>-- NO INDEX: forever -- INDEX: 7.67 s SELECT a.* FROM Info AS a LEFT OUTER JOIN Info AS b ON (a.objectId = b.objectId AND a.time &lt; b.time) WHERE b.objectId IS NULL; -- NO INDEX: 8.05 s -- INDEX: 0.17 s select a.objectId, a.time, a.x, a.y from Info a, (select objectId, max(time) time from Info group by objectId) b where a.objectId = b.objectId and a.time = b.time; -- NO INDEX: 8.30 s -- INDEX: 0.18 s SELECT A.time, A.objectId, B.x, B.y FROM ( SELECT max(time) as time, objectId FROM Info GROUP by objectId ) as A INNER JOIN Info B ON A.objectId = b.objectId AND A.time = b.time; </code></pre> <p>By a margin, it would seem <code>where</code> outperforms <code>inner join</code>.</p>
[ { "answer_id": 236786, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT A.time, A.objectID, B.X, B.Y\nFROM\n(\n SELECT max(time) as time, objectID \n FROM table\n GROUP by objectID\n) as A \nINNER JOIN table B\n ON A.objectID = b.objectID AND A.Time = b.Time\n</code></pre>\n\n<p>votenaders, solution won't work, if x &amp; y decrement at anypoint in the time line.</p>\n" }, { "answer_id": 236790, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": true, "text": "<p>One way is using a subquery.</p>\n\n<pre><code>select distinct a.objectID, a.time, a.x, a.y\n from Info a,\n (select objectID, max(time) time from Info group by objectID) b\n where a.objectID = b.objectID and a.time = b.time\n</code></pre>\n\n<p>EDIT: Added DISTINCT to prevent duplicate rows if one objectId has multiple records with the same time. Depends on your data if this is necessary, the question author mentioned there were many duplicate rows. (<em>added by <a href=\"https://stackoverflow.com/users/18771/tomalak\">Tomalak</a></em>)</p>\n" }, { "answer_id": 236828, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "<p>For what it's worth, here's another way of getting the desired result. I got into the habit of doing tricks like this in the MySQL 4.0 days, before subqueries were supported.</p>\n\n<pre><code>SELECT a.*\nFROM Info AS a\n LEFT OUTER JOIN Info AS b ON (a.objectID = b.objectID AND a.time &lt; b.time)\nWHERE b.objectID IS NULL;\n</code></pre>\n\n<p>In other words, show me the row where there no other row exists with the same objectID and a greater time. This naturally returns the row with the max time per objectID. No GROUP BY required.</p>\n" }, { "answer_id": 236919, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 1, "selected": false, "text": "<p>This is a pretty common way of getting at all the information in a row, for a row that is part of a group.</p>\n\n<pre><code>Select Info.*\nfrom Info\ninner join\n (select ObjectId, max(time) as Latest\n from Info\n group by ObjectId) I\non Info.ObjectId = I.ObjectID and Info.time = I.Latest\n</code></pre>\n\n<p>The same question has been asked in different forms a couple of times in the last couple of weeks. I forget how the questions were worded.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I have a table named Info of this schema: ``` int objectId; int time; int x, y; ``` There is a lot of redundant data in the system - that is, `objectId` is not UNIQUE. For each `objectId` there can be multiple entries of `time, x, y`. I want to retrieve a list of the latest position of each object. I started out with this query: ``` SELECT * FROM Info GROUP BY objectId ``` That got me just the kind of list I was looking for. However I want also to get just the latest times for each Object, so I tried: ``` SELECT * FROM Info GROUP BY objectId ORDER BY time DESC ``` This gave me a `time` descended list of Infos. However, **I don't think it did what I want - that is return me the latest `time, x, y` for each object**. Can anyone imagine a query to do what I want? **Update** I have tried the top three solutions to see how they perform against each other on a dataset of about 50,000 Infos. Here are the results: ``` -- NO INDEX: forever -- INDEX: 7.67 s SELECT a.* FROM Info AS a LEFT OUTER JOIN Info AS b ON (a.objectId = b.objectId AND a.time < b.time) WHERE b.objectId IS NULL; -- NO INDEX: 8.05 s -- INDEX: 0.17 s select a.objectId, a.time, a.x, a.y from Info a, (select objectId, max(time) time from Info group by objectId) b where a.objectId = b.objectId and a.time = b.time; -- NO INDEX: 8.30 s -- INDEX: 0.18 s SELECT A.time, A.objectId, B.x, B.y FROM ( SELECT max(time) as time, objectId FROM Info GROUP by objectId ) as A INNER JOIN Info B ON A.objectId = b.objectId AND A.time = b.time; ``` By a margin, it would seem `where` outperforms `inner join`.
One way is using a subquery. ``` select distinct a.objectID, a.time, a.x, a.y from Info a, (select objectID, max(time) time from Info group by objectID) b where a.objectID = b.objectID and a.time = b.time ``` EDIT: Added DISTINCT to prevent duplicate rows if one objectId has multiple records with the same time. Depends on your data if this is necessary, the question author mentioned there were many duplicate rows. (*added by [Tomalak](https://stackoverflow.com/users/18771/tomalak)*)
236,792
<p>I take care of critical app in my project. It does stuff related to parsing business msgs (legacy standard), processing them and then storing some results in a DB (another apps picks that up). After more then a year of my work (I've other apps to look after as well) the app is finally stable. I've introduced strict TDD policy and I have 20% unit test coverage (thank you Michael Feathers for your book!), most of it in critical parts. I have some white-box Fitness tests as well (whole business scenarios are covered there). I feel that I cannot further refactor this app and I'm safe to play hard with it. It's designed so badly, I want to rewrite it. App itself is around 20k of challenging legacy C/C++ code. There were other dependencies but I manged to decouple most of them.</p> <hr> <p>All I have is Sun C++ compiler, cppunitlite, STLPort and Boost. Please do not suggest other technologies (no XML, Java etc) as this is not the option in my organization. I'd like to do it with modern C++ (perhaps play with metaprogramming...), TDD from start to the end.</p> <p>There are about 30 types of msgs I need to parse. Each of them is composed of 3-10 lines, most of them are pretty similar. This is root of all evil -> lots of code duplication. Each msgs has a class describing how it should be parsed. Take a look at the main inheritance tree:</p> <pre><code> MSG_A MSG_B / \ / \ MSG_A_NEW MSG_A_CNL MSG_B_NEW MSG_B_CNL </code></pre> <p>Both trees goes much deeper. There are very small differences between MSG_A_NEW and MSG_B_NEW. It should be handled by single class that could be injected with some small customization.</p> <p>My initial plan it to have one generic msg class that will be customized. Some entity (builder... ?) will take a look at the msgs and initialize proper object that will be able to parse the msg. Another entity will be able to discover what line is it and this info will be used by builder. I'm planning to write several parsers that are responsible for parsing just one specific line. This will allow me to reuse it in parsing different msgs.</p> <p>There are several challenges that I struggle to solve in an elegant and extensible way. Each type of msg:</p> <p>has min and max number if lines - has some must-have lines - has some optional lines - certain lines must be at certain places (i.e. date cannot be before msg type), order matters</p> <p>I need to be able to validate format of the msgs.</p> <hr> <p>I'm not sure if I explained the design challenge here good enough. My design experience is very limited. I've been bug-fixing for a while now and finally I will have a change to do some fun codding :)</p> <p>What high-level advice do you have for that? Which design patterns can you identify in this description? Main design constraint is maintainability and extensibility with performance at the bottom (we have other bottlenecks anyway...).</p>
[ { "answer_id": 237077, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 0, "selected": false, "text": "<p>That <em>does</em> sound like a fun challenge. :-)</p>\n\n<p>Your \"initial plan\" sounds like a good one: factor out all of the similar processing between all of the messages and put the code for them in a base message class. The changing items can become virtual functions (such as <code>CheckForRequiredLines</code> or <code>VerifyLineOrder</code>, perhaps), possibly with default implementations for the most common case. Then derive other classes for the specific message types.</p>\n\n<p>It's hard to give generic advice for a design problem like this. It seems to me that your main parser function corresponds to the Factory Method pattern, but that's the only one I can easily identify. (I'm not too familiar with the names of design patterns -- I use many of them, but I only learned that they <em>have</em> names a couple years ago.)</p>\n" }, { "answer_id": 237488, "author": "mbyrne215", "author_id": 5241, "author_profile": "https://Stackoverflow.com/users/5241", "pm_score": 0, "selected": false, "text": "<p>You probably are already aware of this, but just in case... You should pick up/borrow the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201633612\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Gang of Four design patterns book</a> for help in identifying and applying appropriate patterns. This is the canonical reference, and it contains cross-references and tables to help you decide what patterns might fit your application. It might be difficult for people here to identify specific patterns that might help you, based just on that description.</p>\n" }, { "answer_id": 239693, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 0, "selected": false, "text": "<p>I would suggest looking at the libraries provided by boost, for example <code>Tuple</code> or <code>mpl::vector</code>. These libraries allows you to create a list of unrelated types and then operate over them. The very rough idea is that you have sequences of types for each message kind:</p>\n\n<pre><code>Seq1 -&gt; MSG_A_NEW, MSG_A_CNL\nSeq2 -&gt; MSG_B_NEW, MSG_B_CNL\n</code></pre>\n\n<p>Once you know your message kind, you use the appropriate tuple with a function template that applies the first tuple type to the data. Then the next entry in the tuple and so on.</p>\n\n<p>This does assume that the layout of your data streams are known at compile time, but it does have the advantage that you are not paying any runtime overhead for the data structures.</p>\n" }, { "answer_id": 242676, "author": "eli", "author_id": 12893, "author_profile": "https://Stackoverflow.com/users/12893", "pm_score": 2, "selected": true, "text": "<p>I would advise you <strong>not</strong> to inherit your specific message handling classes from base classes that contain the common code like this:</p>\n\n<pre><code>\n CommonHandler\n ^ ^\n | | = inheritance\n MsgAHandler\n ^ ^\n | |\nANewHandler ACnlHandler\n</code></pre>\n\n<p>This approach suffers from bad reusability: for example if you want to handle some kind of message that needs to do things from A_NEW and A_CNL, you would end up with multiple inheritance rather quickly.</p>\n\n<p>Instead I would choose a class containing the common code, that makes calls to an interface to customize that common code. Something like this:</p>\n\n<p><pre><code></p>\n\n<p>BasicHandler &lt;>--- IMsgHandler ------------\\\n 1 1 ^ ^ ^ ^ * | ^\n | | | | | | = inheritance\n MsgAHandler | | ANewHandler 1 |\n ACnlHandler HandlerContainer &lt;>-/ &lt;>- = containment</p>\n\n<p></pre></code></p>\n\n<p>The HandlerContainer class can be used to group the behaviour of other handlers together.</p>\n\n<p>This pattern is called 'Composite', if I'm not mistaken. And to create the correct instances of the handlers, you will of course need some kind of factory.</p>\n\n<p>Good luck!</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3579/" ]
I take care of critical app in my project. It does stuff related to parsing business msgs (legacy standard), processing them and then storing some results in a DB (another apps picks that up). After more then a year of my work (I've other apps to look after as well) the app is finally stable. I've introduced strict TDD policy and I have 20% unit test coverage (thank you Michael Feathers for your book!), most of it in critical parts. I have some white-box Fitness tests as well (whole business scenarios are covered there). I feel that I cannot further refactor this app and I'm safe to play hard with it. It's designed so badly, I want to rewrite it. App itself is around 20k of challenging legacy C/C++ code. There were other dependencies but I manged to decouple most of them. --- All I have is Sun C++ compiler, cppunitlite, STLPort and Boost. Please do not suggest other technologies (no XML, Java etc) as this is not the option in my organization. I'd like to do it with modern C++ (perhaps play with metaprogramming...), TDD from start to the end. There are about 30 types of msgs I need to parse. Each of them is composed of 3-10 lines, most of them are pretty similar. This is root of all evil -> lots of code duplication. Each msgs has a class describing how it should be parsed. Take a look at the main inheritance tree: ``` MSG_A MSG_B / \ / \ MSG_A_NEW MSG_A_CNL MSG_B_NEW MSG_B_CNL ``` Both trees goes much deeper. There are very small differences between MSG\_A\_NEW and MSG\_B\_NEW. It should be handled by single class that could be injected with some small customization. My initial plan it to have one generic msg class that will be customized. Some entity (builder... ?) will take a look at the msgs and initialize proper object that will be able to parse the msg. Another entity will be able to discover what line is it and this info will be used by builder. I'm planning to write several parsers that are responsible for parsing just one specific line. This will allow me to reuse it in parsing different msgs. There are several challenges that I struggle to solve in an elegant and extensible way. Each type of msg: has min and max number if lines - has some must-have lines - has some optional lines - certain lines must be at certain places (i.e. date cannot be before msg type), order matters I need to be able to validate format of the msgs. --- I'm not sure if I explained the design challenge here good enough. My design experience is very limited. I've been bug-fixing for a while now and finally I will have a change to do some fun codding :) What high-level advice do you have for that? Which design patterns can you identify in this description? Main design constraint is maintainability and extensibility with performance at the bottom (we have other bottlenecks anyway...).
I would advise you **not** to inherit your specific message handling classes from base classes that contain the common code like this: ``` CommonHandler ^ ^ | | = inheritance MsgAHandler ^ ^ | | ANewHandler ACnlHandler ``` This approach suffers from bad reusability: for example if you want to handle some kind of message that needs to do things from A\_NEW and A\_CNL, you would end up with multiple inheritance rather quickly. Instead I would choose a class containing the common code, that makes calls to an interface to customize that common code. Something like this: BasicHandler <>--- IMsgHandler ------------\ 1 1 ^ ^ ^ ^ \* | ^ | | | | | | = inheritance MsgAHandler | | ANewHandler 1 | ACnlHandler HandlerContainer <>-/ <>- = containment The HandlerContainer class can be used to group the behaviour of other handlers together. This pattern is called 'Composite', if I'm not mistaken. And to create the correct instances of the handlers, you will of course need some kind of factory. Good luck!
236,795
<p>I have a PHP class that creates a PNG image on the fly and sends it to browser. PHP manual says that I need to make sure that <em>imagedestroy</em> function is called at end to release the memory. Now, if I weren't using a class, I would have some code like this:</p> <pre><code>function shutdown_func() { global $img; if ($img) imagedestroy($img); } register_shutdown_function("shutdown_func"); </code></pre> <p>However, I believe that appropriate place for my class would be to place a call to <em>imagedestroy</em> in class' destructor.</p> <p>I failed to find out if destructors get called the same way shutdown functions does? For example, if execution stops when user presses the STOP button in browser.</p> <p>Note: whatever you write in your answer, please point to some article or manual page (URL) that supports it.</p>
[ { "answer_id": 236811, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 0, "selected": false, "text": "<p>I think one big thing that you have missed is that all the memory PHP has allocated during script execution is freed once the script terminates. Even if the user presses the stop-button, PHP processes the script until it is finished, gives it back to the HTTP daemon to be served to the visitor (or not, depending on how clever the daemon is).</p>\n\n<p>So, explicitly freeing up memory at the end of script execution is a bit redundant. Some might argue that it would be a good thing to do, but it's still redundant.</p>\n\n<p>But, on the topic of class destructors, they are called whenever the object is destroyed, either explicitly by <code>unset()</code> or at script completion/termination.</p>\n\n<p>The recommendation of the developer explicitly freeing up the memory used in image manipulation is sure just to make absolutely sure not to have a memory leak, as bitmaps can be straining on the memory side of things (height * width * bit depth * 3 (+ 1 if you have an alpha channel))</p>\n\n<p>To satisfy your Wikipedian needs:</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/language.oop5.decon.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/language.oop5.decon.php</a></li>\n<li><a href=\"http://php.net/manual/en/function.unset.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.unset.php</a></li>\n</ul>\n" }, { "answer_id": 236830, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 5, "selected": true, "text": "<p>I just tested with Apache, PHP being used as Apache module. I created an endless loop like this:</p>\n\n<pre><code>&lt;?php\nclass X\n{\n function __destruct()\n {\n $fp = fopen(\"/var/www/htdocs/dtor.txt\", \"w+\");\n fputs($fp, \"Destroyed\\n\");\n fclose($fp);\n }\n};\n\n$obj = new X();\nwhile (true) {\n // do nothing\n}\n?&gt;\n</code></pre>\n\n<p>Here's what I found out:</p>\n\n<ul>\n<li>pressing STOP button in Firefox does not stop this script</li>\n<li>If I shut down Apache, destructor does not get called</li>\n<li>It stops when it reaches PHP max_execution_time and destuctor does not get called</li>\n</ul>\n\n<p>However, doing this:</p>\n\n<pre><code>&lt;?php\nfunction shutdown_func() {\n $fp = fopen(\"/var/www/htdocs/dtor.txt\", \"w+\");\n fputs($fp, \"Destroyed2\\n\");\n fclose($fp);\n}\nregister_shutdown_function(\"shutdown_func\");\n\nwhile (true) {\n // do nothing\n}\n?&gt;\n</code></pre>\n\n<p>shutdown_func gets called. So this means that class destuctor is not that good as shutdown functions.</p>\n" }, { "answer_id": 237191, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 2, "selected": false, "text": "<p>Based on the principle that you should <a href=\"http://www.pragprog.com/the-pragmatic-programmer/extracts/tips\" rel=\"nofollow noreferrer\">finish what you start</a>, I'd say the destructor is the correct place for the free call.</p>\n\n<p>The <a href=\"http://www.php.net/manual/en/language.oop5.decon.php\" rel=\"nofollow noreferrer\">destructor</a> will be called when the object is disposed of, whereas a <a href=\"http://php.net/manual/en/function.register-shutdown-function.php\" rel=\"nofollow noreferrer\">shutdown function</a> will not be called until script execution finishes. As noted by Wolfie, these won't necessarily happen if you forcibly halt the server or the script, but at that time, the memory allocated by PHP will be freed anyway.</p>\n\n<p>Also noted by Wolfie, PHP will free up script resources when the script closes, so if you're only instantiating one of these objects, then you probably wouldn't notice a massive difference. However, if you later do end up instantiating these things, or do so in a loop, then you probably don't want to have to worry about a sudden spike in memory usage, so for the sake of future sanity, I return to my original recommendation; put it in the destructor.</p>\n" }, { "answer_id": 31690231, "author": "therightstuff", "author_id": 2860309, "author_profile": "https://Stackoverflow.com/users/2860309", "pm_score": 1, "selected": false, "text": "<p>I recently had trouble with this as I was trying to handle destruction specifically for the case where the server experiences a timeout and I wanted to include class data in the error log. I would receive an error when referencing &amp;$this (although I've seen it done in a few examples, possibly a version issue or a symfony side-effect), and the solution I came up with was fairly clean:</p>\n\n<pre><code>class MyClass\n{\n protected $myVar;\n\n /**\n * constructor, registers shutdown handling\n */\n public function __construct()\n {\n $this-&gt;myVar = array();\n\n // workaround: set $self because $this fails\n $self = $this;\n // register for error logging in case of timeout\n $shutdown = function () use (&amp;$self) {\n $self-&gt;shutdown();\n };\n register_shutdown_function($shutdown);\n }\n\n /**\n * handle shutdown events\n */\n public function shutdown()\n {\n $error = error_get_last();\n // if shutdown in error\n if ($error['type'] === E_ERROR) {\n // write contents to error log\n error_log('MyClass-&gt;myVar on shutdown' . json_encode($this-&gt;myVar), 0);\n }\n }\n\n ...\n</code></pre>\n\n<p>Hope this helps someone!</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
I have a PHP class that creates a PNG image on the fly and sends it to browser. PHP manual says that I need to make sure that *imagedestroy* function is called at end to release the memory. Now, if I weren't using a class, I would have some code like this: ``` function shutdown_func() { global $img; if ($img) imagedestroy($img); } register_shutdown_function("shutdown_func"); ``` However, I believe that appropriate place for my class would be to place a call to *imagedestroy* in class' destructor. I failed to find out if destructors get called the same way shutdown functions does? For example, if execution stops when user presses the STOP button in browser. Note: whatever you write in your answer, please point to some article or manual page (URL) that supports it.
I just tested with Apache, PHP being used as Apache module. I created an endless loop like this: ``` <?php class X { function __destruct() { $fp = fopen("/var/www/htdocs/dtor.txt", "w+"); fputs($fp, "Destroyed\n"); fclose($fp); } }; $obj = new X(); while (true) { // do nothing } ?> ``` Here's what I found out: * pressing STOP button in Firefox does not stop this script * If I shut down Apache, destructor does not get called * It stops when it reaches PHP max\_execution\_time and destuctor does not get called However, doing this: ``` <?php function shutdown_func() { $fp = fopen("/var/www/htdocs/dtor.txt", "w+"); fputs($fp, "Destroyed2\n"); fclose($fp); } register_shutdown_function("shutdown_func"); while (true) { // do nothing } ?> ``` shutdown\_func gets called. So this means that class destuctor is not that good as shutdown functions.
236,801
<p>That's basically the question, is there a "right" way to implement <code>operator&lt;&lt;</code> ? Reading <a href="http://bytes.com/forum/thread170304.html" rel="noreferrer">this</a> I can see that something like:</p> <pre><code>friend bool operator&lt;&lt;(obj const&amp; lhs, obj const&amp; rhs); </code></pre> <p>is preferred to something like </p> <pre><code>ostream&amp; operator&lt;&lt;(obj const&amp; rhs); </code></pre> <p>But I can't quite see why should I use one or the other.</p> <p>My personal case is:</p> <pre><code>friend ostream &amp; operator&lt;&lt;(ostream &amp;os, const Paragraph&amp; p) { return os &lt;&lt; p.to_str(); } </code></pre> <p>But I could probably do:</p> <pre><code>ostream &amp; operator&lt;&lt;(ostream &amp;os) { return os &lt;&lt; paragraph; } </code></pre> <p>What rationale should I base this decision on?</p> <p><em>Note</em>:</p> <pre><code> Paragraph::to_str = (return paragraph) </code></pre> <p>where paragraph's a string.</p>
[ { "answer_id": 236806, "author": "Magnus Hoff", "author_id": 2971, "author_profile": "https://Stackoverflow.com/users/2971", "pm_score": 6, "selected": false, "text": "<p>You can not do it as a member function, because the implicit <code>this</code> parameter is the left hand side of the <code>&lt;&lt;</code>-operator. (Hence, you would need to add it as a member function to the <code>ostream</code>-class. Not good :)</p>\n\n<p>Could you do it as a free function without <code>friend</code>ing it? That's what I prefer, because it makes it clear that this is an integration with <code>ostream</code>, and not a core functionality of your class.</p>\n" }, { "answer_id": 236813, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "<p>The signature:</p>\n\n<pre><code>bool operator&lt;&lt;(const obj&amp;, const obj&amp;);\n</code></pre>\n\n<p>Seems rather suspect, this does not fit the <code>stream</code> convention nor the bitwise convention so it looks like a case of operator overloading abuse, <code>operator &lt;</code> should return <code>bool</code> but <code>operator &lt;&lt;</code> should probably return something else.</p>\n\n<p>If you meant so say:</p>\n\n<pre><code>ostream&amp; operator&lt;&lt;(ostream&amp;, const obj&amp;); \n</code></pre>\n\n<p>Then since you can't add functions to <code>ostream</code> by necessity the function must be a free function, whether it a <code>friend</code> or not depends on what it has to access (if it doesn't need to access private or protected members there's no need to make it friend).</p>\n" }, { "answer_id": 236837, "author": "XPav", "author_id": 27550, "author_profile": "https://Stackoverflow.com/users/27550", "pm_score": 4, "selected": false, "text": "<p>It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.</p>\n\n<p>I've actually taken to collecting all of these ostream output free functions in an \"ostreamhelpers\" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.</p>\n" }, { "answer_id": 237074, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 8, "selected": true, "text": "<p>The problem here is in your interpretation of the article you <a href=\"http://bytes.com/forum/thread170304.html\" rel=\"noreferrer\">link</a>.</p>\n\n<h3>Equality</h3>\n\n<p>This article is about somebody that is having problems correctly defining the bool relationship operators.</p>\n\n<p>The operator:</p>\n\n<ul>\n<li>Equality == and !=</li>\n<li>Relationship &lt; > &lt;= >=</li>\n</ul>\n\n<p>These operators should return a bool as they are comparing two objects of the same type. It is usually easiest to define these operators as part of the class. This is because a class is automatically a friend of itself so objects of type Paragraph can examine each other (even each others private members).</p>\n\n<p>There is an argument for making these free standing functions as this lets auto conversion convert both sides if they are not the same type, while member functions only allow the rhs to be auto converted. I find this a paper man argument as you don't really want auto conversion happening in the first place (usually). But if this is something you want (I don't recommend it) then making the comparators free standing can be advantageous.</p>\n\n<h3>Streaming</h3>\n\n<p>The stream operators:</p>\n\n<ul>\n<li>operator &lt;&lt; output</li>\n<li>operator >> input</li>\n</ul>\n\n<p>When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you.</p>\n\n<p>It is also traditional for these objects to return a reference to a stream object so you can chain stream operations together.</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nclass Paragraph\n{\n public:\n explicit Paragraph(std::string const&amp; init)\n :m_para(init)\n {}\n\n std::string const&amp; to_str() const\n {\n return m_para;\n }\n\n bool operator==(Paragraph const&amp; rhs) const\n {\n return m_para == rhs.m_para;\n }\n bool operator!=(Paragraph const&amp; rhs) const\n {\n // Define != operator in terms of the == operator\n return !(this-&gt;operator==(rhs));\n }\n bool operator&lt;(Paragraph const&amp; rhs) const\n {\n return m_para &lt; rhs.m_para;\n }\n private:\n friend std::ostream &amp; operator&lt;&lt;(std::ostream &amp;os, const Paragraph&amp; p);\n std::string m_para;\n};\n\nstd::ostream &amp; operator&lt;&lt;(std::ostream &amp;os, const Paragraph&amp; p)\n{\n return os &lt;&lt; p.to_str();\n}\n\n\nint main()\n{\n Paragraph p(\"Plop\");\n Paragraph q(p);\n\n std::cout &lt;&lt; p &lt;&lt; std::endl &lt;&lt; (p == q) &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 237111, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": false, "text": "<h1>If possible, as non-member and non-friend functions.</h1>\n\n<p>As described by Herb Sutter and Scott Meyers, prefer non-friend non-member functions to member functions, to help increase encapsulation.</p>\n\n<p>In some cases, like C++ streams, you won't have the choice and must use non-member functions.</p>\n\n<p>But still, it does not mean you have to make these functions friends of your classes: These functions can still acess your class through your class accessors. If you succeed in writting those functions this way, then you won.</p>\n\n<h1>About operator &lt;&lt; and >> prototypes</h1>\n\n<p>I believe the examples you gave in your question are wrong. For example;</p>\n\n<pre><code>ostream &amp; operator&lt;&lt;(ostream &amp;os) {\n return os &lt;&lt; paragraph;\n}\n</code></pre>\n\n<p>I can't even start to think how this method could work in a stream.</p>\n\n<p>Here are the two ways to implement the &lt;&lt; and >> operators.</p>\n\n<p>Let's say you want to use a stream-like object of type T.</p>\n\n<p>And that you want to extract/insert from/into T the relevant data of your object of type Paragraph.</p>\n\n<h2>Generic operator &lt;&lt; and >> function prototypes</h2>\n\n<p>The first being as functions:</p>\n\n<pre><code>// T &lt;&lt; Paragraph\nT &amp; operator &lt;&lt; (T &amp; p_oOutputStream, const Paragraph &amp; p_oParagraph)\n{\n // do the insertion of p_oParagraph\n return p_oOutputStream ;\n}\n\n// T &gt;&gt; Paragraph\nT &amp; operator &gt;&gt; (T &amp; p_oInputStream, const Paragraph &amp; p_oParagraph)\n{\n // do the extraction of p_oParagraph\n return p_oInputStream ;\n}\n</code></pre>\n\n<h2>Generic operator &lt;&lt; and >> method prototypes</h2>\n\n<p>The second being as methods:</p>\n\n<pre><code>// T &lt;&lt; Paragraph\nT &amp; T::operator &lt;&lt; (const Paragraph &amp; p_oParagraph)\n{\n // do the insertion of p_oParagraph\n return *this ;\n}\n\n// T &gt;&gt; Paragraph\nT &amp; T::operator &gt;&gt; (const Paragraph &amp; p_oParagraph)\n{\n // do the extraction of p_oParagraph\n return *this ;\n}\n</code></pre>\n\n<p>Note that to use this notation, you must extend T's class declaration. For STL objects, this is not possible (you are not supposed to modify them...).</p>\n\n<h1>And what if T is a C++ stream?</h1>\n\n<p>Here are the prototypes of the same &lt;&lt; and >> operators for C++ streams.</p>\n\n<h2>For generic basic_istream and basic_ostream</h2>\n\n<p>Note that is case of streams, as you can't modify the C++ stream, you must implement the functions. Which means something like:</p>\n\n<pre><code>// OUTPUT &lt;&lt; Paragraph\ntemplate &lt;typename charT, typename traits&gt;\nstd::basic_ostream&lt;charT,traits&gt; &amp; operator &lt;&lt; (std::basic_ostream&lt;charT,traits&gt; &amp; p_oOutputStream, const Paragraph &amp; p_oParagraph)\n{\n // do the insertion of p_oParagraph\n return p_oOutputStream ;\n}\n\n// INPUT &gt;&gt; Paragraph\ntemplate &lt;typename charT, typename traits&gt;\nstd::basic_istream&lt;charT,traits&gt; &amp; operator &gt;&gt; (std::basic_istream&lt;charT,traits&gt; &amp; p_oInputStream, const CMyObject &amp; p_oParagraph)\n{\n // do the extract of p_oParagraph\n return p_oInputStream ;\n}\n</code></pre>\n\n<h2>For char istream and ostream</h2>\n\n<p>The following code will work only for char-based streams.</p>\n\n<pre><code>// OUTPUT &lt;&lt; A\nstd::ostream &amp; operator &lt;&lt; (std::ostream &amp; p_oOutputStream, const Paragraph &amp; p_oParagraph)\n{\n // do the insertion of p_oParagraph\n return p_oOutputStream ;\n}\n\n// INPUT &gt;&gt; A\nstd::istream &amp; operator &gt;&gt; (std::istream &amp; p_oInputStream, const Paragraph &amp; p_oParagraph)\n{\n // do the extract of p_oParagraph\n return p_oInputStream ;\n}\n</code></pre>\n\n<p>Rhys Ulerich commented about the fact the char-based code is but a \"specialization\" of the generic code above it. Of course, Rhys is right: I don't recommend the use of the char-based example. It is only given here because it's simpler to read. As it is only viable if you only work with char-based streams, you should avoid it on platforms where wchar_t code is common (i.e. on Windows).</p>\n\n<p>Hope this will help.</p>\n" }, { "answer_id": 8940570, "author": "Rohit Vipin Mathews", "author_id": 1155650, "author_profile": "https://Stackoverflow.com/users/1155650", "pm_score": 0, "selected": false, "text": "<p><code>operator&lt;&lt;</code> implemented as a friend function:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nclass Samp\n{\npublic:\n int ID;\n string strName; \n friend std::ostream&amp; operator&lt;&lt;(std::ostream &amp;os, const Samp&amp; obj);\n};\n std::ostream&amp; operator&lt;&lt;(std::ostream &amp;os, const Samp&amp; obj)\n {\n os &lt;&lt; obj.ID&lt;&lt; “ ” &lt;&lt; obj.strName;\n return os;\n }\n\nint main()\n{\n Samp obj, obj1;\n obj.ID = 100;\n obj.strName = \"Hello\";\n obj1=obj;\n cout &lt;&lt; obj &lt;&lt;endl&lt;&lt; obj1;\n\n} \n</code></pre>\n\n<blockquote>\n <p>OUTPUT:<br>\n 100 Hello<br>\n 100 Hello</p>\n</blockquote>\n\n<p>This can be a friend function only because the object is on the right hand side of <code>operator&lt;&lt;</code> and argument <code>cout</code> is on the left hand side. So this can't be a member function to the class, it can only be a friend function.</p>\n" }, { "answer_id": 35130062, "author": "Nehigienix", "author_id": 5785958, "author_profile": "https://Stackoverflow.com/users/5785958", "pm_score": 0, "selected": false, "text": "<p>friend operator = equal rights as class</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Object&amp; object) {\n os &lt;&lt; object._atribute1 &lt;&lt; \" \" &lt;&lt; object._atribute2 &lt;&lt; \" \" &lt;&lt; atribute._atribute3 &lt;&lt; std::endl;\n return os;\n}\n</code></pre>\n" }, { "answer_id": 44325720, "author": "ashrasmun", "author_id": 2059351, "author_profile": "https://Stackoverflow.com/users/2059351", "pm_score": 2, "selected": false, "text": "<p>Just for completion sake, I would like to add that you indeed <strong>can</strong> create an operator <code>ostream&amp; operator &lt;&lt; (ostream&amp; os)</code> inside a class and it can work. From what I know it's not a good idea to use it, because it's very convoluted and unintuitive.</p>\n\n<p>Let's assume we have this code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nstruct Widget\n{\n string name;\n\n Widget(string _name) : name(_name) {}\n\n ostream&amp; operator &lt;&lt; (ostream&amp; os)\n {\n return os &lt;&lt; name;\n }\n};\n\nint main()\n{\n Widget w1(\"w1\");\n Widget w2(\"w2\");\n\n // These two won't work\n {\n // Error: operand types are std::ostream &lt;&lt; std::ostream\n // cout &lt;&lt; w1.operator&lt;&lt;(cout) &lt;&lt; '\\n';\n\n // Error: operand types are std::ostream &lt;&lt; Widget\n // cout &lt;&lt; w1 &lt;&lt; '\\n';\n }\n\n // However these two work\n {\n w1 &lt;&lt; cout &lt;&lt; '\\n';\n\n // Call to w1.operator&lt;&lt;(cout) returns a reference to ostream&amp;\n w2 &lt;&lt; w1.operator&lt;&lt;(cout) &lt;&lt; '\\n';\n }\n\n return 0;\n}\n</code></pre>\n\n<p>So to sum it up - you can do it, but you most probably shouldn't :)</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161/" ]
That's basically the question, is there a "right" way to implement `operator<<` ? Reading [this](http://bytes.com/forum/thread170304.html) I can see that something like: ``` friend bool operator<<(obj const& lhs, obj const& rhs); ``` is preferred to something like ``` ostream& operator<<(obj const& rhs); ``` But I can't quite see why should I use one or the other. My personal case is: ``` friend ostream & operator<<(ostream &os, const Paragraph& p) { return os << p.to_str(); } ``` But I could probably do: ``` ostream & operator<<(ostream &os) { return os << paragraph; } ``` What rationale should I base this decision on? *Note*: ``` Paragraph::to_str = (return paragraph) ``` where paragraph's a string.
The problem here is in your interpretation of the article you [link](http://bytes.com/forum/thread170304.html). ### Equality This article is about somebody that is having problems correctly defining the bool relationship operators. The operator: * Equality == and != * Relationship < > <= >= These operators should return a bool as they are comparing two objects of the same type. It is usually easiest to define these operators as part of the class. This is because a class is automatically a friend of itself so objects of type Paragraph can examine each other (even each others private members). There is an argument for making these free standing functions as this lets auto conversion convert both sides if they are not the same type, while member functions only allow the rhs to be auto converted. I find this a paper man argument as you don't really want auto conversion happening in the first place (usually). But if this is something you want (I don't recommend it) then making the comparators free standing can be advantageous. ### Streaming The stream operators: * operator << output * operator >> input When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you. It is also traditional for these objects to return a reference to a stream object so you can chain stream operations together. ``` #include <iostream> class Paragraph { public: explicit Paragraph(std::string const& init) :m_para(init) {} std::string const& to_str() const { return m_para; } bool operator==(Paragraph const& rhs) const { return m_para == rhs.m_para; } bool operator!=(Paragraph const& rhs) const { // Define != operator in terms of the == operator return !(this->operator==(rhs)); } bool operator<(Paragraph const& rhs) const { return m_para < rhs.m_para; } private: friend std::ostream & operator<<(std::ostream &os, const Paragraph& p); std::string m_para; }; std::ostream & operator<<(std::ostream &os, const Paragraph& p) { return os << p.to_str(); } int main() { Paragraph p("Plop"); Paragraph q(p); std::cout << p << std::endl << (p == q) << std::endl; } ```
236,810
<p>I'm trying to extract an uploaded zip file and store its contents in the database, one entry per file. The rubyzip library has nearly no useful documentation.</p> <p>There is an assets table that has key :string (file name) and data :binary (file contents).</p> <p>I'm using the rubyzip library, and have made it as far as this:</p> <pre><code>Zip::ZipFile.open(@file_data.local_path) do |zipfile| zipfile.each do |entry| next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file? asset = self.assets.build asset.key = entry.name asset.data = ?? # what goes here? end end </code></pre> <p>How can I set the data from a ZipEntry? Do I have to use a temp file?</p>
[ { "answer_id": 236827, "author": "Ivan", "author_id": 16957, "author_profile": "https://Stackoverflow.com/users/16957", "pm_score": 3, "selected": false, "text": "<p>It would seem that you can either use the read_local_entry method like this:</p>\n\n<pre><code>asset.data = entry.read_local_entry {|z| z.read }\n</code></pre>\n\n<p>Or, you could save the entry with this method:</p>\n\n<pre><code>data = entry.extract \"#{RAILS_ROOT}/#{entry.name}\"\nasset.data = File.read(\"#{RAILS_ROOT}/#{entry.name}\")\n</code></pre>\n\n<p>I'm not sure how those will work, but maybe they'll help you find the right method (if this ain't it).</p>\n\n<p>And, one more alternative:</p>\n\n<pre><code>asset.data = zipfile.file.read(entry.name)\n</code></pre>\n" }, { "answer_id": 236836, "author": "jcoby", "author_id": 2884, "author_profile": "https://Stackoverflow.com/users/2884", "pm_score": 4, "selected": false, "text": "<p>Found an even more simple way: </p>\n\n<pre><code>asset.data = entry.get_input_stream.read\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884/" ]
I'm trying to extract an uploaded zip file and store its contents in the database, one entry per file. The rubyzip library has nearly no useful documentation. There is an assets table that has key :string (file name) and data :binary (file contents). I'm using the rubyzip library, and have made it as far as this: ``` Zip::ZipFile.open(@file_data.local_path) do |zipfile| zipfile.each do |entry| next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file? asset = self.assets.build asset.key = entry.name asset.data = ?? # what goes here? end end ``` How can I set the data from a ZipEntry? Do I have to use a temp file?
Found an even more simple way: ``` asset.data = entry.get_input_stream.read ```
236,859
<p>Any python libs for parsing Bind zone files? Basically something that will aid in adding/removing zones and records. This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution. </p>
[ { "answer_id": 237236, "author": "Michael Gundlach", "author_id": 4105, "author_profile": "https://Stackoverflow.com/users/4105", "pm_score": 0, "selected": false, "text": "<p>See answer above about bicop.</p>\n\n<p>As an aside, the Python Package Index at <a href=\"http://pypi.python.org/pypi\" rel=\"nofollow noreferrer\">http://pypi.python.org/pypi</a> is a great place to look for Python packages.</p>\n\n<p><strong>EDIT</strong>: The below may still be helpful to someone trying to figure out simple parsing, but bicop is apparently an existing solution.</p>\n\n<p>If someone has modified the config by hand, and you don't want to overwrite it, does that imply that you wish to insert/remove lines from an existing config, leaving all comments etc intact? That does prevent parsing then re-outputting the config, but that's a positive as well -- you don't need to fully parse the file to accomplish your goal.</p>\n\n<p>To add a record, you might try a simple approach like</p>\n\n<pre><code># define zone_you_care_about and line_you_wish_to_insert first, then:\nfor line in bindfile.read():\n out.write(line + '\\n')\n if ('zone \"%s\" in' % zone_you_care_about) in line:\n out.write(line_you_wish_to_insert)\n</code></pre>\n\n<p>Similar code works for removing a line:</p>\n\n<pre><code># define zone_you_care_about and relevant_text_to_remove, then:\nfor line in bindfile.read():\n if not relevant_text_to_remove in line:\n out.write(line + '\\n')\n</code></pre>\n\n<p>You may get as far as you need with simple snippets of code like this.</p>\n" }, { "answer_id": 2145812, "author": "NorbertK", "author_id": 153578, "author_profile": "https://Stackoverflow.com/users/153578", "pm_score": 4, "selected": true, "text": "<p>I was unable to use bicop for classical zone files like these:</p>\n\n<pre><code> $TTL 86400\n@ IN SOA ns1.first-ns.de. postmaster.robot.first-ns.de. (\n 2006040800 ; serial\n 14400 ; refresh\n 1800 ; retry\n 604800 ; expire\n 86400 ) ; minimum\n\n@\n\n IN NS ns1.first-ns.de.\n</code></pre>\n\n<p>I will have a look at <a href=\"http://www.dnspython.org/\" rel=\"nofollow noreferrer\">dnspython</a></p>\n" }, { "answer_id": 6710660, "author": "jccnu619", "author_id": 846874, "author_profile": "https://Stackoverflow.com/users/846874", "pm_score": 0, "selected": false, "text": "<p>I know this is old but the only working one I could find is called iscpy. You can do an easy_install.</p>\n\n<pre><code>easy_install iscpy\n</code></pre>\n\n<p>Then in python:</p>\n\n<pre><code>import iscpy\niscpy.ParseISCString(open('somefile.conf', 'r').read())\n</code></pre>\n\n<p>Which returns a dictionary.</p>\n" }, { "answer_id": 8004435, "author": "Boden Garman", "author_id": 584423, "author_profile": "https://Stackoverflow.com/users/584423", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://pypi.python.org/pypi/easyzone\" rel=\"noreferrer\">easyzone</a> is a nice layer over dnspython</p>\n\n<p><a href=\"http://pypi.python.org/pypi/zoner/1.4.1\" rel=\"noreferrer\">Zoner</a> provides a web-interface for editing zone files and makes use of easyzone.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
Any python libs for parsing Bind zone files? Basically something that will aid in adding/removing zones and records. This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution.
I was unable to use bicop for classical zone files like these: ``` $TTL 86400 @ IN SOA ns1.first-ns.de. postmaster.robot.first-ns.de. ( 2006040800 ; serial 14400 ; refresh 1800 ; retry 604800 ; expire 86400 ) ; minimum @ IN NS ns1.first-ns.de. ``` I will have a look at [dnspython](http://www.dnspython.org/)
236,861
<p>I have a method that creates a MessageDigest (a hash) from a file, and I need to do this to a lot of files (>= 100,000). How big should I make the buffer used to read from the files to maximize performance?</p> <p>Most everyone is familiar with the basic code (which I'll repeat here just in case):</p> <pre><code>MessageDigest md = MessageDigest.getInstance( "SHA" ); FileInputStream ios = new FileInputStream( "myfile.bmp" ); byte[] buffer = new byte[4 * 1024]; // what should this value be? int read = 0; while( ( read = ios.read( buffer ) ) &gt; 0 ) md.update( buffer, 0, read ); ios.close(); md.digest(); </code></pre> <p>What is the ideal size of the buffer to maximize throughput? I know this is system dependent, and I'm pretty sure its OS, FileSystem, <em>and</em> HDD dependent, and there maybe other hardware/software in the mix. </p> <p>(I should point out that I'm somewhat new to Java, so this may just be some Java API call I don't know about.)</p> <p><strong>Edit:</strong> I do not know ahead of time the kinds of systems this will be used on, so I can't assume a whole lot. (I'm using Java for that reason.)</p> <p><strong>Edit:</strong> The code above is missing things like try..catch to make the post smaller</p>
[ { "answer_id": 236877, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.</p>\n\n<p>Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.</p>\n" }, { "answer_id": 236947, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 3, "selected": false, "text": "<p>In the ideal case we should have enough memory to read the file in one read operation.\nThat would be the best performer because we let the system manage File System , allocation units and HDD at will.\nIn practice you are fortunate to know the file sizes in advance, just use the average file size rounded up to 4K (default allocation unit on NTFS).\nAnd best of all : create a benchmark to test multiple options. </p>\n" }, { "answer_id": 236977, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 3, "selected": false, "text": "<p>You could use the BufferedStreams/readers and then use their buffer sizes.</p>\n\n<p>I believe the BufferedXStreams are using 8192 as the buffer size, but like Ovidiu said, you should probably run a test on a whole bunch of options. Its really going to depend on the filesystem and disk configurations as to what the best sizes are.</p>\n" }, { "answer_id": 236994, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>In most cases, it really doesn't matter that much. Just pick a good size such as 4K or 16K and stick with it. If you're <em>positive</em> that this is the bottleneck in your application, then you should start profiling to find the optimal buffer size. If you pick a size that's too small, you'll waste time doing extra I/O operations and extra function calls. If you pick a size that's too big, you'll start seeing a lot of cache misses which will really slow you down. Don't use a buffer bigger than your L2 cache size.</p>\n" }, { "answer_id": 237021, "author": "Maglob", "author_id": 27520, "author_profile": "https://Stackoverflow.com/users/27520", "pm_score": 1, "selected": false, "text": "<p>As already mentioned in other answers, use BufferedInputStreams.</p>\n\n<p>After that, I guess the buffer size does not really matter. Either the program is I/O bound, and growing buffer size over BIS default, will not make any big impact on performance.</p>\n\n<p>Or the program is CPU bound inside the MessageDigest.update(), and majority of the time is not spent in the application code, so tweaking it will not help.</p>\n\n<p>(Hmm... with multiple cores, threads might help.)</p>\n" }, { "answer_id": 237038, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 2, "selected": false, "text": "<p>Reading files using Java NIO's FileChannel and MappedByteBuffer will most likely result in a solution that will be much faster than any solution involving FileInputStream. Basically, memory-map large files, and use direct buffers for small ones.</p>\n" }, { "answer_id": 237495, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 9, "selected": true, "text": "<p>Optimum buffer size is related to a number of things: file system block size, CPU cache size and cache latency.</p>\n\n<p>Most file systems are configured to use block sizes of 4096 or 8192. In theory, if you configure your buffer size so you are reading a few bytes more than the disk block, the operations with the file system can be extremely inefficient (i.e. if you configured your buffer to read 4100 bytes at a time, each read would require 2 block reads by the file system). If the blocks are already in cache, then you wind up paying the price of RAM -> L3/L2 cache latency. If you are unlucky and the blocks are not in cache yet, the you pay the price of the disk->RAM latency as well.</p>\n\n<p>This is why you see most buffers sized as a power of 2, and generally larger than (or equal to) the disk block size. This means that one of your stream reads could result in multiple disk block reads - but those reads will always use a full block - no wasted reads.</p>\n\n<p>Now, this is offset quite a bit in a typical streaming scenario because the block that is read from disk is going to still be in memory when you hit the next read (we are doing sequential reads here, after all) - so you wind up paying the RAM -> L3/L2 cache latency price on the next read, but not the disk->RAM latency. In terms of order of magnitude, disk->RAM latency is so slow that it pretty much swamps any other latency you might be dealing with.</p>\n\n<p>So, I suspect that if you ran a test with different cache sizes (haven't done this myself), you will probably find a big impact of cache size up to the size of the file system block. Above that, I suspect that things would level out pretty quickly.</p>\n\n<p>There are a <em>ton</em> of conditions and exceptions here - the complexities of the system are actually quite staggering (just getting a handle on L3 -> L2 cache transfers is mind bogglingly complex, and it changes with every CPU type).</p>\n\n<p>This leads to the 'real world' answer: If your app is like 99% out there, set the cache size to 8192 and move on (even better, choose encapsulation over performance and use BufferedInputStream to hide the details). If you are in the 1% of apps that are highly dependent on disk throughput, craft your implementation so you can swap out different disk interaction strategies, and provide the knobs and dials to allow your users to test and optimize (or come up with some self optimizing system).</p>\n" }, { "answer_id": 41480018, "author": "Adrian Krebs", "author_id": 4304038, "author_profile": "https://Stackoverflow.com/users/4304038", "pm_score": 0, "selected": false, "text": "<p>1024 is appropriate for a wide variety of circumstances, although in practice you may see better performance with a larger or smaller buffer size. </p>\n\n<p>This would depend on a number of factors including file system block\nsize and CPU hardware.</p>\n\n<p>It is also common to choose a power of 2 for the buffer size, since most underlying\nhardware is structured with fle block and cache sizes that are a power of 2. The Buffered\nclasses allow you to specify the buffer size in the constructor. If none is provided, they\nuse a default value, which is a power of 2 in most JVMs.</p>\n\n<p>Regardless of which buffer size you choose, the biggest performance increase you will\nsee is moving from nonbuffered to buffered file access. Adjusting the buffer size may\nimprove performance slightly, but unless you are using an extremely small or extremely\nlarge buffer size, it is unlikely to have a signifcant impact.</p>\n" }, { "answer_id": 41480390, "author": "GoForce5500", "author_id": 5311885, "author_profile": "https://Stackoverflow.com/users/5311885", "pm_score": 2, "selected": false, "text": "<p>In BufferedInputStream‘s source you will find: private static int DEFAULT_BUFFER_SIZE = 8192;<br/>\nSo it's okey for you to use that default value.<br/>\nBut if you can figure out some more information you will get more valueable answers.<br/>\nFor example, your adsl maybe preffer a buffer of 1454 bytes, thats because TCP/IP's payload. For disks, you may use a value that match your disk's block size.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11889/" ]
I have a method that creates a MessageDigest (a hash) from a file, and I need to do this to a lot of files (>= 100,000). How big should I make the buffer used to read from the files to maximize performance? Most everyone is familiar with the basic code (which I'll repeat here just in case): ``` MessageDigest md = MessageDigest.getInstance( "SHA" ); FileInputStream ios = new FileInputStream( "myfile.bmp" ); byte[] buffer = new byte[4 * 1024]; // what should this value be? int read = 0; while( ( read = ios.read( buffer ) ) > 0 ) md.update( buffer, 0, read ); ios.close(); md.digest(); ``` What is the ideal size of the buffer to maximize throughput? I know this is system dependent, and I'm pretty sure its OS, FileSystem, *and* HDD dependent, and there maybe other hardware/software in the mix. (I should point out that I'm somewhat new to Java, so this may just be some Java API call I don't know about.) **Edit:** I do not know ahead of time the kinds of systems this will be used on, so I can't assume a whole lot. (I'm using Java for that reason.) **Edit:** The code above is missing things like try..catch to make the post smaller
Optimum buffer size is related to a number of things: file system block size, CPU cache size and cache latency. Most file systems are configured to use block sizes of 4096 or 8192. In theory, if you configure your buffer size so you are reading a few bytes more than the disk block, the operations with the file system can be extremely inefficient (i.e. if you configured your buffer to read 4100 bytes at a time, each read would require 2 block reads by the file system). If the blocks are already in cache, then you wind up paying the price of RAM -> L3/L2 cache latency. If you are unlucky and the blocks are not in cache yet, the you pay the price of the disk->RAM latency as well. This is why you see most buffers sized as a power of 2, and generally larger than (or equal to) the disk block size. This means that one of your stream reads could result in multiple disk block reads - but those reads will always use a full block - no wasted reads. Now, this is offset quite a bit in a typical streaming scenario because the block that is read from disk is going to still be in memory when you hit the next read (we are doing sequential reads here, after all) - so you wind up paying the RAM -> L3/L2 cache latency price on the next read, but not the disk->RAM latency. In terms of order of magnitude, disk->RAM latency is so slow that it pretty much swamps any other latency you might be dealing with. So, I suspect that if you ran a test with different cache sizes (haven't done this myself), you will probably find a big impact of cache size up to the size of the file system block. Above that, I suspect that things would level out pretty quickly. There are a *ton* of conditions and exceptions here - the complexities of the system are actually quite staggering (just getting a handle on L3 -> L2 cache transfers is mind bogglingly complex, and it changes with every CPU type). This leads to the 'real world' answer: If your app is like 99% out there, set the cache size to 8192 and move on (even better, choose encapsulation over performance and use BufferedInputStream to hide the details). If you are in the 1% of apps that are highly dependent on disk throughput, craft your implementation so you can swap out different disk interaction strategies, and provide the knobs and dials to allow your users to test and optimize (or come up with some self optimizing system).
236,878
<p>this is a question that when programming I always wonder: What to use when we are writing code: </p> <pre><code>var myFiles = Directory.GetFiles(fullPath); </code></pre> <p>or</p> <pre><code>string[] myFiles = Directory.GetFiles(fullPath); </code></pre> <p><strong><em>var</em></strong> is new and is a <em>Implicitly Typed Local Variables</em>, so we can only use locally and it has rules like can't be null, etc., but I wonder if we get any advantage of using it "normally". </p> <p>The "normally" part says, not in <strong>Anonymous Types</strong>, <strong>Object and Collection Initializers</strong> and <strong>Query Expressions</strong> where that was the intent to use the var anonymous object, so what I mean is... just like the example above.</p> <p>what are your thoughts?</p>
[ { "answer_id": 236886, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>You'll get a huge variety of opinions on this one - from \"use var everywhere\" to \"only use var with anonymous types, where you basically have to.\" I like <a href=\"http://csharpindepth.com/ViewNote.aspx?NoteID=61\" rel=\"noreferrer\">Eric Lippert's take on it</a>:</p>\n\n<blockquote>\n <p>All code is an abstraction. Is what\n the code is “really” doing is\n manipulating data? No. Numbers? Bits?\n No. Voltages? No. Electrons? Yes, but\n understanding the code at the level of\n electrons is a bad idea! The art of\n coding is figuring out what the right\n level of abstraction is for the\n audience.</p>\n \n <p>In a high level language there is\n always this tension between WHAT the\n code does (semantically) and HOW the\n code accomplishes it. Maintenance\n programmers need to understand both\n the what and the how if they’re going\n to be successful in making changes.</p>\n \n <p>The whole point of LINQ is that it\n massively de-emphasizes the \"how\" and\n massively emphasizes the \"what\". By\n using a query comprehension, the\n programmer is saying to the future\n audience \"I believe that you should\n neither know nor care exactly how this\n result set is being computed, but you\n should care very much about what the\n semantics of the resulting set are.\"\n They make the code closer to the\n business process being implemented and\n farther from the bits and electrons\n that make it go.</p>\n \n <p>Implicitly typed locals are just one\n small way in which you can deemphasize\n the how and thereby emphasize the\n what. Whether that is the right thing\n to do in a particular case is a\n judgment call. So I tell people that\n if knowledge of the type is relevant\n and its choice is crucial to the\n continued operation of the method,\n then do not use implicit typing.\n Explicit typing says \"I am telling you\n how this works for a reason, pay\n attention\". Implicit typing says \"it\n doesn’t matter a bit whether this\n thing is a List or a\n Customer[], what matters is that it is\n a collection of customers.\"</p>\n</blockquote>\n\n<p>Personally I don't <em>tend</em> to use it if the type isn't reasonably obvious - where I include LINQ queries as being \"reasonably obvious\". I wouldn't do it for <code>Directory.GetFiles</code> for instance, as it's not really obvious that that returns a <code>string[]</code> instead of (say) a <code>FileInfo[]</code> (or something else entirely) - and that makes a big difference to what you do later.</p>\n\n<p>If there's a constructor call on the right hand side of the assignment operator, I'm much more likely to go with <code>var</code>: it's blatantly obvious what the type will be. This is particularly handy with complex generic types, e.g. <code>Dictionary&lt;string,List&lt;int&gt;&gt;</code>.</p>\n" }, { "answer_id": 236902, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": false, "text": "<p>Personally I only use var in two places:</p>\n\n<ol>\n<li>With anonymous types, ie. LINQ-related (where var is required in some cases)</li>\n<li>When the statement declares and constructs a specific type at the same type</li>\n</ol>\n\n<p>ie. this is an example of point 2:</p>\n\n<pre><code>var names = new List&lt;String&gt;();\n</code></pre>\n\n<p><strong>Edited</strong>: This in response to Jon Skeet's question.</p>\n\n<p>The above answer was in fact simplified. Basically, I use <em>var</em> where the type is either:</p>\n\n<ol>\n<li>Unnecessary to know (not that many places though)</li>\n<li>Impossible to know (LINQ, anonymous types)</li>\n<li>Otherwise known, or clear from the code</li>\n</ol>\n\n<p>In the case of a factory method, where all you need to know at the place where you write the code is that the object you get back is a descendant of some type, and that <em>some type</em> has a static factory method, then I would use <em>var</em>. Like this:</p>\n\n<pre><code>var connection = DatabaseConnection.CreateFromConnectionString(\"...\");\n</code></pre>\n\n<p>The above example is a real example from my code. It is clear, at least to me and the people that use this code, that <em>connection</em> is a DatabaseConnection descendant, but the exact type is not needed for neither understanding the code, nor using it.</p>\n" }, { "answer_id": 236921, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 3, "selected": false, "text": "<p>I tried the \"use var everywhere\" style... and here is why I didn't continue to use it.</p>\n\n<ol>\n<li>Degraded readability at times</li>\n<li>Limits Intellisense after =</li>\n<li>Typing \"var\" really wasn't much shorter than typing \"int\", \"string\", etc., especially with intellisense.</li>\n</ol>\n\n<p>With that said, I DO still use it with LINQ.</p>\n" }, { "answer_id": 236962, "author": "Andres Denkberg", "author_id": 31484, "author_profile": "https://Stackoverflow.com/users/31484", "pm_score": 2, "selected": false, "text": "<p>This <a href=\"http://community.bartdesmet.net/blogs/bart/archive/2008/08/23/appropriate-use-of-local-variable-type-inference.aspx\" rel=\"nofollow noreferrer\">post</a> have some good guidlines on when to use var type interface or object types.</p>\n" }, { "answer_id": 236998, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 7, "selected": true, "text": "<p>Beyond the obvious use of <code>var</code> with LINQ, I also use it to abbreviate hairy variable declarations for readability, e.g.:</p>\n\n<pre><code>var d = new Dictionary&lt;string, Dictionary&lt;string, Queue&lt;SomeClass&gt;&gt;&gt;();\n</code></pre>\n\n<p>In general, I get a kind of comfort (for want of a better word) from static typing that makes me reluctant to give it up. I like the feeling that I know what I'm doing when I'm declaring a variable. Declaring a variable isn't just telling the compiler something, it's telling the person reading your code something.</p>\n\n<p>Let me give you an example. Suppose I have a method that returns a <code>List&lt;string&gt;</code>. This code is certainly correct, and I think it's how 90% of C# developers would probably write it:</p>\n\n<pre><code>List&lt;string&gt; list = MyMethod();\n</code></pre>\n\n<p>Obviously, right? In fact, here's a place you could just as easily use <code>var</code>.</p>\n\n<p>True enough. But <em>this</em> version of the code isn't just declaring a variable, it's telling me what the person who wrote it is intending to do:</p>\n\n<pre><code>IEnumerable&lt;string&gt; list = MyMethod();\n</code></pre>\n\n<p>The developer who wrote that code is telling me \"I'm not going to be changing this list, nor am I going to use an index to access its members. All I'm going to do is iterate across it.\" That's a lot of information to get across in a single line of code. It's something you give up if you use <code>var</code>.</p>\n\n<p>Of course, you're not giving it up if you weren't using it in the first place. If you're the kind of developer who would write that line of code, you already know that you wouldn't use <code>var</code> there.</p>\n\n<p><strong>Edit:</strong> </p>\n\n<p>I just reread Jon Skeet's post, and this quote from Eric Lippert jumped out at me:</p>\n\n<blockquote>\n <p>Implicitly typed locals are just one small way in which you can deemphasize the how and thereby emphasize the what.</p>\n</blockquote>\n\n<p>I think that actually in a lot of cases using implicit typing is leaving the what implicit. It's just OK to not dwell on the what. For instance, I'll casually write a LINQ query like:</p>\n\n<pre><code>var rows = from DataRow r in parentRow.GetChildRows(myRelation)\n where r.Field&lt;bool&gt;(\"Flag\")\n orderby r.Field&lt;int&gt;(\"SortKey\")\n select r;\n</code></pre>\n\n<p>When I read that code, one of the things I think when I'm reading it is \"<code>rows</code> is an <code>IEnumerable&lt;DataRow&gt;</code>.\" Because I know that what LINQ queries return is <code>IEnumerable&lt;T&gt;</code>, and I can see the type of the object being selected right there.</p>\n\n<p>That's a case where the what <em>hasn't</em> been made explicit. It's been left for me to infer.</p>\n\n<p>Now, in about 90% of the cases where I use LINQ, this doesn't matter one tiny little bit. Because 90% of the time, the next line of code is:</p>\n\n<pre><code>foreach (DataRow r in rows)\n</code></pre>\n\n<p>But it's not hard to envision code in which it would be very useful to declare <code>rows</code> as <code>IEnumerable&lt;DataRow&gt;</code> - code where a lot of different kinds of objects were being queried, it wasn't feasible to put the query declaration next to the iteration, and it would be useful to be able inspect <code>rows</code> with IntelliSense. And that's a what thing, not a how thing.</p>\n" }, { "answer_id": 237065, "author": "mithrandi", "author_id": 31490, "author_profile": "https://Stackoverflow.com/users/31490", "pm_score": 1, "selected": false, "text": "<p>I think it's interesting to note how this is usually handled in Haskell. Thanks to the <a href=\"http://en.wikipedia.org/wiki/Curry-Howard_correspondence\" rel=\"nofollow noreferrer\">Curry-Howard isomorphism</a>, the (most general) type of any expression in Haskell can be inferred, and thus type declarations are essentially not required anywhere, with a few exceptions; for example, sometimes you deliberately want to limit the type to something more specific than would be inferred.</p>\n\n<p>Of course, what is required and what is recommended are not the same thing; in practice, the convention seems to be that top-level definitions always have type declarations, while localised definitions have the type declarations left out. This seems to strike a good balance between explicitness-for-readability of the definition as a whole, contrasted with brevity-for-readability of the local \"helper\" or \"temporary\" definitions. If I understand correctly, you can't use <code>var</code> for \"top-level\" definitions (like a method or global function) in the first place, so I guess this translates to \"use <code>var</code> everywhere you can\" in C# world. Of course, typing \"<code>int</code>\" is the same number of keystrokes as \"<code>var</code>\", but most examples will be longer than that.</p>\n" }, { "answer_id": 237551, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "<p>Coming from the land of functional programming, where type-inference rules the day, I use <code>var</code> for all locals wherever possible.</p>\n\n<p>In Visual Studio, if you are ever wondering what the type of any local is, all you have to do is hover over it with your mouse.</p>\n" }, { "answer_id": 365409, "author": "Aleš Roubíček", "author_id": 19892, "author_profile": "https://Stackoverflow.com/users/19892", "pm_score": 2, "selected": false, "text": "<p>I tend to use <code>var</code> everywhere, but my co-workers said stop, it is less readable to us. So I now I use <code>var</code> only on anonymous types, LINQ queries and where is constructor on right side.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28004/" ]
this is a question that when programming I always wonder: What to use when we are writing code: ``` var myFiles = Directory.GetFiles(fullPath); ``` or ``` string[] myFiles = Directory.GetFiles(fullPath); ``` ***var*** is new and is a *Implicitly Typed Local Variables*, so we can only use locally and it has rules like can't be null, etc., but I wonder if we get any advantage of using it "normally". The "normally" part says, not in **Anonymous Types**, **Object and Collection Initializers** and **Query Expressions** where that was the intent to use the var anonymous object, so what I mean is... just like the example above. what are your thoughts?
Beyond the obvious use of `var` with LINQ, I also use it to abbreviate hairy variable declarations for readability, e.g.: ``` var d = new Dictionary<string, Dictionary<string, Queue<SomeClass>>>(); ``` In general, I get a kind of comfort (for want of a better word) from static typing that makes me reluctant to give it up. I like the feeling that I know what I'm doing when I'm declaring a variable. Declaring a variable isn't just telling the compiler something, it's telling the person reading your code something. Let me give you an example. Suppose I have a method that returns a `List<string>`. This code is certainly correct, and I think it's how 90% of C# developers would probably write it: ``` List<string> list = MyMethod(); ``` Obviously, right? In fact, here's a place you could just as easily use `var`. True enough. But *this* version of the code isn't just declaring a variable, it's telling me what the person who wrote it is intending to do: ``` IEnumerable<string> list = MyMethod(); ``` The developer who wrote that code is telling me "I'm not going to be changing this list, nor am I going to use an index to access its members. All I'm going to do is iterate across it." That's a lot of information to get across in a single line of code. It's something you give up if you use `var`. Of course, you're not giving it up if you weren't using it in the first place. If you're the kind of developer who would write that line of code, you already know that you wouldn't use `var` there. **Edit:** I just reread Jon Skeet's post, and this quote from Eric Lippert jumped out at me: > > Implicitly typed locals are just one small way in which you can deemphasize the how and thereby emphasize the what. > > > I think that actually in a lot of cases using implicit typing is leaving the what implicit. It's just OK to not dwell on the what. For instance, I'll casually write a LINQ query like: ``` var rows = from DataRow r in parentRow.GetChildRows(myRelation) where r.Field<bool>("Flag") orderby r.Field<int>("SortKey") select r; ``` When I read that code, one of the things I think when I'm reading it is "`rows` is an `IEnumerable<DataRow>`." Because I know that what LINQ queries return is `IEnumerable<T>`, and I can see the type of the object being selected right there. That's a case where the what *hasn't* been made explicit. It's been left for me to infer. Now, in about 90% of the cases where I use LINQ, this doesn't matter one tiny little bit. Because 90% of the time, the next line of code is: ``` foreach (DataRow r in rows) ``` But it's not hard to envision code in which it would be very useful to declare `rows` as `IEnumerable<DataRow>` - code where a lot of different kinds of objects were being queried, it wasn't feasible to put the query declaration next to the iteration, and it would be useful to be able inspect `rows` with IntelliSense. And that's a what thing, not a how thing.
236,972
<p>Based on this question <a href="https://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc">here</a> and using code found <a href="http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx" rel="nofollow noreferrer">here</a> I'm trying to load views that are embedded resources in a separate DLL project, and the original question's author says he has had success doing this - but I can't get it to work as it seems the MVC view engine is intercepting the request and still looking at the file system for the view. Exception:</p> <pre><code>Server Error in '/' Application. The view 'Index' or its master could not be found. The following locations were searched: ~/Views/admin/Index.aspx ~/Views/admin/Index.ascx ~/Views/Shared/Index.aspx ~/Views/Shared/Index.ascx ~/App/Views/admin/Index.aspx ~/App/Views/admin/Index.ascx ~/App/Views/Shared/Index.aspx ~/App/Views/Shared/Index.ascx </code></pre> <p>I am using a <code>CustomViewEngine</code>, like Rob Connery's /App structure one as follows:</p> <pre><code>public class CustomViewEngine : WebFormViewEngine { public CustomViewEngine() { MasterLocationFormats = new[] { "~/App/Views/{1}/{0}.master", "~/App/Views/Shared/{0}.master" }; ViewLocationFormats = new[] { "~/App/Views/{1}/{0}.aspx", "~/App/Views/{1}/{0}.ascx", "~/App/Views/Shared/{0}.aspx", "~/App/Views/Shared/{0}.ascx" }; PartialViewLocationFormats = ViewLocationFormats; } } </code></pre> <p>Here are my routes:</p> <pre><code> routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Home", "", new {controller = "Page", action = "Index", id = "Default"}); routes.MapRoute("Default", "Page/{id}", new { controller = "Page", action = "Index", id = "" }); routes.MapRoute("Plugins", "plugin/{controller}/{action}", new { controller = "", action = "Index", id = "" }); routes.MapRoute("Error", "{*url}", new { controller = "Error", action = "ResourceNotFound404" }); </code></pre> <p>In my <a href="http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx" rel="nofollow noreferrer"><code>AssemblyResourceProvider</code></a> I'm checking to see if the path starts <code>~/plugin/</code> and then using the dll filename convention <code>plugin.{controller}.dll</code></p> <p>Any suggestions?</p> <p><strong>UPDATE:</strong> By the time the routed request for say <code>http://localhost/plugin/admin</code> is getting to the VirtualFileProvider it doesn't have any View attached at the end. So in the <code>VirtualFileProvider</code>'s Open method the virtual path of <code>~/plugin/admin</code> is being passed in when it should be <code>~/plugin/admin/Index.aspx</code> as defined in my route above. Have I messed up my routes or am I right to be expecting this to happen?</p>
[ { "answer_id": 238131, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 2, "selected": false, "text": "<p>The built-in WebFormsViewEngine uses VirtualPathProviders, so if you write a VPP and register it, you won't need to make any changes to the view engine.</p>\n" }, { "answer_id": 238363, "author": "jmcd", "author_id": 2285, "author_profile": "https://Stackoverflow.com/users/2285", "pm_score": 6, "selected": true, "text": "<ol>\n<li>You must register your <code>VirtualPathProvider</code> within the <code>Global.asax</code> <code>Application_Start</code> handler.</li>\n<li>You must call the view in your DLL using the special path like so: <code>return View(\"~/Plugin/YOURDLL.dll/FULLNAME_YOUR_VIEW.aspx\");</code></li>\n</ol>\n\n<p>Here's an article with downloadable code sample that demonstrates this:</p>\n\n<p><a href=\"http://www.wynia.org/wordpress/2008/12/aspnet-mvc-plugins/\" rel=\"nofollow noreferrer\">http://www.wynia.org/wordpress/2008/12/aspnet-mvc-plugins/</a></p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2285/" ]
Based on this question [here](https://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc) and using code found [here](http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx) I'm trying to load views that are embedded resources in a separate DLL project, and the original question's author says he has had success doing this - but I can't get it to work as it seems the MVC view engine is intercepting the request and still looking at the file system for the view. Exception: ``` Server Error in '/' Application. The view 'Index' or its master could not be found. The following locations were searched: ~/Views/admin/Index.aspx ~/Views/admin/Index.ascx ~/Views/Shared/Index.aspx ~/Views/Shared/Index.ascx ~/App/Views/admin/Index.aspx ~/App/Views/admin/Index.ascx ~/App/Views/Shared/Index.aspx ~/App/Views/Shared/Index.ascx ``` I am using a `CustomViewEngine`, like Rob Connery's /App structure one as follows: ``` public class CustomViewEngine : WebFormViewEngine { public CustomViewEngine() { MasterLocationFormats = new[] { "~/App/Views/{1}/{0}.master", "~/App/Views/Shared/{0}.master" }; ViewLocationFormats = new[] { "~/App/Views/{1}/{0}.aspx", "~/App/Views/{1}/{0}.ascx", "~/App/Views/Shared/{0}.aspx", "~/App/Views/Shared/{0}.ascx" }; PartialViewLocationFormats = ViewLocationFormats; } } ``` Here are my routes: ``` routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Home", "", new {controller = "Page", action = "Index", id = "Default"}); routes.MapRoute("Default", "Page/{id}", new { controller = "Page", action = "Index", id = "" }); routes.MapRoute("Plugins", "plugin/{controller}/{action}", new { controller = "", action = "Index", id = "" }); routes.MapRoute("Error", "{*url}", new { controller = "Error", action = "ResourceNotFound404" }); ``` In my [`AssemblyResourceProvider`](http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx) I'm checking to see if the path starts `~/plugin/` and then using the dll filename convention `plugin.{controller}.dll` Any suggestions? **UPDATE:** By the time the routed request for say `http://localhost/plugin/admin` is getting to the VirtualFileProvider it doesn't have any View attached at the end. So in the `VirtualFileProvider`'s Open method the virtual path of `~/plugin/admin` is being passed in when it should be `~/plugin/admin/Index.aspx` as defined in my route above. Have I messed up my routes or am I right to be expecting this to happen?
1. You must register your `VirtualPathProvider` within the `Global.asax` `Application_Start` handler. 2. You must call the view in your DLL using the special path like so: `return View("~/Plugin/YOURDLL.dll/FULLNAME_YOUR_VIEW.aspx");` Here's an article with downloadable code sample that demonstrates this: <http://www.wynia.org/wordpress/2008/12/aspnet-mvc-plugins/>
236,979
<p>I'm creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can't get it to work for all properties. I'm using preg/perl syntax in PHP.</p> <h3>Regex</h3> <pre><code>(?&lt;selector&gt;[A-Za-z]+[\s]*)[\s]*{[\s]*((?&lt;properties&gt;[A-Za-z0-9-_]+)[\s]*:[\s]*(?&lt;values&gt;[A-Za-z0-9#, ]+);[\s]*)*[\s]*} </code></pre> <h3>Test case</h3> <pre><code>body { background: #f00; font: 12px Arial; } </code></pre> <h3>Expected Outcome</h3> <pre><code>Array( [0] =&gt; Array( [0] =&gt; body { background: #f00; font: 12px Arial; } [selector] =&gt; Array( [0] =&gt; body ) [1] =&gt; Array( [0] =&gt; body ) [2] =&gt; font: 12px Arial; [properties] =&gt; Array( [0] =&gt; font ) [3] =&gt; Array( [0] =&gt; font ) [values] =&gt; Array( [0] =&gt; 12px Arial [1] =&gt; background: #f00 ) [4] =&gt; Array( [0] =&gt; 12px Arial [1] =&gt; background: #f00 ) ) ) </code></pre> <h3>Real Outcome</h3> <pre><code>Array( [0] =&gt; Array ( [0] =&gt; body { background: #f00; font: 12px Arial; } [selector] =&gt; body [1] =&gt; body [2] =&gt; font: 12px Arial; [properties] =&gt; font [3] =&gt; font [values] =&gt; 12px Arial [4] =&gt; 12px Arial ) ) </code></pre> <p>Thanks in advance for any help - this has been confusing me all afternoon!</p>
[ { "answer_id": 236984, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 5, "selected": true, "text": "<p>That just seems too convoluted for a single regular expression. Well, I'm sure that with the right extentions, an advanced user could create the right regex. But then you'd need an even more advanced user to debug it.</p>\n\n<p>Instead, I'd suggest using a regex to pull out the pieces, and then tokenising each piece separately. e.g.,</p>\n\n<pre><code>/([^{])\\s*\\{\\s*([^}]*?)\\s*}/\n</code></pre>\n\n<p>Then you end up with the selector and the attributes in separate fields, and then split those up. (Even the selector will be fun to parse.) Note that even this will have pains if }'s can appear inside quotes or something. You could, again, convolute the heck out of it to avoid that, but it's probably even better to avoid regex's altogether here, and handle it by parsing one field at a time, perhaps by using a recursive-descent parser or yacc/bison or whatever.</p>\n" }, { "answer_id": 236987, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": false, "text": "<p>You are trying to pull structure out of the data, and not just individual values. Regular expressions might could be painfully stretched to do the job, but you are really entering parser territory, and should be pulling out the big guns, namely parsers.</p>\n\n<p>I have never used the PHP parser generating tools, but they look okay after a light scan of the docs. Check out <a href=\"http://pear.php.net/package/PHP_LexerGenerator\" rel=\"noreferrer\">LexerGenerator</a> and <a href=\"http://pear.php.net/package/PHP_ParserGenerator\" rel=\"noreferrer\">ParserGenerator</a>. LexerGenerator will take a bunch of regular expressions describing the different types of tokens in a language (in this case, CSS) and spit out some code that recognizes the individual tokens. ParserGenerator will take a grammar, a description of what things in a language are made up of what other things, and spit out a parser, code that takes a bunch of tokens and returns a syntax tree (the data structure that you are after.</p>\n" }, { "answer_id": 237381, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": false, "text": "<p>I would recommend against using regex's to parse CSS - especially in single regex!</p>\n\n<p>If you insist on doing the parsing in regex's, split it up into sensible sections - use one regex to split all the <code>body{..}</code> blocks, then another to parse the <code>color:rgb(1,2,3);</code> attributes.</p>\n\n<p>If you are actually trying to write something \"useful\" (not trying to learn regular expressions), look for a prewritten CSS parser.</p>\n\n<p>I found <a href=\"http://websvn.atrc.utoronto.ca/websvn/wsvn/Atutor/trunk/docs/include/classes/cssparser.php\" rel=\"noreferrer\">this cssparser.php</a> which seems to work very well:</p>\n\n<pre><code>$cssp = new cssparser;\n$cssp -&gt; ParseStr(\"body { background: #f00;font: 12px Arial; }\");\nprint_r($cssp-&gt;css);\n</code></pre>\n\n<p>..which outputs the following:</p>\n\n<pre><code>Array\n(\n [body] =&gt; Array\n (\n [background] =&gt; #f00\n [font] =&gt; 12px arial\n )\n)\n</code></pre>\n\n<p>The parser is pretty simple, so should be easy to work out what it's doing. Oh, I had to remove the lines that read <code>if($this-&gt;html) {$this-&gt;Add(\"VAR\", \"\");}</code> (it seems to be a debugging thing that was left in)</p>\n\n<p>I've mirrored the script <a href=\"http://github.com/dbr/so_scripts/tree/master/csssparser.php\" rel=\"noreferrer\">here</a>, with the above changes in</p>\n" }, { "answer_id": 1012557, "author": "Jacek Lange", "author_id": 125086, "author_profile": "https://Stackoverflow.com/users/125086", "pm_score": 4, "selected": false, "text": "<p>Do not use your own regex for parsing CSS.\nWhy reinvent the wheel while there is code waiting for you, ready to use and (hopefully) bug-free? </p>\n\n<p>There are two generally available classes that can parse CSS for you:</p>\n\n<p>HTML_CSS PEAR package at pear.php.net</p>\n\n<p>and</p>\n\n<p>CSS Parser class at PHPCLasses:</p>\n\n<p><a href=\"http://www.phpclasses.org/browse/package/1289.html\" rel=\"noreferrer\">http://www.phpclasses.org/browse/package/1289.html</a></p>\n" }, { "answer_id": 2694121, "author": "Nick Franceschina", "author_id": 130221, "author_profile": "https://Stackoverflow.com/users/130221", "pm_score": 3, "selected": false, "text": "<p>I am using the regex below and it pretty much works... of course this question is old now and I see that you've abandoned your efforts... but in case someone else runs across it:</p>\n\n<pre><code>(?&lt;selector&gt;(?:(?:[^,{]+),?)*?)\\{(?:(?&lt;name&gt;[^}:]+):?(?&lt;value&gt;[^};]+);?)*?\\}\n</code></pre>\n\n<p>(hafta remove all of the <strong>/* comments */</strong> from your CSS first to be safe)</p>\n" }, { "answer_id": 2798564, "author": "Poseidon", "author_id": 336746, "author_profile": "https://Stackoverflow.com/users/336746", "pm_score": 0, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>function trimStringArray($stringArray){\n $result = array();\n for($i=0; $i &lt; count($stringArray); $i++){\n $trimmed = trim($stringArray[$i]);\n if($trimmed != '') $result[] = $trimmed;\n }\n return $result;\n}\n$regExp = '/\\{|\\}/';\n$rawCssData = preg_split($regExp, $style);\n\n$cssArray = array();\nfor($i=0; $i &lt; count($rawCssData); $i++){\n if($i % 2 == 0){\n $cssStyle['selectors'] = array();\n $selectors = split(',', $rawCssData[$i]);\n $cssStyle['selectors'] = trimStringArray($selectors);\n }\n if($i % 2 == 1){\n $attributes = split(';', $rawCssData[$i]);\n $cssStyle['attributes'] = trimStringArray($attributes);\n $cssArray[] = $cssStyle;\n }\n\n}\n//return false;\necho '&lt;pre&gt;'.\"\\n\";\nprint_r($cssArray);\necho '&lt;/pre&gt;'.\"\\n\";\n</code></pre>\n" }, { "answer_id": 5477827, "author": "Dan", "author_id": 88033, "author_profile": "https://Stackoverflow.com/users/88033", "pm_score": 3, "selected": false, "text": "<p>I wrote a piece of code that easily parses CSS. All you have to do is do a couple of explodes really... The $css variable is a string of the CSS. All you have to do is do a <code>print_r($css)</code> to get a nice array of CSS, fully parsed.</p>\n\n<pre><code>$css_array = array(); // master array to hold all values\n$element = explode('}', $css);\nforeach ($element as $element) {\n // get the name of the CSS element\n $a_name = explode('{', $element);\n $name = $a_name[0];\n // get all the key:value pair styles\n $a_styles = explode(';', $element);\n // remove element name from first property element\n $a_styles[0] = str_replace($name . '{', '', $a_styles[0]);\n // loop through each style and split apart the key from the value\n $count = count($a_styles);\n for ($a=0;$a&lt;$count;$a++) {\n if ($a_styles[$a] != '') {\n $a_key_value = explode(':', $a_styles[$a]);\n // build the master css array\n $css_array[$name][$a_key_value[0]] = $a_key_value[1];\n }\n } \n}\n</code></pre>\n\n<p>Gives you this:</p>\n\n<pre><code>Array\n(\n [body] =&gt; Array\n (\n [background] =&gt; #f00\n [font] =&gt; 12px arial\n )\n)\n</code></pre>\n" }, { "answer_id": 48937026, "author": "CTS_AE", "author_id": 349659, "author_profile": "https://Stackoverflow.com/users/349659", "pm_score": 2, "selected": false, "text": "<p>Building off of the current answer by Tanktalus there's a couple of improvements and edge cases to note.</p>\n\n<h2>CSS Parsing Regex</h2>\n\n<pre><code>\\s*([^{]+)\\s*\\{\\s*([^}]*?)\\s*}\n</code></pre>\n\n<p>This Regex will do some space trimming and hits on some additional edge cases as listed in this example: <a href=\"https://regex101.com/r/qQRIHx/5\" rel=\"nofollow noreferrer\">https://regex101.com/r/qQRIHx/5</a></p>\n\n<h3>key:value pairs; Pitfalls of Further Complexicated Regex</h3>\n\n<p>I too started to try work on delimiting the key:value pairs but quickly saw in the case where there were multiple styles per selector that things started to get trickier than I wanted. You can view version 1 of the regex where I tried to delimit the key:values and how it failed with multiple declarations here: <a href=\"https://regex101.com/r/qQRIHx/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/qQRIHx/1</a></p>\n\n<h2>Implementation</h2>\n\n<p>As others mentioned, you should break this up into multiple steps to parse and tokenize your css. This regex will help you obtain the declarations, but you will need to then parse those out.</p>\n\n<h3>Declaration Parser</h3>\n\n<p>You could use something like this to parse the declarations after you get your first set of matches.</p>\n\n<p><code>([^:\\s]+)*\\s*:\\s*([^;]+);</code></p>\n\n<p>Example: <a href=\"https://regex101.com/r/py9OKO/1/\" rel=\"nofollow noreferrer\">https://regex101.com/r/py9OKO/1/</a></p>\n\nEdge Case\n\n<p>The above example works great with multiple declarations, but it's possible that it's just 1 declaration with no semi-colon to end which will render in [most] browsers but break this regex.</p>\n\n<h3>Noted Cases</h3>\n\n<p>You may also need to account for nested rules in the case that there's a media query. In this case I would try to run the css matching regex against the declarations that are extracted. If you get matches you could run recursion on it (although I'm not sure there's cases where you would have more than 1 level nested for vanilla CSS).</p>\n\nEdge Cases\n\n<ul>\n<li>This doesn't handle a right curly bracket in a string</li>\n</ul>\n\n<h2>Tomorrow's Research</h2>\n\n<p>I've decided to instead use an npm package like <code>css</code> or <code>cssom</code>. I know this is in PHP but it's going to do a lot of heavy lifting for me and handle edge cases I keep running into.</p>\n\n<p><strong>Edit</strong>:</p>\n\n<p>I ended up using Jotform's public css.js library. It has a really small footprint which was one of the main requirements I had when choosing libraries to parse CSS. </p>\n\n<ul>\n<li><a href=\"https://github.com/jotform/css.js/tree/master\" rel=\"nofollow noreferrer\">https://github.com/jotform/css.js/tree/master</a></li>\n<li>They also published this article explaining their process: \n\n<ul>\n<li><a href=\"https://stories.jotform.com/writing-a-css-parser-in-javascript-3ecaa1719a43\" rel=\"nofollow noreferrer\">https://stories.jotform.com/writing-a-css-parser-in-javascript-3ecaa1719a43</a></li>\n</ul></li>\n</ul>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
I'm creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can't get it to work for all properties. I'm using preg/perl syntax in PHP. ### Regex ``` (?<selector>[A-Za-z]+[\s]*)[\s]*{[\s]*((?<properties>[A-Za-z0-9-_]+)[\s]*:[\s]*(?<values>[A-Za-z0-9#, ]+);[\s]*)*[\s]*} ``` ### Test case ``` body { background: #f00; font: 12px Arial; } ``` ### Expected Outcome ``` Array( [0] => Array( [0] => body { background: #f00; font: 12px Arial; } [selector] => Array( [0] => body ) [1] => Array( [0] => body ) [2] => font: 12px Arial; [properties] => Array( [0] => font ) [3] => Array( [0] => font ) [values] => Array( [0] => 12px Arial [1] => background: #f00 ) [4] => Array( [0] => 12px Arial [1] => background: #f00 ) ) ) ``` ### Real Outcome ``` Array( [0] => Array ( [0] => body { background: #f00; font: 12px Arial; } [selector] => body [1] => body [2] => font: 12px Arial; [properties] => font [3] => font [values] => 12px Arial [4] => 12px Arial ) ) ``` Thanks in advance for any help - this has been confusing me all afternoon!
That just seems too convoluted for a single regular expression. Well, I'm sure that with the right extentions, an advanced user could create the right regex. But then you'd need an even more advanced user to debug it. Instead, I'd suggest using a regex to pull out the pieces, and then tokenising each piece separately. e.g., ``` /([^{])\s*\{\s*([^}]*?)\s*}/ ``` Then you end up with the selector and the attributes in separate fields, and then split those up. (Even the selector will be fun to parse.) Note that even this will have pains if }'s can appear inside quotes or something. You could, again, convolute the heck out of it to avoid that, but it's probably even better to avoid regex's altogether here, and handle it by parsing one field at a time, perhaps by using a recursive-descent parser or yacc/bison or whatever.
237,006
<p>I installed SQL Server 2005 sometime ago and forgot the administrator password I set during setup. How can I connect to SQL server now?</p> <p><strong>EDIT:</strong> I think I only allowed Sql Server Authentication. Login with integrated security also does not work.</p>
[ { "answer_id": 237008, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Unless you set it up to only accept SQL Server authentication, you can log on with integrated security using the administrator user of the domain and/or machine.</p>\n" }, { "answer_id": 237025, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 5, "selected": false, "text": "<p>Try running the following commands at the command prompt (assuming your Server name is <strong>SQLEXPRESS</strong>):</p>\n\n<pre><code>osql -E -S .\\SQLEXPRESS\nexec sp_password @new='changeme', @loginame='sa'\ngo\nalter login sa enable\ngo\nexit\n</code></pre>\n\n<p>Once you have completed these steps, try to login with username <strong>sa</strong> and password <strong>changeme</strong>.</p>\n" }, { "answer_id": 682759, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Thanks a lot <strong>cowgod</strong></p>\n\n<p>It works Fine.\nI have Logged in to SQL Server with windows authentication mode.\nThen opened a new query window. There I typed these two commands by prssing F5.</p>\n\n<p>First run\n<strong>exec sp_password @new='changeme', @loginame='sa'</strong></p>\n\n<p>Then\n<strong>alter login sa enable</strong></p>\n" }, { "answer_id": 2956264, "author": "Chris W", "author_id": 121879, "author_profile": "https://Stackoverflow.com/users/121879", "pm_score": 3, "selected": false, "text": "<p>You don't need to pay for any reset tools to do this. Start the instance in single user mode and you can create a new login with sysadmin permissions/</p>\n\n<p>See this <a href=\"http://blog.sqlauthority.com/2009/02/10/sql-server-start-sql-server-instance-in-single-user-mode/\" rel=\"noreferrer\">Pinal Dave link</a>.</p>\n" }, { "answer_id": 21597062, "author": "Ilia Barahovsky", "author_id": 404099, "author_profile": "https://Stackoverflow.com/users/404099", "pm_score": 2, "selected": false, "text": "<p>If there's no other user with sysadmin privileges but <code>sa</code>, SQL Server should be restarted with <code>-m</code> option for single-user mode. Then you can connect to this SQL Server instance and you're able to add other users with sysadmin role or to execute <code>exec sp_password</code>.</p>\n\n<p>Pinal Dave explains here - <a href=\"http://blog.sqlauthority.com/2009/02/10/sql-server-start-sql-server-instance-in-single-user-mode/\" rel=\"nofollow\">http://blog.sqlauthority.com/2009/02/10/sql-server-start-sql-server-instance-in-single-user-mode/</a> - how to add <code>-m</code> with <strong>SQL Server Configuration Manager</strong>: right-click server service, go to Advanced tab and add <code>-m;</code> (notice semicolon) in Startup Parameters.</p>\n\n<p>Another way is to stop SQL Server instance in Services and to run it manually from the <strong>command line</strong> like this:</p>\n\n<blockquote>\n <p>\"C:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\Binn\\sqlservr.exe\" -m -sSQLEXPRESS</p>\n</blockquote>\n\n<p>I had to do that for SQL Server 2008 as it didn't appear in SQL Server 2008 R2 Configuration Manager. Exect command line can be found with in service properties.</p>\n" }, { "answer_id": 46377492, "author": "TheGameiswar", "author_id": 2975396, "author_profile": "https://Stackoverflow.com/users/2975396", "pm_score": 0, "selected": false, "text": "<p>For these steps to work, you need to be an admin on box where SQL Server is installed.</p>\n\n<ul>\n<li>Stop SQL Server from configuration manager</li>\n<li>Start SQL Server in single user mode</li>\n<li><p>Add this <code>-mSQLCMD</code> command as one of the start up parameters, by right clicking the service and going into startup parameters section as shown in screenshot below and start SQL Server </p>\n\n<p><a href=\"https://i.stack.imgur.com/Rcz6o.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Rcz6o.png\" alt=\"enter image description here\"></a> </p></li>\n<li><p>Now connect to SQLSERVER from SQLCMD (open command prompt as admin) like below:</p>\n\n<pre><code>sqlcmd -s servername\\instancename\n</code></pre>\n\n<p>And run below command:</p>\n\n<pre><code>USE [master]\nGO\nCREATE LOGIN [BUILTIN\\Administrators] FROM WINDOWS WITH DEFAULT_DATABASE=[master]\nGO\nEXEC master..sp_addsrvrolemember @loginame = N'BUILTIN\\Administrators', @rolename = N'sysadmin'\nGO\n</code></pre>\n\n<p>Above command adds all local users as sysadmins. You may change this and add a user like or you can make another user sysadmin and remove <code>BUILTIN\\Administrators</code></p></li>\n<li><p>Once this is done, you need to now stop SQL Server and remove <code>-mSQLCMD</code> parameter and restart SQL Server</p></li>\n</ul>\n\n<p><strong>References:</strong><br>\n<a href=\"https://sqlserver-help.com/2012/02/08/help-i-lost-sa-password-and-no-one-has-system-administrator-sysadmin-permission-what-should-i-do/\" rel=\"nofollow noreferrer\">Help : I lost sa password and no one has System Administrator (SysAdmin) permission. What should I do?</a></p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I installed SQL Server 2005 sometime ago and forgot the administrator password I set during setup. How can I connect to SQL server now? **EDIT:** I think I only allowed Sql Server Authentication. Login with integrated security also does not work.
Try running the following commands at the command prompt (assuming your Server name is **SQLEXPRESS**): ``` osql -E -S .\SQLEXPRESS exec sp_password @new='changeme', @loginame='sa' go alter login sa enable go exit ``` Once you have completed these steps, try to login with username **sa** and password **changeme**.
237,027
<p>Here's my problem: I have a virtual method defined in a .h file that I want to call in a class that inherits from the base class. Sadly though, the method in the derived class doesn't get called. Is there a better way to implement what I'm trying to do?</p> <pre><code>#ifndef ofxBASE_SND_OBJ #define ofxBASE_SND_OBJ #include "ofConstants.h" class ofxBaseSndObj { public: virtual string getType(){} string key; }; #endif </code></pre> <p>Here's my buzz class</p> <pre><code>#ifndef OFXSO_BUZZ #define OFXSO_BUZZ #include "ofxBaseSndObj.h" class ofxSOBuzz : public ofxBaseSndObj { public: string getType(); }; #endif </code></pre> <p>ofxSOBuzz.cpp</p> <pre><code>string ofxSOBuzz::getType() { string s = string("ofxSOBuzz"); printf(" ********* returning string type %s", s.c_str()); // doesn't get called! return s; } </code></pre> <p>Then in another class I try to call it this way:</p> <pre><code>string ofxSndObj::createFilter(ofxBaseSndObj obj) { string str = obj.getType(); if(str.compare("ofxSOBuzz") == 0) { printf(" all is well "); } } </code></pre> <p>In the method above I need to be able to pass in one of many kinds of objects that all extend the ofxBaseSndObj object. Any suggestsions or pointers would be greatly appreciated. Thanks!</p>
[ { "answer_id": 237033, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "<p>You need to pass the instance to createFilter as a <strong>pointer</strong> (or reference) to the object. You are <a href=\"http://cplus.about.com/od/glossar1/g/passbyvaldefn.htm\" rel=\"nofollow noreferrer\">passing by value</a>, and this causes the compiler to copy the derived object you use as an argument into an instance of the base class. When it does this you lose the fact that it was originally a derived type.</p>\n\n<p>As written your code shouldn't actually compile since the declaration of ofxBaseSndObj::getType doesn't return anything. Did you mean for this to be an abstract method or return an empty string?</p>\n\n<p>If you made it an abstract method then the compiler would complain about trying to instantiate an abstract class in your ofxSndObj::createFilter method.</p>\n" }, { "answer_id": 237034, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": true, "text": "<p>Change this line:</p>\n\n<pre><code>string ofxSndObj::createFilter(ofxBaseSndObj obj)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>string ofxSndObj::createFilter(ofxBaseSndObj&amp; obj)\n</code></pre>\n\n<p>What you are doing is passing by value (passing a copy).</p>\n\n<p>This means you are copying the object to the function. Because the function does not know what type you are actually passing it only passes the type defined in the function declaration and thus it makes a copy of the base class (this is know as the <a href=\"http://www.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/section/slice.htm\" rel=\"nofollow noreferrer\">slicing</a> problem).</p>\n\n<p>The solution is to pass by reference.</p>\n\n<p>If you do not want the function to modify the object (maybe that is why you were passing by value so it could not alter the original) then pass a const reference.</p>\n\n<pre><code>class ofxBaseSndObj\n{\n public:\n virtual string getType() const;\n // If the method does not change the object mark it const\n\n string key;\n\n};\n\nstring ofxSndObj::createFilter(ofxBaseSndObj const&amp; obj)\n{\n // allowed to call this if getType() is a const\n string str = obj.getType();\n\n if(str.compare(\"ofxSOBuzz\") == 0)\n {\n printf(\" all is well \");\n }\n}\n</code></pre>\n" }, { "answer_id": 237039, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>This problem is called <a href=\"http://www.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/section/slice.htm\" rel=\"nofollow noreferrer\">\"slicing\"</a> in C++.</p>\n" }, { "answer_id": 237059, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 2, "selected": false, "text": "<p>Making the copy constructor and operator= private is an effective way of preventing this bug from happening again. </p>\n\n<p>For example:</p>\n\n<pre><code>class ofxBaseSndObj {\npublic:\n virtual string getType(){}\n string key;\n\nprivate:\n ofxBaseSndObj(const ofxBaseSndObj&amp; rhs);\n ofxBaseSndObj&amp; operator=(const ofxBaseSndObj&amp; rhs);\n};\n</code></pre>\n\n<p>If there is no other good reason you should use C++'s built in RTTI. You can then use typeid operator. Look at your compilers documentation to turn this on if it is not on by default.</p>\n" }, { "answer_id": 237060, "author": "user21714", "author_id": 21714, "author_profile": "https://Stackoverflow.com/users/21714", "pm_score": -1, "selected": false, "text": "<p>You could use dynamic_cast or type_id</p>\n" }, { "answer_id": 237134, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<p>Others have addressed the slicing problem. You then ask <em>Ok, let me say, I know I need to do something to determine the base type, but is there something more elegant than doing an enum lookup to determine the kind of inherited object?</em></p>\n\n<p>Querying and switching on the type of the object is a poor design which misses the point of the OO approach.</p>\n\n<p>Instead of</p>\n\n<pre><code>string ofxSndObj::createFilter(ofxBaseSndObj&amp; obj)\n{\n string str = obj.getType();\n if(str.compare(\"ofxSOBuzz\") == 0)\n {\n // do ofxSOBuzz - specific thing\n }\n else if(str.compare(\"some other derived class\") == 0)\n {\n // do stuff for other derived classes\n }\n // etc...\n}\n</code></pre>\n\n<p>make the interesting behaviour the virtual function:</p>\n\n<pre><code>class ofxBaseSndObj {\n\npublic:\n // get rid of getType()\n virtual void HelpCreateFilter() = 0;\n};\n\n\nstring ofxSndObj::createFilter(ofxBaseSndObj&amp; obj)\n{\n // Let the derived class do it's own specialized work.\n // This function doesn't need to know what it is.\n obj.HelpCreateFilter();\n // rest of filter creation\n}\n</code></pre>\n\n<p>Why is this better than the original version? Because <code>ofxSndObj::createFilter</code> does not need modifying if future derived classes of ofxBaseSndObj are added to the system. Your version needs extending for each new derived class. If this is unclear, try to post a little more code - I can't tell from your code or class names what these functions are supposed to do.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66105/" ]
Here's my problem: I have a virtual method defined in a .h file that I want to call in a class that inherits from the base class. Sadly though, the method in the derived class doesn't get called. Is there a better way to implement what I'm trying to do? ``` #ifndef ofxBASE_SND_OBJ #define ofxBASE_SND_OBJ #include "ofConstants.h" class ofxBaseSndObj { public: virtual string getType(){} string key; }; #endif ``` Here's my buzz class ``` #ifndef OFXSO_BUZZ #define OFXSO_BUZZ #include "ofxBaseSndObj.h" class ofxSOBuzz : public ofxBaseSndObj { public: string getType(); }; #endif ``` ofxSOBuzz.cpp ``` string ofxSOBuzz::getType() { string s = string("ofxSOBuzz"); printf(" ********* returning string type %s", s.c_str()); // doesn't get called! return s; } ``` Then in another class I try to call it this way: ``` string ofxSndObj::createFilter(ofxBaseSndObj obj) { string str = obj.getType(); if(str.compare("ofxSOBuzz") == 0) { printf(" all is well "); } } ``` In the method above I need to be able to pass in one of many kinds of objects that all extend the ofxBaseSndObj object. Any suggestsions or pointers would be greatly appreciated. Thanks!
Change this line: ``` string ofxSndObj::createFilter(ofxBaseSndObj obj) ``` to ``` string ofxSndObj::createFilter(ofxBaseSndObj& obj) ``` What you are doing is passing by value (passing a copy). This means you are copying the object to the function. Because the function does not know what type you are actually passing it only passes the type defined in the function declaration and thus it makes a copy of the base class (this is know as the [slicing](http://www.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/section/slice.htm) problem). The solution is to pass by reference. If you do not want the function to modify the object (maybe that is why you were passing by value so it could not alter the original) then pass a const reference. ``` class ofxBaseSndObj { public: virtual string getType() const; // If the method does not change the object mark it const string key; }; string ofxSndObj::createFilter(ofxBaseSndObj const& obj) { // allowed to call this if getType() is a const string str = obj.getType(); if(str.compare("ofxSOBuzz") == 0) { printf(" all is well "); } } ```
237,041
<p>Does anyone know what will be in .NET 4.0?</p> <p>I found <a href="https://mef.svn.codeplex.com/svn/src/ComponentModel/System/Tuple.cs" rel="nofollow noreferrer">tuples on codeplex</a>:</p> <pre><code>.... // NOTE : this is a TEMPORARY and a very minimalistic implementation of Tuple'2, // as defined in http://devdiv/sites/docs/NetFX4/CLR/Specs/Base Class Libraries/Tuple Spec.docx // We will remove this after we move to v4 and Tuple is actually in there public struct Tuple&lt;TFirst, TSecond&gt; .... </code></pre>
[ { "answer_id": 237046, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://blogs.msdn.com/pfxteam/archive/2008/10/10/8994927.aspx\" rel=\"nofollow noreferrer\">Parallel Extensions</a></p>\n\n<p><a href=\"http://blogs.msdn.com/wenlong/archive/2008/09/07/net-4-0-wf-wcf-and-oslo.aspx\" rel=\"nofollow noreferrer\">WCF/WF improvements</a></p>\n\n<p>I expect BigInteger will be back, too. I'd really like to see a bunch of the F# immutable collections become part of \".NET proper\" too - and that wouldn't surprise me at all.</p>\n" }, { "answer_id": 237080, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 1, "selected": false, "text": "<p>I have seen the usage of <em>dynamic</em> keyword in C# 4.0 from <a href=\"http://jaoo.blip.tv/file/1317881/\" rel=\"nofollow noreferrer\">Anders Hejlsberg's JAOO talk</a>. It allows calling methods in a late-bindish way which will really help in COM interop scenarios.</p>\n\n<p>Usage:</p>\n\n<pre><code>// Instead of this:\nobject calc = GetCalculator();\nType calcType = calc.GetType();\nobject res = calcType.InvokeMember(\"Add\", \n BindingFlags.InvokeMethod, null,\n new int[] { 10, 20 });\nint sum = Convert.ToInt32(res);\n\n// you can write this:\ndynamic calc = GetCalculator();\nint sum = calc.Add(10, 20);\n</code></pre>\n\n<p><a href=\"http://img266.imageshack.us/img266/9469/dynamicxf4.png\" rel=\"nofollow noreferrer\">Static and Dynamic http://img266.imageshack.us/img266/9469/dynamicxf4.png</a></p>\n" }, { "answer_id": 237167, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://blogs.msdn.com/gblock/\" rel=\"nofollow noreferrer\">Glenn Block</a> confirmed on a recent <a href=\"http://herdingcode.com/\" rel=\"nofollow noreferrer\">Herding Code</a> episode that <a href=\"http://www.codeplex.com/MEF\" rel=\"nofollow noreferrer\">MEF</a> would be part of .NET 4.0.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29788/" ]
Does anyone know what will be in .NET 4.0? I found [tuples on codeplex](https://mef.svn.codeplex.com/svn/src/ComponentModel/System/Tuple.cs): ``` .... // NOTE : this is a TEMPORARY and a very minimalistic implementation of Tuple'2, // as defined in http://devdiv/sites/docs/NetFX4/CLR/Specs/Base Class Libraries/Tuple Spec.docx // We will remove this after we move to v4 and Tuple is actually in there public struct Tuple<TFirst, TSecond> .... ```
[Parallel Extensions](http://blogs.msdn.com/pfxteam/archive/2008/10/10/8994927.aspx) [WCF/WF improvements](http://blogs.msdn.com/wenlong/archive/2008/09/07/net-4-0-wf-wcf-and-oslo.aspx) I expect BigInteger will be back, too. I'd really like to see a bunch of the F# immutable collections become part of ".NET proper" too - and that wouldn't surprise me at all.
237,044
<p>I'm trying to compile code from F# to use in Silverlight. I compile with:</p> <p>--noframework --cliroot "C:\program Files\Microsoft Silverlight\2.0.31005.0" --standalone</p> <p>This generates a standalone assembly that references the SL framework. But when I try to add a reference to the generated assembly, I get this error:</p> <blockquote> <p>You can only add project references to other Silverlight projects in the solution.</p> </blockquote> <p>What is the VS plugin doing to determine that this isn't a Silverlight assembly? Here's the manifest:</p> <pre><code>// Metadata version: v2.0.50727 .assembly extern mscorlib { .publickeytoken = (7C EC 85 D7 BE A7 79 8E ) // |.....y. .ver 2:0:5:0 } .assembly FSSLLibrary1 { // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 01 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .module 'F#-Module-FSSLLibrary1' // MVID: {49038883-5D18-7281-A745-038383880349} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04120000 </code></pre> <p>I don't understand what it's finding that it doesn't like; it's pure verifiable IL. I compared to a SL "class library" assembly, and it looks the same. The only difference was some attributes, but I deleted those and VS still let me reference the DLL. I even added unverifiable IL to the "SL library" DLL and it still loaded.</p> <p>Any suggestions?</p> <p><em>Update:</em> I've done some poking around, and it doesn't seem to be the manifest that matters. It doesn't like something in the IL from the FSharp libraries. They are peverifiable, but something in there is triggering the rejection. </p>
[ { "answer_id": 245116, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 4, "selected": true, "text": "<p><strong>Answer!</strong></p>\n\n<p>Apparently the problem is that when you add a reference to the bin\\Release or bin\\Debug, Visual Studio (or the Silverlight project system) decides to try to reference the project. This fails for whatever reason.</p>\n\n<p>If you copy the F# output DLL to another location, then the reference goes through just fine. (This will be a file reference, not a project reference, of course.)</p>\n\n<p>Then setup dependencies so the F# library builds first, then you can use a file reference to get the F#-generated binary.</p>\n\n<p><em>Update:</em> One more apparent issue. If I turn optimize code on, then I get this error:</p>\n\n<pre><code>C:\\test\\SilverlightApplication1\\FSC(0,0): error FS0193: internal error: the module/namespace 'System' from compilation unit 'mscorlib' did not contain the namespace, module or type 'MarshalByRefObject'\n</code></pre>\n\n<p>If I keep optimized code off, this goes away and everything works fine.</p>\n" }, { "answer_id": 468894, "author": "Maurice", "author_id": 19676, "author_profile": "https://Stackoverflow.com/users/19676", "pm_score": 0, "selected": false, "text": "<p>Visual Studio uses the IsSilverlightAssembly() function in the Microsoft.VisualStudio.Silverlight.SLUtil type to check if a reference can be set.</p>\n\n<p>David Betz has a nice blog post describing the details <a href=\"http://www.netfxharmonics.com/2008/12/Reusing-NET-Assemblies-in-Silverlight\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27012/" ]
I'm trying to compile code from F# to use in Silverlight. I compile with: --noframework --cliroot "C:\program Files\Microsoft Silverlight\2.0.31005.0" --standalone This generates a standalone assembly that references the SL framework. But when I try to add a reference to the generated assembly, I get this error: > > You can only add project references to > other Silverlight projects in the > solution. > > > What is the VS plugin doing to determine that this isn't a Silverlight assembly? Here's the manifest: ``` // Metadata version: v2.0.50727 .assembly extern mscorlib { .publickeytoken = (7C EC 85 D7 BE A7 79 8E ) // |.....y. .ver 2:0:5:0 } .assembly FSSLLibrary1 { // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 01 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .module 'F#-Module-FSSLLibrary1' // MVID: {49038883-5D18-7281-A745-038383880349} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04120000 ``` I don't understand what it's finding that it doesn't like; it's pure verifiable IL. I compared to a SL "class library" assembly, and it looks the same. The only difference was some attributes, but I deleted those and VS still let me reference the DLL. I even added unverifiable IL to the "SL library" DLL and it still loaded. Any suggestions? *Update:* I've done some poking around, and it doesn't seem to be the manifest that matters. It doesn't like something in the IL from the FSharp libraries. They are peverifiable, but something in there is triggering the rejection.
**Answer!** Apparently the problem is that when you add a reference to the bin\Release or bin\Debug, Visual Studio (or the Silverlight project system) decides to try to reference the project. This fails for whatever reason. If you copy the F# output DLL to another location, then the reference goes through just fine. (This will be a file reference, not a project reference, of course.) Then setup dependencies so the F# library builds first, then you can use a file reference to get the F#-generated binary. *Update:* One more apparent issue. If I turn optimize code on, then I get this error: ``` C:\test\SilverlightApplication1\FSC(0,0): error FS0193: internal error: the module/namespace 'System' from compilation unit 'mscorlib' did not contain the namespace, module or type 'MarshalByRefObject' ``` If I keep optimized code off, this goes away and everything works fine.
237,058
<p>A string will be made up of certain symbols (ax,bx,dx,c,acc for example) and numbers.</p> <p>ex: ax 5 5 dx 3 acc c ax bx</p> <p>I want to replace one or all of the symbols (randomly) with another symbol of the same set. ie, replace one of {ax,bx,dx,c,acc} with one of {ax,bx,dx,c,acc}.</p> <p>replacement example: acc 5 5 dx 3 acc c ax bx or c 5 5 dx 3 acc c ax ax</p> <p>Is there a way to do this with regexes? In Java? If so, which methods should I use?</p>
[ { "answer_id": 237088, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 1, "selected": false, "text": "<p>To answer the first question: no.</p>\n\n<p>Since you are doing a random replace, regex will not help you, nothing about regex is random. * Since your strings are in an array, you don't need to find them with any pattern matching, so again regex isn't necessary. </p>\n\n<p>**Edit: the question has been edited so it no longer says the strings are in an array. In this case, assuming they are all in one big string, you might build a regex to find the parts you want to replace, as shown in other answers.*</p>\n" }, { "answer_id": 237097, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 0, "selected": false, "text": "<p>Use the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html\" rel=\"nofollow noreferrer\">Random</a> class to generate a random int to choose the index of the symbols.</p>\n\n<pre><code> String text = \"ax 5 5 dx 3 acc c ax bx\";\n System.out.println(\"Original: \" + text);\n String[] tokens = text.split(\" \");\n List&lt;Integer&gt; symbols = new ArrayList&lt;Integer&gt;();\n for(int i=0; i&lt;tokens.length; i++) {\n try {\n Integer.parseInt(tokens[i]);\n } catch (Exception e) {\n symbols.add(i);\n }\n }\n Random rand = new Random();\n // this is the part you can do multiple times\n int source = symbols.get((rand.nextInt(symbols.size())));\n int target = symbols.get((rand.nextInt(symbols.size())));\n tokens[target] = tokens[source];\n\n String result = tokens[0];\n for(int i=1; i&lt;tokens.length; i++) {\n result = result + \" \" + tokens[i];\n }\n System.out.println(\"Result: \" + result);\n</code></pre>\n\n<p>Make as many replacements as you need <em>before</em> you <a href=\"http://hivemind.apache.org/hivemind1/hivemind/apidocs/org/apache/hivemind/util/StringUtils.html\" rel=\"nofollow noreferrer\">join</a> the tokens back together.</p>\n\n<p>There are two parts here that might seem tricky. First, the try catch to identify those tokens that are not integers. I recommend you pull that part out into its own method, since it works, but it's a bit hacky.</p>\n\n<p>The second is where I set the <code>source</code> and <code>target</code> variables. What I'm doing there is getting a randomly selected <em>index</em> of one of the non-numeric symbols. Once I have two random indexes, I can swap them in the next line.</p>\n\n<p>An alternative would be, to build up a new String from randomly selected symbols after you've split the original String into an array.</p>\n" }, { "answer_id": 237105, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Yes, this can be done with regexes. \nProbably not very prettily, not\nwithout a loop or two</li>\n<li>Yes, this can be implemented in Java.</li>\n<li>See <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html\" rel=\"nofollow noreferrer\">Random</a>, the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex\" rel=\"nofollow noreferrer\">regex</a> package</li>\n<li>The implementation is left as an exercise for the student.</li>\n</ol>\n" }, { "answer_id": 237181, "author": "Andreas Petersson", "author_id": 16542, "author_profile": "https://Stackoverflow.com/users/16542", "pm_score": 3, "selected": true, "text": "<p>I think this is the most clean solution for replacing a certain set of symbols from a string containing a superset of them.\nappendreplacement is the key to this method.\none important caveat: do not include any unescped dollar characters ($) in your elements list. escape them by using \"\\$\"\neventually use<br>\n .replaceall(\"\\$\",\"\\\\$\");\non every string before adding it to the list.\nsee also the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuffer,%20java.lang.String)\" rel=\"nofollow noreferrer\">javadoc</a> in doubt about the $ signs.</p>\n\n<pre><code>import java.util.*;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\npublic class ReplaceTokens {\npublic static void main(String[] args) {\n List&lt;String&gt; elements = Arrays.asList(\"ax\", \"bx\", \"dx\", \"c\", \"acc\");\n final String patternStr = join(elements, \"|\"); //build string \"ax|bx|dx|c|acc\" \n Pattern p = Pattern.compile(patternStr);\n Matcher m = p.matcher(\"ax 5 5 dx 3 acc c ax bx\");\n StringBuffer sb = new StringBuffer();\n Random rand = new Random();\n while (m.find()){\n String randomSymbol = elements.get(rand.nextInt(elements.size()));\n m.appendReplacement(sb,randomSymbol);\n }\n m.appendTail(sb);\n System.out.println(sb);\n}\n\n/**\n * this method is only needed to generate the string ax|bx|dx|c|acc in a clean way....\n * @see org.apache.commons.lang.StringUtils.join for a more common alternative...\n */\npublic static String join(List&lt;String&gt; s, String delimiter) {\n if (s.isEmpty()) return \"\";\n Iterator&lt;String&gt; iter = s.iterator();\n StringBuffer buffer = new StringBuffer(iter.next());\n while (iter.hasNext()) buffer.append(delimiter).append(iter.next());\n return buffer.toString();\n}\n</code></pre>\n" }, { "answer_id": 237349, "author": "Dove", "author_id": 27677, "author_profile": "https://Stackoverflow.com/users/27677", "pm_score": -1, "selected": false, "text": "<p>thanks a bunch guys. here's what i came up with. see if you can come up with a more efficient way.</p>\n\n<pre><code>private final String[] symbolsPossible = {\"ax\",\"bx\",\"cx\",\"dx\",\"foo\"};\nprivate boolean exists;\nprivate final String mutate(String s)\n{\nString[] tokens=s.split(\" \");\nfor(int j=0; j&lt;tokens.length; j++)\nif(Math.random()&lt;.1) //10% chance of mutation per token\n{\n//checking to see if the token is a supported symbol\nexists=false;\nfor(int i=0; i&lt;symbolsPossible.length; i++)\n if(tokens[j].equals(symbolsPossible[i]))\n exists=true;\nif(exists)\n tokens[j]=symbolsPossible[(int)Math.random()*symbolsPossible.length];\n}\nStringBuffer result=new StringBuffer();\nfor(String t:tokens)\n result.append(t);\nreturn result;\n}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27677/" ]
A string will be made up of certain symbols (ax,bx,dx,c,acc for example) and numbers. ex: ax 5 5 dx 3 acc c ax bx I want to replace one or all of the symbols (randomly) with another symbol of the same set. ie, replace one of {ax,bx,dx,c,acc} with one of {ax,bx,dx,c,acc}. replacement example: acc 5 5 dx 3 acc c ax bx or c 5 5 dx 3 acc c ax ax Is there a way to do this with regexes? In Java? If so, which methods should I use?
I think this is the most clean solution for replacing a certain set of symbols from a string containing a superset of them. appendreplacement is the key to this method. one important caveat: do not include any unescped dollar characters ($) in your elements list. escape them by using "\$" eventually use .replaceall("\$","\\$"); on every string before adding it to the list. see also the [javadoc](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuffer,%20java.lang.String)) in doubt about the $ signs. ``` import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; public class ReplaceTokens { public static void main(String[] args) { List<String> elements = Arrays.asList("ax", "bx", "dx", "c", "acc"); final String patternStr = join(elements, "|"); //build string "ax|bx|dx|c|acc" Pattern p = Pattern.compile(patternStr); Matcher m = p.matcher("ax 5 5 dx 3 acc c ax bx"); StringBuffer sb = new StringBuffer(); Random rand = new Random(); while (m.find()){ String randomSymbol = elements.get(rand.nextInt(elements.size())); m.appendReplacement(sb,randomSymbol); } m.appendTail(sb); System.out.println(sb); } /** * this method is only needed to generate the string ax|bx|dx|c|acc in a clean way.... * @see org.apache.commons.lang.StringUtils.join for a more common alternative... */ public static String join(List<String> s, String delimiter) { if (s.isEmpty()) return ""; Iterator<String> iter = s.iterator(); StringBuffer buffer = new StringBuffer(iter.next()); while (iter.hasNext()) buffer.append(delimiter).append(iter.next()); return buffer.toString(); } ```
237,061
<p>I have several strings in the rough form:</p> <pre><code>[some text] [some number] [some more text] </code></pre> <p>I want to extract the text in [some number] using the Java Regex classes.</p> <p>I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].</p> <p>EDIT: I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].</p>
[ { "answer_id": 237068, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 10, "selected": true, "text": "<p>Full example:</p>\n\n<pre><code>private static final Pattern p = Pattern.compile(\"^([a-zA-Z]+)([0-9]+)(.*)\");\npublic static void main(String[] args) {\n // create matcher for pattern p and given string\n Matcher m = p.matcher(\"Testing123Testing\");\n\n // if an occurrence if a pattern was found in a given string...\n if (m.find()) {\n // ...then you can use group() methods.\n System.out.println(m.group(0)); // whole matched expression\n System.out.println(m.group(1)); // first expression from round brackets (Testing)\n System.out.println(m.group(2)); // second one (123)\n System.out.println(m.group(3)); // third one (Testing)\n }\n}\n</code></pre>\n\n<p>Since you're looking for the first number, you can use such regexp:</p>\n\n<pre><code>^\\D+(\\d+).*\n</code></pre>\n\n<p>and <code>m.group(1)</code> will return you the first number. Note that signed numbers can contain a minus sign:</p>\n\n<pre><code>^\\D+(-?\\d+).*\n</code></pre>\n" }, { "answer_id": 237078, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 4, "selected": false, "text": "<p>In Java 1.4 and up:</p>\n\n<pre><code>String input = \"...\";\nMatcher matcher = Pattern.compile(\"[^0-9]+([0-9]+)[^0-9]+\").matcher(input);\nif (matcher.find()) {\n String someNumberStr = matcher.group(1);\n // if you need this to be an int:\n int someNumberInt = Integer.parseInt(someNumberStr);\n}\n</code></pre>\n" }, { "answer_id": 237081, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": false, "text": "<p>Allain basically has the java code, so you can use that. However, his expression only matches <em>if</em> your numbers are only preceded by a stream of word characters. </p>\n\n<pre><code>\"(\\\\d+)\"\n</code></pre>\n\n<p>should be able to find the first string of digits. You don't need to specify what's before it, if you're sure that it's going to be the first string of digits. Likewise, there is no use to specify what's after it, unless you want that. If you just want the number, and are sure that it will be the first string of one or more digits then that's all you need. </p>\n\n<p>If you expect it to be offset by spaces, it will make it even more distinct to specify </p>\n\n<pre><code>\"\\\\s+(\\\\d+)\\\\s+\"\n</code></pre>\n\n<p>might be better. </p>\n\n<p>If you need all three parts, this will do:</p>\n\n<pre><code>\"(\\\\D+)(\\\\d+)(.*)\"\n</code></pre>\n\n<p><strong>EDIT</strong> The Expressions given by Allain and Jack suggest that you need to specify some subset of non-digits in order to capture <em>digits</em>. If you tell the regex engine you're looking for <code>\\d</code> then it's going to ignore everything before the digits. If J or A's expression <em>fits</em> your pattern, then the whole match <em>equals</em> the <em>input string</em>. And there's no reason to specify it. It probably slows a clean match down, if it isn't totally ignored. </p>\n" }, { "answer_id": 2061076, "author": "arturo", "author_id": 250319, "author_profile": "https://Stackoverflow.com/users/250319", "pm_score": 0, "selected": false, "text": "<p>How about <code>[^\\\\d]*([0-9]+[\\\\s]*[.,]{0,1}[\\\\s]*[0-9]*).*</code> I think it would take care of numbers with fractional part. \nI included white spaces and included <code>,</code> as possible separator.\nI'm trying to get the numbers out of a string including floats and taking into account that the user might make a mistake and include white spaces while typing the number.</p>\n" }, { "answer_id": 5553243, "author": "Tint Naing Win", "author_id": 693073, "author_profile": "https://Stackoverflow.com/users/693073", "pm_score": 2, "selected": false, "text": "<p>Try doing something like this:</p>\n\n<pre><code>Pattern p = Pattern.compile(\"^.+(\\\\d+).+\");\nMatcher m = p.matcher(\"Testing123Testing\");\n\nif (m.find()) {\n System.out.println(m.group(1));\n}\n</code></pre>\n" }, { "answer_id": 8116229, "author": "javaMan", "author_id": 771318, "author_profile": "https://Stackoverflow.com/users/771318", "pm_score": 6, "selected": false, "text": "<pre><code>import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Regex1 {\n public static void main(String[]args) {\n Pattern p = Pattern.compile(\"\\\\d+\");\n Matcher m = p.matcher(\"hello1234goodboy789very2345\");\n while(m.find()) {\n System.out.println(m.group());\n }\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1234\n789\n2345\n</code></pre>\n" }, { "answer_id": 9354651, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 4, "selected": false, "text": "<p>In addition to <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\" rel=\"noreferrer\">Pattern</a>, the Java <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29\" rel=\"noreferrer\">String</a> class also has several methods that can work with regular expressions, in your case the code will be:</p>\n\n<pre><code>\"ab123abc\".replaceFirst(\"\\\\D*(\\\\d*).*\", \"$1\")\n</code></pre>\n\n<p>where <code>\\\\D</code> is a non-digit character.</p>\n" }, { "answer_id": 10730820, "author": "shounak", "author_id": 1412460, "author_profile": "https://Stackoverflow.com/users/1412460", "pm_score": 1, "selected": false, "text": "<p>Look you can do it using StringTokenizer\n</p>\n\n<pre><code>String str = \"as:\"+123+\"as:\"+234+\"as:\"+345;\nStringTokenizer st = new StringTokenizer(str,\"as:\");\n\nwhile(st.hasMoreTokens())\n{\n String k = st.nextToken(); // you will get first numeric data i.e 123\n int kk = Integer.parseInt(k);\n System.out.println(\"k string token in integer \" + kk);\n\n String k1 = st.nextToken(); // you will get second numeric data i.e 234\n int kk1 = Integer.parseInt(k1);\n System.out.println(\"new string k1 token in integer :\" + kk1);\n\n String k2 = st.nextToken(); // you will get third numeric data i.e 345\n int kk2 = Integer.parseInt(k2);\n System.out.println(\"k2 string token is in integer : \" + kk2);\n}\n</code></pre>\n\n<p>Since we are taking these numeric data into three different variables we can use this data anywhere in the code (for further use)</p>\n" }, { "answer_id": 13916090, "author": "LukaszTaraszka", "author_id": 1816687, "author_profile": "https://Stackoverflow.com/users/1816687", "pm_score": 3, "selected": false, "text": "<p>This function collect all matching sequences from string. In this example it takes all email addresses from string.</p>\n\n<pre><code>static final String EMAIL_PATTERN = \"[_A-Za-z0-9-\\\\+]+(\\\\.[_A-Za-z0-9-]+)*@\"\n + \"[A-Za-z0-9-]+(\\\\.[A-Za-z0-9]+)*(\\\\.[A-Za-z]{2,})\";\n\npublic List&lt;String&gt; getAllEmails(String message) { \n List&lt;String&gt; result = null;\n Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);\n\n if (matcher.find()) {\n result = new ArrayList&lt;String&gt;();\n result.add(matcher.group());\n\n while (matcher.find()) {\n result.add(matcher.group());\n }\n }\n\n return result;\n}\n</code></pre>\n\n<p>For <code>message = \"[email protected], &lt;[email protected]&gt;&gt;&gt;&gt; [email protected]\"</code> it will create List of 3 elements.</p>\n" }, { "answer_id": 23009935, "author": "user1722707", "author_id": 1722707, "author_profile": "https://Stackoverflow.com/users/1722707", "pm_score": 0, "selected": false, "text": "<p>Sometimes you can use simple .split(\"REGEXP\") method available in java.lang.String. For example:<br></p>\n\n<pre><code>String input = \"first,second,third\";\n\n//To retrieve 'first' \ninput.split(\",\")[0] \n//second\ninput.split(\",\")[1]\n//third\ninput.split(\",\")[2]\n</code></pre>\n" }, { "answer_id": 23010127, "author": "seeker", "author_id": 1632156, "author_profile": "https://Stackoverflow.com/users/1632156", "pm_score": -1, "selected": false, "text": "<p>if you are reading from file then this can help you</p>\n\n<pre><code> try{\n InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();\n BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));\n String line;\n //Ref:03\n while ((line = br.readLine()) != null) {\n if (line.matches(\"[A-Z],\\\\d,(\\\\d*,){2}(\\\\s*\\\\d*\\\\|\\\\d*:)+\")) {\n String[] splitRecord = line.split(\",\");\n //do something\n }\n else{\n br.close();\n //error\n return;\n }\n }\n br.close();\n\n }\n }\n catch (IOException ioExpception){\n logger.logDebug(\"Exception \" + ioExpception.getStackTrace());\n }\n</code></pre>\n" }, { "answer_id": 31014297, "author": "NoBrainer", "author_id": 1169991, "author_profile": "https://Stackoverflow.com/users/1169991", "pm_score": 2, "selected": false, "text": "<h2>Simple Solution</h2>\n\n<pre><code>// Regexplanation:\n// ^ beginning of line\n// \\\\D+ 1+ non-digit characters\n// (\\\\d+) 1+ digit characters in a capture group\n// .* 0+ any character\nString regexStr = \"^\\\\D+(\\\\d+).*\";\n\n// Compile the regex String into a Pattern\nPattern p = Pattern.compile(regexStr);\n\n// Create a matcher with the input String\nMatcher m = p.matcher(inputStr);\n\n// If we find a match\nif (m.find()) {\n // Get the String from the first capture group\n String someDigits = m.group(1);\n // ...do something with someDigits\n}\n</code></pre>\n\n<h2>Solution in a Util Class</h2>\n\n<pre><code>public class MyUtil {\n private static Pattern pattern = Pattern.compile(\"^\\\\D+(\\\\d+).*\");\n private static Matcher matcher = pattern.matcher(\"\");\n\n // Assumptions: inputStr is a non-null String\n public static String extractFirstNumber(String inputStr){\n // Reset the matcher with a new input String\n matcher.reset(inputStr);\n\n // Check if there's a match\n if(matcher.find()){\n // Return the number (in the first capture group)\n return matcher.group(1);\n }else{\n // Return some default value, if there is no match\n return null;\n }\n }\n}\n\n...\n\n// Use the util function and print out the result\nString firstNum = MyUtil.extractFirstNumber(\"Testing4234Things\");\nSystem.out.println(firstNum);\n</code></pre>\n" }, { "answer_id": 39076286, "author": "Mohammadreza Tavakoli", "author_id": 4393496, "author_profile": "https://Stackoverflow.com/users/4393496", "pm_score": -1, "selected": false, "text": "<pre><code>Pattern p = Pattern.compile(\"(\\\\D+)(\\\\d+)(.*)\");\nMatcher m = p.matcher(\"this is your number:1234 thank you\");\nif (m.find()) {\n String someNumberStr = m.group(2);\n int someNumberInt = Integer.parseInt(someNumberStr);\n}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
I have several strings in the rough form: ``` [some text] [some number] [some more text] ``` I want to extract the text in [some number] using the Java Regex classes. I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number]. EDIT: I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].
Full example: ``` private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)"); public static void main(String[] args) { // create matcher for pattern p and given string Matcher m = p.matcher("Testing123Testing"); // if an occurrence if a pattern was found in a given string... if (m.find()) { // ...then you can use group() methods. System.out.println(m.group(0)); // whole matched expression System.out.println(m.group(1)); // first expression from round brackets (Testing) System.out.println(m.group(2)); // second one (123) System.out.println(m.group(3)); // third one (Testing) } } ``` Since you're looking for the first number, you can use such regexp: ``` ^\D+(\d+).* ``` and `m.group(1)` will return you the first number. Note that signed numbers can contain a minus sign: ``` ^\D+(-?\d+).* ```
237,063
<p>I've created a one-line batch file to run SqlMetal to regenerate a LINQ to SQL DataContext for my database; this works great. </p> <p><em>Refresh_DataContext.bat</em>:</p> <pre><code>"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\sqlmetal.exe" /server:.\sqlexpress /database:MyDatabaseName /code:"%~dp0\DataContext.vb" /context:DataContext /views /functions /sprocs /pluralize </code></pre> <p>So far I can run this by opening the enclosing folder in Explorer and running the batch file, and I've also added it to the Tools menu (<code>Tools/External Tools.../Add</code>). </p> <p>Now I'd like to run this batch file whenever I build (in certain configurations). How do I do this?</p>
[ { "answer_id": 237227, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 2, "selected": false, "text": "<p>What you seem to be looking for can be found under \"Pre-build event command line\" under your project's properties. Click the \"Build Events\" tab, and you'll have a little space to enter in a command line which does what you want.</p>\n" }, { "answer_id": 576469, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 1, "selected": true, "text": "<p>Doh! Of course. Web Application projects have pre- and post- build events; Web Site projects don't. </p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I've created a one-line batch file to run SqlMetal to regenerate a LINQ to SQL DataContext for my database; this works great. *Refresh\_DataContext.bat*: ``` "C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\sqlmetal.exe" /server:.\sqlexpress /database:MyDatabaseName /code:"%~dp0\DataContext.vb" /context:DataContext /views /functions /sprocs /pluralize ``` So far I can run this by opening the enclosing folder in Explorer and running the batch file, and I've also added it to the Tools menu (`Tools/External Tools.../Add`). Now I'd like to run this batch file whenever I build (in certain configurations). How do I do this?
Doh! Of course. Web Application projects have pre- and post- build events; Web Site projects don't.
237,064
<p>i am trying to compile this very simple piece of code</p> <pre><code>class myList { public: std::vector&lt;std::string&gt; vec; class Items { public: void Add(std::string str) { myList::vec.push_back(str); }; }items; }; int main() { myList newList; newList.items.Add("A"); } </code></pre> <p>what can i do to make this work without creating more objects that needed or overcomplicating stuff... </p>
[ { "answer_id": 237072, "author": "richq", "author_id": 4596, "author_profile": "https://Stackoverflow.com/users/4596", "pm_score": 5, "selected": true, "text": "<p>Add a couple of constructors and a pointer to the parent class.</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\nclass myList\n{\npublic:\n std::vector&lt;std::string&gt; vec;\n myList(): items(this) {} // Added\n class Items\n {\n public:\n Items(myList *ml): self(ml) {} // Added\n void Add(std::string str)\n {\n self-&gt;vec.push_back(str); // Changed\n };\n myList *self; //Added\n }items;\n};\n\nint main()\n{\n myList newList;\n newList.items.Add(\"A\");\n}\n</code></pre>\n\n<p>You need the myList() constructor, so it registers instances of itself with the instance of the inner class member variable. Then you need the Items constructor to store the pointer to the outer myList class instance. Finally in the Add method, you need to reference vec in the stored myList instance.</p>\n\n<p>As Catskul points out, the Item constructor mustn't actually do anything with the myList pointer it receives. I'd also like to say that though this answer is closer to the original intent, steveth45's answer is closer to what you would want to do in a real program.</p>\n" }, { "answer_id": 237073, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 4, "selected": false, "text": "<p>This way you aren't exposing your class members directly. Your example seems over-architected a bit. Why put a std::vector into a class and then expose it as public? </p>\n\n<pre><code>class myList\n{\nprivate:\n std::vector&lt;std::string&gt; vec;\npublic:\n void Add(std::string str)\n {\n vec.push_back(str);\n };\n};\n\nint main()\n{\n myList newList;\n newList.Add(\"A\");\n}\n</code></pre>\n" }, { "answer_id": 237076, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 2, "selected": false, "text": "<p>Inner classes are only related by name. You can't refer to the vector in the base class like that.</p>\n\n<p>You either need to move the vector in to the inner class or store a reference to it. </p>\n" }, { "answer_id": 237083, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "<p>Unlike Java, inner objects in C++ don't have access to an outer 'this' pointer ... if you think about it there may be cases where there isn't one to reference.</p>\n\n<p>Richard Quirk's solution is the nearest you can get in C++</p>\n" }, { "answer_id": 1509019, "author": "phoku", "author_id": 157410, "author_profile": "https://Stackoverflow.com/users/157410", "pm_score": 0, "selected": false, "text": "<p>You can simplify this by the following construct:</p>\n\n<pre><code>typedef std::vector&lt;std::string&gt; myList;\n</code></pre>\n\n<p>Really why don't you use the STL vector directly?\nThis way you get all the standard algorithms work with the\ndata.</p>\n" }, { "answer_id": 14076732, "author": "nickdu", "author_id": 1769110, "author_profile": "https://Stackoverflow.com/users/1769110", "pm_score": 1, "selected": false, "text": "<p>While this post is a few years old I <em>might</em> be able to add something useful to it. While I will say that the design of the class in the original post doesn't look that great, there are times where it's useful to have an embedded class be able to access the containing class. This can easily be done without storing extra pointers. Below is an example. It should work as I took it from some existing code and changed some names around. The key is the EmbeddorOf macro. Works like a charm.</p>\n\n<p>//////////////////// .h file /////////////////////////</p>\n\n<pre><code>struct IReferenceCounted\n{\n virtual unsigned long AddRef() = 0;\n virtual unsigned long Release() = 0;\n};\n\nstruct IFoo : public IReferenceCounted\n{\n};\n\nclass Foo : public IFoo\n{\npublic:\n static IFoo* Create();\n static IFoo* Create(IReferenceCounted* outer, IReferenceCounted** inner);\n\nprivate:\n Foo();\n Foo(IReferenceCounted* outer);\n ~Foo();\n\n // IReferenceCounted\n\n unsigned long AddRef();\n unsigned long Release();\n\nprivate:\n struct EIReferenceCounted : IReferenceCounted\n {\n // IReferenceCounted\n\n unsigned long AddRef();\n unsigned long Release();\n } _inner;\n\n unsigned long _refs;\n IReferenceCounted* _outer;\n};\n</code></pre>\n\n<p>//////////////// .cpp file /////////////////</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stddef.h&gt;\n#include \"Foo.h\"\n\n#define EmbeddorOf(class, member, this) \\\n (class *) ((char *) this - offsetof(class, member))\n\n// Foo\n\nFoo::Foo() : _refs(1), _outer(&amp;this-&gt;_inner)\n{\n}\n\nFoo::Foo(IReferenceCounted* outer) : _refs(1), _outer(outer)\n{\n}\n\nFoo::~Foo()\n{\n printf(\"Foo::~Foo()\\n\");\n}\n\nIFoo* Foo::Create()\n{\n return new Foo();\n}\n\nIFoo* Foo::Create(IReferenceCounted* outer, IReferenceCounted** inner)\n{\n Foo* foo = new Foo(outer);\n *inner = &amp;foo-&gt;_inner;\n return (IFoo*) foo;\n}\n\n// IReferenceCounted\n\nunsigned long Foo::AddRef()\n{\n printf(\"Foo::AddRef()\\n\");\n return this-&gt;_outer-&gt;AddRef();\n}\n\nunsigned long Foo::Release()\n{\n printf(\"Foo::Release()\\n\");\n return this-&gt;_outer-&gt;Release();\n}\n\n// Inner IReferenceCounted\n\nunsigned long Foo::EIReferenceCounted::AddRef()\n{\n Foo* pThis = EmbeddorOf(Foo, _inner, this);\n return ++pThis-&gt;_refs;\n}\n\nunsigned long Foo::EIReferenceCounted::Release()\n{\n Foo* pThis = EmbeddorOf(Foo, _inner, this);\n unsigned long refs = --pThis-&gt;_refs;\n if (refs == 0)\n {\n\n // Artifically increment so that we won't try to destroy multiple\n // times in the event that our destructor causes AddRef()'s or\n // Releases().\n\n pThis-&gt;_refs = 1;\n delete pThis;\n }\n return refs;\n}\n</code></pre>\n\n<p>Nick</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28954/" ]
i am trying to compile this very simple piece of code ``` class myList { public: std::vector<std::string> vec; class Items { public: void Add(std::string str) { myList::vec.push_back(str); }; }items; }; int main() { myList newList; newList.items.Add("A"); } ``` what can i do to make this work without creating more objects that needed or overcomplicating stuff...
Add a couple of constructors and a pointer to the parent class. ``` #include <string> #include <vector> class myList { public: std::vector<std::string> vec; myList(): items(this) {} // Added class Items { public: Items(myList *ml): self(ml) {} // Added void Add(std::string str) { self->vec.push_back(str); // Changed }; myList *self; //Added }items; }; int main() { myList newList; newList.items.Add("A"); } ``` You need the myList() constructor, so it registers instances of itself with the instance of the inner class member variable. Then you need the Items constructor to store the pointer to the outer myList class instance. Finally in the Add method, you need to reference vec in the stored myList instance. As Catskul points out, the Item constructor mustn't actually do anything with the myList pointer it receives. I'd also like to say that though this answer is closer to the original intent, steveth45's answer is closer to what you would want to do in a real program.
237,079
<p>What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?</p>
[ { "answer_id": 237082, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 6, "selected": false, "text": "<p><a href=\"https://docs.python.org/2/library/stat.html#module-stat\" rel=\"nofollow noreferrer\">os.stat</a></p>\n<p>In newer code you should probably use <a href=\"http://docs.python.org/library/os.path.html#os.path.getmtime\" rel=\"nofollow noreferrer\">os.path.getmtime()</a> (<a href=\"https://stackoverflow.com/questions/237079/how-to-get-file-creation-and-modification-date-times/237082#comment1381307_237082\">thanks, Christian Oudard</a>).</p>\n<p>But note that it returns a floating point value of <em>time_t</em> with fraction seconds (if your OS supports it).</p>\n" }, { "answer_id": 237084, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 10, "selected": false, "text": "<p>You have a couple of choices. For one, you can use the <a href=\"https://docs.python.org/library/os.path.html#os.path.getmtime\" rel=\"noreferrer\"><code>os.path.getmtime</code></a> and <a href=\"https://docs.python.org/library/os.path.html#os.path.getctime\" rel=\"noreferrer\"><code>os.path.getctime</code></a> functions:</p>\n<pre><code>import os.path, time\nprint(&quot;last modified: %s&quot; % time.ctime(os.path.getmtime(file)))\nprint(&quot;created: %s&quot; % time.ctime(os.path.getctime(file)))\n</code></pre>\n<p>Your other option is to use <a href=\"https://docs.python.org/library/os.html#os.stat\" rel=\"noreferrer\"><code>os.stat</code></a>:</p>\n<pre><code>import os, time\n(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)\nprint(&quot;last modified: %s&quot; % time.ctime(mtime))\n</code></pre>\n<p><strong>Note</strong>: <code>ctime()</code> does <em>not</em> refer to creation time on *nix systems, but rather the last time the <a href=\"https://en.wikipedia.org/wiki/Inode\" rel=\"noreferrer\">inode</a> data changed. (Thanks to <a href=\"https://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times#comment9847709_237084\">kojiro for making that fact more clear</a> in the comments by providing a link to an interesting blog post.)</p>\n" }, { "answer_id": 237092, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 6, "selected": false, "text": "<p>There are two methods to get the mod time, os.path.getmtime() or os.stat(), but the ctime is not reliable cross-platform (see below).</p>\n<h3><a href=\"http://www.python.org/doc/2.5.2/lib/module-os.path.html\" rel=\"noreferrer\">os.path.getmtime()</a></h3>\n<p><strong>getmtime</strong>(<em>path</em>)<br />\n<em>Return the time of last modification of path. The return value is a number giving the\nnumber of seconds since the epoch (see the time module). Raise os.error if the file does\nnot exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If\nos.stat_float_times() returns True, the result is a floating point number.</em></p>\n<h3><a href=\"http://www.python.org/doc/2.5.2/lib/os-file-dir.html\" rel=\"noreferrer\">os.stat()</a></h3>\n<p><strong>stat</strong>(<em>path</em>)<br />\n<em>Perform a stat() system call on the given path. The return value is an object whose\nattributes correspond to the members of the stat structure, namely: st_mode (protection\nbits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid\n(user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes),\nst_atime (time of most recent access), <strong>st_mtime</strong> (time of most recent content\nmodification), <strong>st_ctime</strong> (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)</em>:</p>\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; statinfo = os.stat('somefile.txt')\n&gt;&gt;&gt; statinfo\n(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)\n&gt;&gt;&gt; statinfo.st_size\n926L\n&gt;&gt;&gt; \n</code></pre>\n<p>In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.</p>\n" }, { "answer_id": 237093, "author": "mithrandi", "author_id": 31490, "author_profile": "https://Stackoverflow.com/users/31490", "pm_score": 4, "selected": false, "text": "<p><code>os.stat</code> returns a named tuple with <code>st_mtime</code> and <code>st_ctime</code> attributes. The modification time is <code>st_mtime</code> on both platforms; unfortunately, on Windows, <code>ctime</code> means \"creation time\", whereas on POSIX it means \"change time\". I'm not aware of any way to get the creation time on POSIX platforms.</p>\n" }, { "answer_id": 237094, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 1, "selected": false, "text": "<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.stat('feedparser.py').st_mtime\n1136961142.0\n&gt;&gt;&gt; os.stat('feedparser.py').st_ctime\n1222664012.233\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 367166, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p><code>os.stat</code> does include the creation time. There's just no definition of st_anything for the element of <code>os.stat()</code> that contains the time.</p>\n\n<p>So try this:</p>\n\n<p><code>os.stat('feedparser.py')[8]</code></p>\n\n<p>Compare that with your create date on the file in ls -lah</p>\n\n<p>They should be the same.</p>\n" }, { "answer_id": 1526089, "author": "Christian Oudard", "author_id": 3757, "author_profile": "https://Stackoverflow.com/users/3757", "pm_score": 9, "selected": false, "text": "<p>The best function to use for this is <a href=\"http://docs.python.org/library/os.path.html#os.path.getmtime\" rel=\"noreferrer\">os.path.getmtime()</a>. Internally, this just uses <code>os.stat(filename).st_mtime</code>.</p>\n<p>The datetime module is the best for manipulating timestamps, so you can get the modification date as a <code>datetime</code> object like this:</p>\n<pre><code>import os\nimport datetime\ndef modification_date(filename):\n t = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(t)\n</code></pre>\n<p>Usage example:</p>\n<pre><code>&gt;&gt;&gt; d = modification_date('/var/log/syslog')\n&gt;&gt;&gt; print d\n2009-10-06 10:50:01\n&gt;&gt;&gt; print repr(d)\ndatetime.datetime(2009, 10, 6, 10, 50, 1)\n</code></pre>\n" }, { "answer_id": 28444315, "author": "Muhammad Lukman Low", "author_id": 501800, "author_profile": "https://Stackoverflow.com/users/501800", "pm_score": 0, "selected": false, "text": "<p>If the following symbolic links are not important, you can also use the <code>os.lstat</code> builtin.</p>\n<pre><code>&gt;&gt;&gt; os.lstat(&quot;2048.py&quot;)\nposix.stat_result(st_mode=33188, st_ino=4172202, st_dev=16777218L, st_nlink=1, st_uid=501, st_gid=20, st_size=2078, st_atime=1423378041, st_mtime=1423377552, st_ctime=1423377553)\n&gt;&gt;&gt; os.lstat(&quot;2048.py&quot;).st_atime\n1423378041.0\n</code></pre>\n" }, { "answer_id": 39501288, "author": "Mark Amery", "author_id": 1709587, "author_profile": "https://Stackoverflow.com/users/1709587", "pm_score": 10, "selected": false, "text": "<p>Getting some sort of modification date in a cross-platform way is easy - just call <a href=\"https://docs.python.org/library/os.path.html#os.path.getmtime\" rel=\"noreferrer\"><code>os.path.getmtime(<i>path</i>)</code></a> and you'll get the Unix timestamp of when the file at <code>path</code> was last modified.</p>\n\n<p>Getting file <em>creation</em> dates, on the other hand, is fiddly and platform-dependent, differing even between the three big OSes:</p>\n\n<ul>\n<li>On <strong>Windows</strong>, a file's <code>ctime</code> (documented at <a href=\"https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx</a>) stores its creation date. You can access this in Python through <a href=\"https://docs.python.org/library/os.path.html#os.path.getctime\" rel=\"noreferrer\"><code>os.path.getctime()</code></a> or the <a href=\"https://docs.python.org/3/library/os.html#os.stat_result.st_ctime\" rel=\"noreferrer\"><code>.st_ctime</code></a> attribute of the result of a call to <a href=\"https://docs.python.org/3/library/os.html#os.stat\" rel=\"noreferrer\"><code>os.stat()</code></a>. This <em>won't</em> work on Unix, where the <code>ctime</code> <a href=\"http://www.linux-faqs.info/general/difference-between-mtime-ctime-and-atime\" rel=\"noreferrer\">is the last time that the file's attributes <em>or</em> content were changed</a>.</li>\n<li>On <strong>Mac</strong>, as well as some other Unix-based OSes, you can use the <a href=\"https://docs.python.org/3/library/os.html#os.stat_result.st_birthtime\" rel=\"noreferrer\"><code>.st_birthtime</code></a> attribute of the result of a call to <code>os.stat()</code>.</li>\n<li><p>On <strong>Linux</strong>, this is currently impossible, at least without writing a C extension for Python. Although some file systems commonly used with Linux <a href=\"https://unix.stackexchange.com/questions/7562/what-file-systems-on-linux-store-the-creation-time\">do store creation dates</a> (for example, <code>ext4</code> stores them in <code>st_crtime</code>) , the Linux kernel <a href=\"https://unix.stackexchange.com/questions/91197/how-to-find-creation-date-of-file\">offers no way of accessing them</a>; in particular, the structs it returns from <code>stat()</code> calls in C, as of the latest kernel version, <a href=\"https://github.com/torvalds/linux/blob/v4.8-rc6/include/linux/stat.h\" rel=\"noreferrer\">don't contain any creation date fields</a>. You can also see that the identifier <code>st_crtime</code> doesn't currently feature anywhere in the <a href=\"https://github.com/python/cpython/search?utf8=%E2%9C%93&amp;q=st_crtime\" rel=\"noreferrer\">Python source</a>. At least if you're on <code>ext4</code>, the data <em>is</em> attached to the inodes in the file system, but there's no convenient way of accessing it.</p>\n\n<p>The next-best thing on Linux is to access the file's <code>mtime</code>, through either <a href=\"https://docs.python.org/library/os.path.html#os.path.getmtime\" rel=\"noreferrer\"><code>os.path.getmtime()</code></a> or the <a href=\"https://docs.python.org/3/library/os.html#os.stat_result.st_mtime\" rel=\"noreferrer\"><code>.st_mtime</code></a> attribute of an <code>os.stat()</code> result. This will give you the last time the file's content was modified, which may be adequate for some use cases.</p></li>\n</ul>\n\n<p>Putting this all together, cross-platform code should look something like this...</p>\n\n<pre><code>import os\nimport platform\n\ndef creation_date(path_to_file):\n \"\"\"\n Try to get the date that a file was created, falling back to when it was\n last modified if that isn't possible.\n See http://stackoverflow.com/a/39501288/1709587 for explanation.\n \"\"\"\n if platform.system() == 'Windows':\n return os.path.getctime(path_to_file)\n else:\n stat = os.stat(path_to_file)\n try:\n return stat.st_birthtime\n except AttributeError:\n # We're probably on Linux. No easy way to get creation dates here,\n # so we'll settle for when its content was last modified.\n return stat.st_mtime\n</code></pre>\n" }, { "answer_id": 52858040, "author": "Steven C. Howell", "author_id": 3585557, "author_profile": "https://Stackoverflow.com/users/3585557", "pm_score": 8, "selected": true, "text": "<p>In Python 3.4 and above, you can use the object oriented <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\">pathlib module</a> interface which includes wrappers for much of the os module. Here is an example of getting the file stats.</p>\n<pre><code>&gt;&gt;&gt; import pathlib\n&gt;&gt;&gt; fname = pathlib.Path('test.py')\n&gt;&gt;&gt; assert fname.exists(), f'No such file: {fname}' # check that the file exists\n&gt;&gt;&gt; print(fname.stat())\nos.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)\n</code></pre>\n<p>For more information about what <code>os.stat_result</code> contains, refer to <a href=\"https://docs.python.org/3/library/os.html#os.stat_result\" rel=\"noreferrer\">the documentation</a>. For the modification time you want <code>fname.stat().st_mtime</code>:</p>\n<pre><code>&gt;&gt;&gt; import datetime\n&gt;&gt;&gt; mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime, tz=datetime.timezone.utc)\n&gt;&gt;&gt; print(mtime)\ndatetime.datetime(2018, 10, 17, 10, 49, 0, 249980)\n</code></pre>\n<p>If you want the creation time on Windows, or the most recent metadata change on Unix, you would use <code>fname.stat().st_ctime</code>:</p>\n<pre><code>&gt;&gt;&gt; ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime, tz=datetime.timezone.utc)\n&gt;&gt;&gt; print(ctime)\ndatetime.datetime(2018, 4, 11, 16, 57, 52, 151953)\n</code></pre>\n<p><a href=\"https://realpython.com/python-pathlib/\" rel=\"noreferrer\">This article</a> has more helpful info and examples for the pathlib module.</p>\n" }, { "answer_id": 53586899, "author": "Puddle", "author_id": 9312988, "author_profile": "https://Stackoverflow.com/users/9312988", "pm_score": 6, "selected": false, "text": "<pre><code>import os, time, datetime\n\nfile = &quot;somefile.txt&quot;\nprint(file)\n\nprint(&quot;Modified&quot;)\nprint(os.stat(file)[-2])\nprint(os.stat(file).st_mtime)\nprint(os.path.getmtime(file))\n\nprint()\n\nprint(&quot;Created&quot;)\nprint(os.stat(file)[-1])\nprint(os.stat(file).st_ctime)\nprint(os.path.getctime(file))\n\nprint()\n\nmodified = os.path.getmtime(file)\nprint(&quot;Date modified: &quot;+time.ctime(modified))\nprint(&quot;Date modified:&quot;,datetime.datetime.fromtimestamp(modified))\nyear,month,day,hour,minute,second=time.localtime(modified)[:-3]\nprint(&quot;Date modified: %02d/%02d/%d %02d:%02d:%02d&quot;%(day,month,year,hour,minute,second))\n\nprint()\n\ncreated = os.path.getctime(file)\nprint(&quot;Date created: &quot;+time.ctime(created))\nprint(&quot;Date created:&quot;,datetime.datetime.fromtimestamp(created))\nyear,month,day,hour,minute,second=time.localtime(created)[:-3]\nprint(&quot;Date created: %02d/%02d/%d %02d:%02d:%02d&quot;%(day,month,year,hour,minute,second))\n</code></pre>\n<p>prints</p>\n<pre><code>somefile.txt\nModified\n1429613446\n1429613446.0\n1429613446.0\n\nCreated\n1517491049\n1517491049.28306\n1517491049.28306\n\nDate modified: Tue Apr 21 11:50:46 2015\nDate modified: 2015-04-21 11:50:46\nDate modified: 21/04/2015 11:50:46\n\nDate created: Thu Feb 1 13:17:29 2018\nDate created: 2018-02-01 13:17:29.283060\nDate created: 01/02/2018 13:17:29\n</code></pre>\n<p>Note: A file's ctime on Linux is slightly different than on Windows.<br />\nWindows users know theirs as &quot;creation time&quot;.<br />\nLinux users know theirs as &quot;change time&quot;.</p>\n" }, { "answer_id": 56333103, "author": "Delgan", "author_id": 2291710, "author_profile": "https://Stackoverflow.com/users/2291710", "pm_score": 2, "selected": false, "text": "<p>It may worth taking a look at the <a href=\"https://github.com/kootenpv/crtime\" rel=\"nofollow noreferrer\"><code>crtime</code></a> library which implements cross-platform access to the file creation time.</p>\n\n<pre><code>from crtime import get_crtimes_in_dir\n\nfor fname, date in get_crtimes_in_dir(\".\", raise_on_error=True, as_epoch=False):\n print(fname, date)\n # file_a.py Mon Mar 18 20:51:18 CET 2019\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?
In Python 3.4 and above, you can use the object oriented [pathlib module](https://docs.python.org/3/library/pathlib.html) interface which includes wrappers for much of the os module. Here is an example of getting the file stats. ``` >>> import pathlib >>> fname = pathlib.Path('test.py') >>> assert fname.exists(), f'No such file: {fname}' # check that the file exists >>> print(fname.stat()) os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272) ``` For more information about what `os.stat_result` contains, refer to [the documentation](https://docs.python.org/3/library/os.html#os.stat_result). For the modification time you want `fname.stat().st_mtime`: ``` >>> import datetime >>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime, tz=datetime.timezone.utc) >>> print(mtime) datetime.datetime(2018, 10, 17, 10, 49, 0, 249980) ``` If you want the creation time on Windows, or the most recent metadata change on Unix, you would use `fname.stat().st_ctime`: ``` >>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime, tz=datetime.timezone.utc) >>> print(ctime) datetime.datetime(2018, 4, 11, 16, 57, 52, 151953) ``` [This article](https://realpython.com/python-pathlib/) has more helpful info and examples for the pathlib module.
237,085
<p>It's possible to write <a href="http://en.wikipedia.org/wiki/Markdown" rel="noreferrer">Markdown</a> content with invalid syntax. Invalid means that the <a href="http://www.deveiate.org/projects/BlueCloth" rel="noreferrer">BlueCloth</a> library fails to parse the content and throws an exception. The <code>markdown</code> helper in Rails doesn't catch any BlueCloth exceptions and because of that the complete page fails to render (500 Server Error page is rendered instead).</p> <p>In my case, users are allowed to write Markdown content and save it to the database. If someone used invalid syntax, all successive rendering attempts of that content fail (Status Code 500 - Internal Server Error).</p> <p>How do you get around this issue? Is it possible to validate the Markdown syntax at the Model-level before saving to the database?</p>
[ { "answer_id": 237200, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 4, "selected": true, "text": "<p>You should write your own validation method in which you would initialize BlueCloth object, and try to call <code>to_html</code> method catching any exception. If you catch an exception, validation fails, otherwise it should be ok.</p>\n\n<p>In your model:</p>\n\n<pre><code>protected:\n\ndef validate\n bc = BlueCloth.new(your_markdown_string_attribute)\n begin\n bc.to_html\n rescue\n errors.add(:your_markdown_string_attribute, 'has invalid markdown syntax')\n end\nend\n</code></pre>\n" }, { "answer_id": 277564, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 1, "selected": false, "text": "<p>I've done a bit of research and decided to use <a href=\"http://github.com/rtomayko/rdiscount/tree/master\" rel=\"nofollow noreferrer\">RDiscount</a> instead of BlueCloth. RDiscount seems to be much faster and more reliable than BlueCloth.</p>\n\n<p>It's easy to integrate RDiscount in your Rails environment. Include the following snipped in your <code>environment.rb</code> and you are ready to go:</p>\n\n<pre><code>begin\n require \"rdiscount\"\n BlueCloth = RDiscount\nrescue LoadError\n # BlueCloth is still the our fallback,\n # if RDiscount is not available\n require 'bluecloth'\nend\n</code></pre>\n\n<p>(tested with Rails 2.2.0)</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
It's possible to write [Markdown](http://en.wikipedia.org/wiki/Markdown) content with invalid syntax. Invalid means that the [BlueCloth](http://www.deveiate.org/projects/BlueCloth) library fails to parse the content and throws an exception. The `markdown` helper in Rails doesn't catch any BlueCloth exceptions and because of that the complete page fails to render (500 Server Error page is rendered instead). In my case, users are allowed to write Markdown content and save it to the database. If someone used invalid syntax, all successive rendering attempts of that content fail (Status Code 500 - Internal Server Error). How do you get around this issue? Is it possible to validate the Markdown syntax at the Model-level before saving to the database?
You should write your own validation method in which you would initialize BlueCloth object, and try to call `to_html` method catching any exception. If you catch an exception, validation fails, otherwise it should be ok. In your model: ``` protected: def validate bc = BlueCloth.new(your_markdown_string_attribute) begin bc.to_html rescue errors.add(:your_markdown_string_attribute, 'has invalid markdown syntax') end end ```
237,104
<p>What is the most concise and efficient way to find out if a JavaScript array contains a value?</p> <p>This is the only way I know to do it:</p> <pre><code>function contains(a, obj) { for (var i = 0; i &lt; a.length; i++) { if (a[i] === obj) { return true; } } return false; } </code></pre> <p>Is there a better and more concise way to accomplish this?</p> <p>This is very closely related to Stack Overflow question <em><a href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array">Best way to find an item in a JavaScript Array?</a></em> which addresses finding objects in an array using <code>indexOf</code>.</p>
[ { "answer_id": 237142, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": false, "text": "<p>If you are using JavaScript 1.6 or later (Firefox 1.5 or later) you can use <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/indexOf\" rel=\"noreferrer\">Array.indexOf</a>. Otherwise, I think you are going to end up with something similar to your original code.</p>\n" }, { "answer_id": 237148, "author": "cic", "author_id": 4771, "author_profile": "https://Stackoverflow.com/users/4771", "pm_score": 8, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf\" rel=\"noreferrer\"><code>indexOf</code></a> maybe, but it's a \"JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard.\"</p>\n\n<p>Example:</p>\n\n<pre><code>[1, 2, 3].indexOf(1) =&gt; 0\n[\"foo\", \"bar\", \"baz\"].indexOf(\"bar\") =&gt; 1\n[1, 2, 3].indexOf(4) =&gt; -1\n</code></pre>\n\n<p>AFAICS <a href=\"http://msdn.microsoft.com/en-us/library/k4h76zbx%5C%28VS.85%5C%29.aspx\" rel=\"noreferrer\">Microsoft does <em>not</em> offer some kind of alternative</a> to this, but you can add similar functionality to arrays in Internet Explorer (and other browsers that don't support <code>indexOf</code>) if you want to, as a <a href=\"http://google.com/search?q=indexof%20internet%20explorer\" rel=\"noreferrer\">quick Google search reveals</a> (for example, <a href=\"http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/\" rel=\"noreferrer\">this one</a>).</p>\n" }, { "answer_id": 237176, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 9, "selected": false, "text": "<p><strong>Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need the best performance, benchmark for yourself in the relevant execution environments.</strong></p>\n<p>As others have said, the iteration through the array is probably the best way, but it <a href=\"https://web.archive.org/web/20170403221045/https://blogs.oracle.com/greimer/entry/best_way_to_code_a\" rel=\"noreferrer\">has been proven</a> that a decreasing <code>while</code> loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:</p>\n<pre><code>function contains(a, obj) {\n var i = a.length;\n while (i--) {\n if (a[i] === obj) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n<p>Of course, you may as well extend Array prototype:</p>\n<pre><code>Array.prototype.contains = function(obj) {\n var i = this.length;\n while (i--) {\n if (this[i] === obj) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n<p>And now you can simply use the following:</p>\n<pre><code>alert([1, 2, 3].contains(2)); // =&gt; true\nalert([1, 2, 3].contains('2')); // =&gt; false\n</code></pre>\n" }, { "answer_id": 238862, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 6, "selected": false, "text": "<p>Here's a <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/indexOf\" rel=\"noreferrer\">JavaScript 1.6 compatible</a> implementation of <code>Array.indexOf</code>:</p>\n\n<pre><code>if (!Array.indexOf) {\n Array.indexOf = [].indexOf ?\n function(arr, obj, from) {\n return arr.indexOf(obj, from);\n } :\n function(arr, obj, from) { // (for IE6)\n var l = arr.length,\n i = from ? parseInt((1 * from) + (from &lt; 0 ? l : 0), 10) : 0;\n i = i &lt; 0 ? 0 : i;\n for (; i &lt; l; i++) {\n if (i in arr &amp;&amp; arr[i] === obj) {\n return i;\n }\n }\n return -1;\n };\n}\n</code></pre>\n" }, { "answer_id": 1342312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Extending the JavaScript <code>Array</code> object is a really bad idea because you introduce new properties (your custom methods) into <code>for-in</code> loops which can break existing scripts. A few years ago the authors of the <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"noreferrer\">Prototype</a> library had to re-engineer their library implementation to remove just this kind of thing.</p>\n\n<p>If you don't need to worry about compatibility with other JavaScript running on your page, go for it, otherwise, I'd recommend the more awkward, but safer free-standing function solution.</p>\n" }, { "answer_id": 1342459, "author": "Ken", "author_id": 121620, "author_profile": "https://Stackoverflow.com/users/121620", "pm_score": 3, "selected": false, "text": "<p>Here's how <a href=\"http://github.com/sstephenson/prototype/blob/f405b2c510e09b55d08c926a9e1a5c2e2d0a1834/src/lang/array.js#L286-302\" rel=\"noreferrer\">Prototype does it</a>:</p>\n\n<pre><code>/**\n * Array#indexOf(item[, offset = 0]) -&gt; Number\n * - item (?): A value that may or may not be in the array.\n * - offset (Number): The number of initial items to skip before beginning the\n * search.\n *\n * Returns the position of the first occurrence of `item` within the array &amp;mdash; or\n * `-1` if `item` doesn't exist in the array.\n**/\nfunction indexOf(item, i) {\n i || (i = 0);\n var length = this.length;\n if (i &lt; 0) i = length + i;\n for (; i &lt; length; i++)\n if (this[i] === item) return i;\n return -1;\n}\n</code></pre>\n\n<p>Also see <a href=\"http://github.com/sstephenson/prototype/blob/f405b2c510e09b55d08c926a9e1a5c2e2d0a1834/src/lang/array.js#L364-365\" rel=\"noreferrer\">here</a> for how they hook it up.</p>\n" }, { "answer_id": 1473742, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 13, "selected": true, "text": "<p>Modern browsers have <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#browser_compatibility\" rel=\"noreferrer\"><code>Array#includes</code></a>, which does <em>exactly</em> that and <a href=\"https://kangax.github.io/compat-table/es2016plus/#test-Array.prototype.includes\" rel=\"noreferrer\">is widely supported</a> by everyone except IE:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(['joe', 'jane', 'mary'].includes('jane')); //true</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You can also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"noreferrer\"><code>Array#indexOf</code></a>, which is less direct, but doesn't require polyfills for outdated browsers.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(['joe', 'jane', 'mary'].indexOf('jane') &gt;= 0); //true</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<p>Many frameworks also offer similar methods:</p>\n<ul>\n<li>jQuery: <a href=\"https://api.jquery.com/jquery.inarray/\" rel=\"noreferrer\"><code>$.inArray(value, array, [fromIndex])</code></a></li>\n<li>Underscore.js: <a href=\"https://underscorejs.org/#contains\" rel=\"noreferrer\"><code>_.contains(array, value)</code></a> (also aliased as <code>_.include</code> and <code>_.includes</code>)</li>\n<li>Dojo Toolkit: <a href=\"https://dojotoolkit.org/reference-guide/1.10/dojo/indexOf.html\" rel=\"noreferrer\"><code>dojo.indexOf(array, value, [fromIndex, findLast])</code></a></li>\n<li>Prototype: <a href=\"http://api.prototypejs.org/language/Array/prototype/indexOf/\" rel=\"noreferrer\"><code>array.indexOf(value)</code></a></li>\n<li>MooTools: <a href=\"https://mootools.net/core/docs/1.6.0/Types/Array#Array:indexOf\" rel=\"noreferrer\"><code>array.indexOf(value)</code></a></li>\n<li>MochiKit: <a href=\"http://mochi.github.io/mochikit/doc/html/MochiKit/Base.html#fn-findvalue\" rel=\"noreferrer\"><code>findValue(array, value)</code></a></li>\n<li>MS Ajax: <a href=\"https://web.archive.org/web/20140819232945/http://www.asp.net/ajaxlibrary/Reference.Array-indexOf-Function.ashx\" rel=\"noreferrer\"><code>array.indexOf(value)</code></a></li>\n<li>Ext: <a href=\"https://docs.sencha.com/extjs/7.5.1/modern/Ext.Array.html#method-contains\" rel=\"noreferrer\"><code>Ext.Array.contains(array, value)</code></a></li>\n<li>Lodash: <a href=\"https://lodash.com/docs#includes\" rel=\"noreferrer\"><code>_.includes(array, value, [from])</code></a> (is <code>_.contains</code> prior 4.0.0)</li>\n<li>Ramda: <a href=\"https://ramdajs.com/docs/#includes\" rel=\"noreferrer\"><code>R.includes(value, array)</code></a></li>\n</ul>\n<p>Notice that some frameworks implement this as a function, while others add the function to the array prototype.</p>\n" }, { "answer_id": 1953622, "author": "MattMcKnight", "author_id": 8136, "author_profile": "https://Stackoverflow.com/users/8136", "pm_score": 5, "selected": false, "text": "<p>Thinking out of the box for a second, if you are making this call many many times, it is vastly more efficient to use <strike>an associative array</strike> a Map to do lookups using a hash function.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map</a></p>\n" }, { "answer_id": 3406317, "author": "Dennis Allen", "author_id": 214691, "author_profile": "https://Stackoverflow.com/users/214691", "pm_score": -1, "selected": false, "text": "<p>Just another option</p>\n\n<pre><code>// usage: if ( ['a','b','c','d'].contains('b') ) { ... }\nArray.prototype.contains = function(value){\n for (var key in this)\n if (this[key] === value) return true;\n return false;\n}\n</code></pre>\n\n<p>Be careful because overloading javascript array objects with custom methods can disrupt the behavior of other javascripts, causing unexpected behavior.</p>\n" }, { "answer_id": 4908569, "author": "Ztyx", "author_id": 260805, "author_profile": "https://Stackoverflow.com/users/260805", "pm_score": 4, "selected": false, "text": "<p>If you are checking repeatedly for existence of an object in an array you should maybe look into</p>\n\n<ol>\n<li>Keeping the array sorted at all times by doing <a href=\"http://en.wikipedia.org/wiki/Insertion_sort\" rel=\"noreferrer\">insertion sort</a> in your array (put new objects in on the right place) </li>\n<li>Make updating objects as remove+sorted insert operation and</li>\n<li>Use a <a href=\"http://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"noreferrer\">binary search</a> lookup in your <code>contains(a, obj)</code>.</li>\n</ol>\n" }, { "answer_id": 5955215, "author": "Ekim", "author_id": 725589, "author_profile": "https://Stackoverflow.com/users/725589", "pm_score": -1, "selected": false, "text": "<p>Literally:</p>\n<p>(using Firefox v3.6, with <code>for-in</code> caveats as previously noted\n(HOWEVER the use below might endorse <code>for-in</code> for this very purpose! That is, enumerating array elements that ACTUALLY exist via a property index (HOWEVER, in particular, the array <code>length</code> property is NOT enumerated in the <code>for-in</code> property list!).).)</p>\n<p>(Drag &amp; drop the following complete URI's for immediate mode browser testing.)</p>\n<h3>JavaScript:</h3>\n<pre><code> function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}\n\n function check(ra){\n return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')\n }\n alert([\n check([{}]), check([]), check([,2,3]),\n check(['']), '\\t (a null string)', check([,,,])\n ].join('\\n'));\n</code></pre>\n<p>which displays:</p>\n<pre><code>There is an object in [[object Object]].\nThere is NO object in [].\nThere is an object in [,2,3].\nThere is an object in [].\n (a null string)\nThere is NO object in [,,].\n</code></pre>\n<p>Wrinkles: if looking for a &quot;specific&quot; object consider:</p>\n<p>JavaScript: <code>alert({}!={}); alert({}!=={});</code></p>\n<p>And thus:</p>\n<h3>JavaScript:</h3>\n<pre><code> obj = {prop:&quot;value&quot;}; \n ra1 = [obj]; \n ra2 = [{prop:&quot;value&quot;}];\n alert(ra1[0] == obj); \n alert(ra2[0] == obj);\n</code></pre>\n<p>Often <code>ra2</code> is considered to &quot;contain&quot; <code>obj</code> as the literal entity <code>{prop:&quot;value&quot;}</code>.</p>\n<p>A very coarse, rudimentary, naive (as in code needs qualification enhancing) solution:</p>\n<h3>JavaScript:</h3>\n<pre><code> obj={prop:&quot;value&quot;}; ra2=[{prop:&quot;value&quot;}];\n alert(\n ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?\n 'found' :\n 'missing' );\n</code></pre>\n<p>See ref: <em><a href=\"https://stackoverflow.com/questions/3624741/searching-for-objects-in-javascript-arrays/5750179#5750179\">Searching for objects in JavaScript arrays</a></em>.</p>\n" }, { "answer_id": 8758721, "author": "Carlos A", "author_id": 1134413, "author_profile": "https://Stackoverflow.com/users/1134413", "pm_score": 2, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>Array.prototype.contains = function(x){\n var retVal = -1;\n\n // x is a primitive type\n if([\"string\",\"number\"].indexOf(typeof x)&gt;=0 ){ retVal = this.indexOf(x);}\n\n // x is a function\n else if(typeof x ==\"function\") for(var ix in this){\n if((this[ix]+\"\")==(x+\"\")) retVal = ix;\n }\n\n //x is an object...\n else {\n var sx=JSON.stringify(x);\n for(var ix in this){\n if(typeof this[ix] ==\"object\" &amp;&amp; JSON.stringify(this[ix])==sx) retVal = ix;\n }\n }\n\n //Return False if -1 else number if numeric otherwise string\n return (retVal === -1)?false : ( isNaN(+retVal) ? retVal : +retVal);\n}\n</code></pre>\n\n<p>I know it's not the best way to go, but since there is no native IComparable way to interact between objects, I guess this is as close as you can get to compare two entities in an array. Also, extending Array object might not be a wise thing to do, but sometimes it's OK (if you are aware of it and the trade-off).</p>\n" }, { "answer_id": 9849276, "author": "william malo", "author_id": 1145932, "author_profile": "https://Stackoverflow.com/users/1145932", "pm_score": 7, "selected": false, "text": "<p>Let's say you've defined an array like so:</p>\n\n<pre><code>const array = [1, 2, 3, 4]\n</code></pre>\n\n<p>Below are three ways of checking whether there is a <code>3</code> in there. All of them return either <code>true</code> or <code>false</code>.</p>\n\n<h3>Native Array method (since ES2016) (<a href=\"https://caniuse.com/#feat=array-includes\" rel=\"noreferrer\">compatibility table</a>)</h3>\n\n<pre><code>array.includes(3) // true\n</code></pre>\n\n<h3>As custom Array method (pre ES2016)</h3>\n\n<pre><code>// Prefixing the method with '_' to avoid name clashes\nObject.defineProperty(Array.prototype, '_includes', { value: function (v) { return this.indexOf(v) !== -1 }})\narray._includes(3) // true\n</code></pre>\n\n<h3>Simple function</h3>\n\n<pre><code>const includes = (a, v) =&gt; a.indexOf(v) !== -1\nincludes(array, 3) // true\n</code></pre>\n" }, { "answer_id": 10265443, "author": "ninjagecko", "author_id": 711085, "author_profile": "https://Stackoverflow.com/users/711085", "pm_score": 3, "selected": false, "text": "<p>While <code>array.indexOf(x)!=-1</code> is the most concise way to do this (and has been supported by non-Internet&nbsp;Explorer browsers for over decade...), it is not O(1), but rather O(N), which is terrible. If your array will not be changing, you can convert your array to a hashtable, then do <code>table[x]!==undefined</code> or <code>===undefined</code>:</p>\n\n<pre><code>Array.prototype.toTable = function() {\n var t = {};\n this.forEach(function(x){t[x]=true});\n return t;\n}\n</code></pre>\n\n<p>Demo:</p>\n\n<pre><code>var toRemove = [2,4].toTable();\n[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})\n</code></pre>\n\n<p>(Unfortunately, while you can create an Array.prototype.contains to \"freeze\" an array and store a hashtable in this._cache in two lines, this would give wrong results if you chose to edit your array later. JavaScript has insufficient hooks to let you keep this state, unlike Python for example.)</p>\n" }, { "answer_id": 11226279, "author": "Lemex", "author_id": 983969, "author_profile": "https://Stackoverflow.com/users/983969", "pm_score": 4, "selected": false, "text": "<pre><code>function inArray(elem,array)\n{\n var len = array.length;\n for(var i = 0 ; i &lt; len;i++)\n {\n if(array[i] == elem){return i;}\n }\n return -1;\n} \n</code></pre>\n\n<p>Returns array index if found, or -1 if not found</p>\n" }, { "answer_id": 13532998, "author": "Andy Rohr", "author_id": 584171, "author_profile": "https://Stackoverflow.com/users/584171", "pm_score": 2, "selected": false, "text": "<p>Similar thing: Finds the first element by a \"search lambda\":</p>\n\n<pre><code>Array.prototype.find = function(search_lambda) {\n return this[this.map(search_lambda).indexOf(true)];\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>[1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })\n=&gt; 4\n</code></pre>\n\n<p>Same in coffeescript:</p>\n\n<pre><code>Array.prototype.find = (search_lambda) -&gt; @[@map(search_lambda).indexOf(true)]\n</code></pre>\n" }, { "answer_id": 15354149, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 2, "selected": false, "text": "<p>As others have mentioned you can use <code>Array.indexOf</code>, but it isn't available in all browsers. Here's the code from <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf</a> to make it work the same in older browsers.</p>\n\n<blockquote>\n <p>indexOf is a recent addition to the ECMA-262 standard; as such it may\n not be present in all browsers. You can work around this by inserting\n the following code at the beginning of your scripts, allowing use of\n indexOf in implementations which do not natively support it. This\n algorithm is exactly the one specified in ECMA-262, 5th edition,\n assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.max\n have their original value.</p>\n</blockquote>\n\n<pre><code>if (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {\n \"use strict\";\n if (this == null) {\n throw new TypeError();\n }\n var t = Object(this);\n var len = t.length &gt;&gt;&gt; 0;\n if (len === 0) {\n return -1;\n }\n var n = 0;\n if (arguments.length &gt; 1) {\n n = Number(arguments[1]);\n if (n != n) { // shortcut for verifying if it's NaN\n n = 0;\n } else if (n != 0 &amp;&amp; n != Infinity &amp;&amp; n != -Infinity) {\n n = (n &gt; 0 || -1) * Math.floor(Math.abs(n));\n }\n }\n if (n &gt;= len) {\n return -1;\n }\n var k = n &gt;= 0 ? n : Math.max(len - Math.abs(n), 0);\n for (; k &lt; len; k++) {\n if (k in t &amp;&amp; t[k] === searchElement) {\n return k;\n }\n }\n return -1;\n }\n}\n</code></pre>\n" }, { "answer_id": 17453323, "author": "stamat", "author_id": 1909864, "author_profile": "https://Stackoverflow.com/users/1909864", "pm_score": 2, "selected": false, "text": "<p>I looked through submitted answers and got that they only apply if you search for the object via reference. A simple linear search with reference object comparison. </p>\n\n<p>But lets say you don't have the reference to an object, how will you find the correct object in the array? You will have to go linearly and deep compare with each object. Imagine if the list is too large, and the objects in it are very big containing big pieces of text. The performance drops drastically with the number and size of the elements in the array.</p>\n\n<p>You can stringify objects and put them in the native hash table, but then you will have data redundancy remembering these keys cause JavaScript keeps them for 'for i in obj', and you only want to check if the object exists or not, that is, you have the key.</p>\n\n<p>I thought about this for some time constructing a JSON Schema validator, and I devised a simple wrapper for the native hash table, similar to the sole hash table implementation, with some optimization exceptions which I left to the native hash table to deal with. It only needs performance benchmarking...\nAll the details and code can be found on my blog: <a href=\"http://stamat.wordpress.com/javascript-quickly-find-very-large-objects-in-a-large-array/\" rel=\"nofollow\">http://stamat.wordpress.com/javascript-quickly-find-very-large-objects-in-a-large-array/</a>\nI will soon post benchmark results. </p>\n\n<p>The complete solution works like this:</p>\n\n<pre><code>var a = {'a':1,\n 'b':{'c':[1,2,[3,45],4,5],\n 'd':{'q':1, 'b':{'q':1, 'b':8},'c':4},\n 'u':'lol'},\n 'e':2};\n\n var b = {'a':1, \n 'b':{'c':[2,3,[1]],\n 'd':{'q':3,'b':{'b':3}}},\n 'e':2};\n\n var c = \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\";\n\n var hc = new HashCache([{a:3, b:2, c:5}, {a:15, b:2, c:'foo'}]); //init\n\n hc.put({a:1, b:1});\n hc.put({b:1, a:1});\n hc.put(true);\n hc.put('true');\n hc.put(a);\n hc.put(c);\n hc.put(d);\n console.log(hc.exists('true'));\n console.log(hc.exists(a));\n console.log(hc.exists(c));\n console.log(hc.exists({b:1, a:1}));\n hc.remove(a);\n console.log(hc.exists(c));\n</code></pre>\n" }, { "answer_id": 18792061, "author": "Matías Cánepa", "author_id": 702353, "author_profile": "https://Stackoverflow.com/users/702353", "pm_score": 6, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>function isInArray(array, search)\n{\n return array.indexOf(search) &gt;= 0;\n}\n\n// Usage\nif(isInArray(my_array, \"my_value\"))\n{\n //...\n}\n</code></pre>\n" }, { "answer_id": 19208820, "author": "Mina Gabriel", "author_id": 1410185, "author_profile": "https://Stackoverflow.com/users/1410185", "pm_score": 3, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>var myArray = ['yellow', 'orange', 'red'] ;\n\nalert(!!~myArray.indexOf('red')); //true\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/An5jQ/\" rel=\"noreferrer\">Demo</a></p>\n\n<p>To know exactly what the <code>tilde</code> <code>~</code> do at this point, refer to this question <em><a href=\"https://stackoverflow.com/questions/12299665/what-does-a-tilde-do-when-it-precedes-an-expression\">What does a tilde do when it precedes an expression?</a></em>.</p>\n" }, { "answer_id": 23938696, "author": "Pradeep Mahdevu", "author_id": 572100, "author_profile": "https://Stackoverflow.com/users/572100", "pm_score": 3, "selected": false, "text": "<p>ECMAScript 6 has an elegant proposal on find.</p>\n\n<blockquote>\n <p>The find method executes the callback function once for each element\n present in the array until it finds one where callback returns a true\n value. If such an element is found, find immediately returns the value\n of that element. Otherwise, find returns undefined. callback is\n invoked only for indexes of the array which have assigned values; it\n is not invoked for indexes which have been deleted or which have never\n been assigned values.</p>\n</blockquote>\n\n<p>Here is the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"noreferrer\">MDN documentation</a> on that.</p>\n\n<p>The find functionality works like this.</p>\n\n<pre><code>function isPrime(element, index, array) {\n var start = 2;\n while (start &lt;= Math.sqrt(element)) {\n if (element % start++ &lt; 1) return false;\n }\n return (element &gt; 1);\n}\n\nconsole.log( [4, 6, 8, 12].find(isPrime) ); // Undefined, not found\nconsole.log( [4, 5, 8, 12].find(isPrime) ); // 5\n</code></pre>\n\n<p>You can use this in ECMAScript 5 and below by <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill\" rel=\"noreferrer\">defining the function</a>.</p>\n\n<pre><code>if (!Array.prototype.find) {\n Object.defineProperty(Array.prototype, 'find', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function(predicate) {\n if (this == null) {\n throw new TypeError('Array.prototype.find called on null or undefined');\n }\n if (typeof predicate !== 'function') {\n throw new TypeError('predicate must be a function');\n }\n var list = Object(this);\n var length = list.length &gt;&gt;&gt; 0;\n var thisArg = arguments[1];\n var value;\n\n for (var i = 0; i &lt; length; i++) {\n if (i in list) {\n value = list[i];\n if (predicate.call(thisArg, value, i, list)) {\n return value;\n }\n }\n }\n return undefined;\n }\n });\n}\n</code></pre>\n" }, { "answer_id": 24225731, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 5, "selected": false, "text": "<p>I use the following:</p>\n\n<pre><code>Array.prototype.contains = function (v) {\n return this.indexOf(v) &gt; -1;\n}\n\nvar a = [ 'foo', 'bar' ];\n\na.contains('foo'); // true\na.contains('fox'); // false\n</code></pre>\n" }, { "answer_id": 24827594, "author": "Michael", "author_id": 599912, "author_profile": "https://Stackoverflow.com/users/599912", "pm_score": 8, "selected": false, "text": "<p>The top answers assume primitive types but if you want to find out if an array contains an <strong>object</strong> with some trait, <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"noreferrer\">Array.prototype.some()</a> is an elegant solution:</p>\n<pre><code>const items = [ {a: '1'}, {a: '2'}, {a: '3'} ]\n\nitems.some(item =&gt; item.a === '3') // returns true\nitems.some(item =&gt; item.a === '4') // returns false\n</code></pre>\n<p>The nice thing about it is that the iteration is aborted once the element is found so unnecessary iteration cycles are spared.</p>\n<p>Also, it fits nicely in an <code>if</code> statement since it returns a boolean:</p>\n<pre><code>if (items.some(item =&gt; item.a === '3')) {\n // do something\n}\n</code></pre>\n<p>* As jamess pointed out in the comment, at the time of this answer, September 2018, <code>Array.prototype.some()</code> is fully supported: <a href=\"http://kangax.github.io/compat-table/es5/#test-Array_methods_Array.prototype.some_a_href=_https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some_title=_MDN_documentation_img_src=_../mdn.png_alt=_MDN_(Mozilla_Development_Network)_logo_width=_15_height=_13_/_/a_nbsp;\" rel=\"noreferrer\">caniuse.com support table</a></p>\n" }, { "answer_id": 25765186, "author": "dr.dimitru", "author_id": 1320932, "author_profile": "https://Stackoverflow.com/users/1320932", "pm_score": 4, "selected": false, "text": "<p>We use this snippet (works with objects, arrays, strings):</p>\n\n<pre><code>/*\n * @function\n * @name Object.prototype.inArray\n * @description Extend Object prototype within inArray function\n *\n * @param {mix} needle - Search-able needle\n * @param {bool} searchInKey - Search needle in keys?\n *\n */\nObject.defineProperty(Object.prototype, 'inArray',{\n value: function(needle, searchInKey){\n\n var object = this;\n\n if( Object.prototype.toString.call(needle) === '[object Object]' || \n Object.prototype.toString.call(needle) === '[object Array]'){\n needle = JSON.stringify(needle);\n }\n\n return Object.keys(object).some(function(key){\n\n var value = object[key];\n\n if( Object.prototype.toString.call(value) === '[object Object]' || \n Object.prototype.toString.call(value) === '[object Array]'){\n value = JSON.stringify(value);\n }\n\n if(searchInKey){\n if(value === needle || key === needle){\n return true;\n }\n }else{\n if(value === needle){\n return true;\n }\n }\n });\n },\n writable: true,\n configurable: true,\n enumerable: false\n});\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>var a = {one: \"first\", two: \"second\", foo: {three: \"third\"}};\na.inArray(\"first\"); //true\na.inArray(\"foo\"); //false\na.inArray(\"foo\", true); //true - search by keys\na.inArray({three: \"third\"}); //true\n\nvar b = [\"one\", \"two\", \"three\", \"four\", {foo: 'val'}];\nb.inArray(\"one\"); //true\nb.inArray('foo'); //false\nb.inArray({foo: 'val'}) //true\nb.inArray(\"{foo: 'val'}\") //false\n\nvar c = \"String\";\nc.inArray(\"S\"); //true\nc.inArray(\"s\"); //false\nc.inArray(\"2\", true); //true\nc.inArray(\"20\", true); //false\n</code></pre>\n" }, { "answer_id": 25813188, "author": "dansalmo", "author_id": 1355221, "author_profile": "https://Stackoverflow.com/users/1355221", "pm_score": 5, "selected": false, "text": "<pre><code>function contains(a, obj) {\n return a.some(function(element){return element == obj;})\n}\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\">Array.prototype.some()</a> was added to the ECMA-262 standard in the 5th edition</p>\n" }, { "answer_id": 27727752, "author": "Oriol", "author_id": 1529630, "author_profile": "https://Stackoverflow.com/users/1529630", "pm_score": 8, "selected": false, "text": "<p>ECMAScript 7 introduces <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"noreferrer\"><code>Array.prototype.includes</code></a>.</p>\n<p>It can be used like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>[1, 2, 3].includes(2); // true\n[1, 2, 3].includes(4); // false\n</code></pre>\n<p>It also accepts an optional second argument <code>fromIndex</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>[1, 2, 3].includes(3, 3); // false\n[1, 2, 3].includes(3, -1); // true\n</code></pre>\n<p>Unlike <code>indexOf</code>, which uses <a href=\"https://262.ecma-international.org/12.0/#sec-strict-equality-comparison\" rel=\"noreferrer\">Strict Equality Comparison</a>, <code>includes</code> compares using <a href=\"https://262.ecma-international.org/12.0/#sec-samevaluezero\" rel=\"noreferrer\">SameValueZero</a> equality algorithm. That means that you can detect if an array includes a <code>NaN</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>[1, 2, NaN].includes(NaN); // true\n</code></pre>\n<p>Also unlike <code>indexOf</code>, <code>includes</code> does not skip missing indices:</p>\n<pre class=\"lang-js prettyprint-override\"><code>new Array(5).includes(undefined); // true\n</code></pre>\n<p>It can be <a href=\"https://github.com/zloirock/core-js#ecmascript-array\" rel=\"noreferrer\">polyfilled</a> to make it work on all browsers.</p>\n" }, { "answer_id": 27819913, "author": "AlonL", "author_id": 1563935, "author_profile": "https://Stackoverflow.com/users/1563935", "pm_score": 5, "selected": false, "text": "<p>One-liner:</p>\n\n<pre><code>function contains(arr, x) {\n return arr.filter(function(elem) { return elem == x }).length &gt; 0;\n}\n</code></pre>\n" }, { "answer_id": 30335438, "author": "cocco", "author_id": 2450730, "author_profile": "https://Stackoverflow.com/users/2450730", "pm_score": 4, "selected": false, "text": "<p><strong>A hopefully faster bidirectional <code>indexOf</code> / <code>lastIndexOf</code> alternative</strong></p>\n<h2>2015</h2>\n<p>While the new method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\"><code>includes</code></a> is very nice, the support is basically zero for now.</p>\n<p>It's a long time that I was thinking of a way to replace the slow <code>indexOf</code>/<code>lastIndexOf</code> functions.</p>\n<p>A performant way has already been found, looking at the top answers. From those I chose the <code>contains</code> function posted by @Damir Zekic which should be the fastest one. But it also states that the benchmarks are from 2008 and so are outdated.</p>\n<p>I also prefer <code>while</code> over <code>for</code>, but for not a specific reason I ended writing the function with a for loop. It could be also done with a <code>while --</code>.</p>\n<p>I was curious if the iteration was much slower if I check both sides of the array while doing it. Apparently no, and so this function is around two times faster than the top voted ones. Obviously it's also faster than the native one. This is in a real world environment, where you never know if the value you are searching is at the beginning or at the end of the array.</p>\n<p>When you know you just pushed an array with a value, using lastIndexOf remains probably the best solution, but if you have to travel through big arrays and the result could be everywhere, this could be a solid solution to make things faster.</p>\n<p><strong>Bidirectional <code>indexOf</code>/<code>lastIndexOf</code></strong></p>\n<pre><code>function bidirectionalIndexOf(a, b, c, d, e){\n for(c=a.length,d=c*1; c--; ){\n if(a[c]==b) return c; //or this[c]===b\n if(a[e=d-1-c]==b) return e; //or a[e=d-1-c]===b\n }\n return -1\n}\n\n//Usage\nbidirectionalIndexOf(array,'value');\n</code></pre>\n<h3>Performance test</h3>\n<p><a href=\"https://jsbench.me/7el1b8dj80\" rel=\"nofollow noreferrer\">https://jsbench.me/7el1b8dj80</a></p>\n<p>As a test I created an array with 100k entries.</p>\n<p>Three queries: at the beginning, in the middle &amp; at the end of the array.</p>\n<p>I hope you also find this interesting and test the performance.</p>\n<p>Note: As you can see I slightly modified the <code>contains</code> function to reflect the <code>indexOf</code> &amp; <code>lastIndexOf</code> output (so basically <code>true</code> with the <code>index</code> and <code>false</code> with <code>-1</code>). That shouldn't harm it.</p>\n<h3>The array prototype variant</h3>\n<pre><code>Object.defineProperty(Array.prototype,'bidirectionalIndexOf',{value:function(b,c,d,e){\n for(c=this.length,d=c*1; c--; ){\n if(this[c]==b) return c; //or this[c]===b\n if(this[e=d-1-c] == b) return e; //or this[e=d-1-c]===b\n }\n return -1\n},writable:false, enumerable:false});\n\n// Usage\narray.bidirectionalIndexOf('value');\n</code></pre>\n<p>The function can also be easily modified to return true or false or even the object, string or whatever it is.</p>\n<p>And here is the <code>while</code> variant:</p>\n<pre><code>function bidirectionalIndexOf(a, b, c, d){\n c=a.length; d=c-1;\n while(c--){\n if(b===a[c]) return c;\n if(b===a[d-c]) return d-c;\n }\n return c\n}\n\n// Usage\nbidirectionalIndexOf(array,'value');\n</code></pre>\n<h3>How is this possible?</h3>\n<p>I think that the simple calculation to get the reflected index in an array is so simple that it's two times faster than doing an actual loop iteration.</p>\n<p>Here is a complex example doing three checks per iteration, but this is only possible with a longer calculation which causes the slowdown of the code.</p>\n<p><a href=\"https://web.archive.org/web/20151019160219/http://jsperf.com/bidirectionalindexof/2\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20151019160219/http://jsperf.com/bidirectionalindexof/2</a></p>\n" }, { "answer_id": 33257515, "author": "l3x", "author_id": 1978383, "author_profile": "https://Stackoverflow.com/users/1978383", "pm_score": 4, "selected": false, "text": "<p>Use lodash's <a href=\"https://lodash.com/docs#some\" rel=\"noreferrer\">some</a> function.</p>\n\n<p>It's concise, accurate and has great cross platform support.</p>\n\n<p>The accepted answer does not even meet the requirements.</p>\n\n<p><em>Requirements:</em> Recommend most concise and efficient way to find out if a JavaScript array contains an object.</p>\n\n<p><strong>Accepted Answer:</strong></p>\n\n<pre><code>$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])\n&gt; -1\n</code></pre>\n\n<p><strong>My recommendation:</strong></p>\n\n<pre><code>_.some([{'a': 1}, {'b': 2}], {'b': 2})\n&gt; true\n</code></pre>\n\n<p>Notes: </p>\n\n<p>$.inArray works fine for determining whether a <em>scalar</em> value exists in an array of scalars...</p>\n\n<pre><code>$.inArray(2, [1,2])\n&gt; 1\n</code></pre>\n\n<p>... but the question clearly asks for an efficient way to determine if an <em>object</em> is contained in an array.</p>\n\n<p>In order to handle both scalars and objects, you could do this:</p>\n\n<pre><code>(_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) &gt; -1)\n</code></pre>\n" }, { "answer_id": 33735369, "author": "rlib", "author_id": 1477299, "author_profile": "https://Stackoverflow.com/users/1477299", "pm_score": 3, "selected": false, "text": "<p>One can use <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"noreferrer\">Set</a> that has the method \"has()\":</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function contains(arr, obj) {\r\n var proxy = new Set(arr);\r\n if (proxy.has(obj))\r\n return true;\r\n else\r\n return false;\r\n }\r\n\r\n var arr = ['Happy', 'New', 'Year'];\r\n console.log(contains(arr, 'Happy'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 34690541, "author": "sqram", "author_id": 93026, "author_profile": "https://Stackoverflow.com/users/93026", "pm_score": 3, "selected": false, "text": "<p>By no means the best, but I was just getting creative and adding to the repertoire.</p>\n<h3>Do not use this</h3>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Object.defineProperty(Array.prototype, 'exists', {\n value: function(element, index) {\n\n var index = index || 0\n\n return index === this.length ? -1 : this[index] === element ? index : this.exists(element, ++index)\n }\n})\n\n\n// Outputs 1\nconsole.log(['one', 'two'].exists('two'));\n\n// Outputs -1\nconsole.log(['one', 'two'].exists('three'));\n\nconsole.log(['one', 'two', 'three', 'four'].exists('four'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 34704195, "author": "user2724028", "author_id": 2724028, "author_profile": "https://Stackoverflow.com/users/2724028", "pm_score": 3, "selected": false, "text": "<p>You can also use this trick:</p>\n\n<pre><code>var arrayContains = function(object) {\n return (serverList.filter(function(currentObject) {\n if (currentObject === object) {\n return currentObject\n }\n else {\n return false;\n }\n }).length &gt; 0) ? true : false\n}\n</code></pre>\n" }, { "answer_id": 41841362, "author": "Igor Barbashin", "author_id": 283803, "author_profile": "https://Stackoverflow.com/users/283803", "pm_score": 4, "selected": false, "text": "<p>Solution that works in all modern browsers:</p>\n\n<pre><code>function contains(arr, obj) {\n const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration\n return arr.some(item =&gt; JSON.stringify(item) === stringifiedObj);\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>contains([{a: 1}, {a: 2}], {a: 1}); // true\n</code></pre>\n\n<p>IE6+ solution:</p>\n\n<pre><code>function contains(arr, obj) {\n var stringifiedObj = JSON.stringify(obj)\n return arr.some(function (item) {\n return JSON.stringify(item) === stringifiedObj;\n });\n}\n\n// .some polyfill, not needed for IE9+\nif (!('some' in Array.prototype)) {\n Array.prototype.some = function (tester, that /*opt*/) {\n for (var i = 0, n = this.length; i &lt; n; i++) {\n if (i in this &amp;&amp; tester.call(that, this[i], i, this)) return true;\n } return false;\n };\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>contains([{a: 1}, {a: 2}], {a: 1}); // true\n</code></pre>\n\n<h1>Why to use <code>JSON.stringify</code>?</h1>\n\n<p><code>Array.indexOf</code> and <code>Array.includes</code> (as well as most of the answers here) only compare by reference and not by value.</p>\n\n<pre><code>[{a: 1}, {a: 2}].includes({a: 1});\n// false, because {a: 1} is a new object\n</code></pre>\n\n<h1>Bonus</h1>\n\n<p>Non-optimized ES6 one-liner:</p>\n\n<pre><code>[{a: 1}, {a: 2}].some(item =&gt; JSON.stringify(item) === JSON.stringify({a: 1));\n// true\n</code></pre>\n\n<hr>\n\n<p>Note:\nComparing objects by value will work better if the keys are in the same order, so to be safe you might sort the keys first with a package like this one: <a href=\"https://www.npmjs.com/package/sort-keys\" rel=\"noreferrer\">https://www.npmjs.com/package/sort-keys</a></p>\n\n<hr>\n\n<p>Updated the <code>contains</code> function with a perf optimization. Thanks <a href=\"https://stackoverflow.com/users/1397160/itinance\">itinance</a> for pointing it out.</p>\n" }, { "answer_id": 44620847, "author": "Maxime Helen", "author_id": 2647671, "author_profile": "https://Stackoverflow.com/users/2647671", "pm_score": 2, "selected": false, "text": "<p>Or this solution:</p>\n\n<pre><code>Array.prototype.includes = function (object) {\n return !!+~this.indexOf(object);\n};\n</code></pre>\n" }, { "answer_id": 44870333, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 3, "selected": false, "text": "<p>OK, you can just <strong>optimise your</strong> code to get the result! </p>\n\n<p>There are many ways to do this which are cleaner and better, but I just wanted to get your pattern and apply to that using <code>JSON.stringify</code>, just simply do something like this in your case:</p>\n\n<pre><code>function contains(a, obj) {\n for (var i = 0; i &lt; a.length; i++) {\n if (JSON.stringify(a[i]) === JSON.stringify(obj)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n" }, { "answer_id": 45460232, "author": "KRRySS", "author_id": 2023542, "author_profile": "https://Stackoverflow.com/users/2023542", "pm_score": 2, "selected": false, "text": "<p>Using idnexOf() it is a good solution, but you should hide embedded implementation indexOf() function which returns -1 with ~ operator: </p>\n\n<pre><code>function include(arr,obj) { \n return !!(~arr.indexOf(obj)); \n} \n</code></pre>\n" }, { "answer_id": 45748512, "author": "Krishna Ganeriwal", "author_id": 6167785, "author_profile": "https://Stackoverflow.com/users/6167785", "pm_score": 3, "selected": false, "text": "<ol>\n<li>Either use <code>Array.indexOf(Object)</code>. </li>\n<li>With ECMA 7 one can use the <code>Array.includes(Object)</code>. </li>\n<li><p>With ECMA 6 you can use <code>Array.find(FunctionName)</code> where <code>FunctionName</code> is a user \ndefined function to search for the object in the array.</p>\n\n<p>Hope this helps!</p></li>\n</ol>\n" }, { "answer_id": 46047077, "author": "Jeeva", "author_id": 4737293, "author_profile": "https://Stackoverflow.com/users/4737293", "pm_score": 2, "selected": false, "text": "<p>I was working on a project that I needed a functionality like python <code>set</code> which removes all duplicates values and returns a new list, so I wrote this function maybe useful to someone</p>\n\n<pre><code>function set(arr) {\n var res = [];\n for (var i = 0; i &lt; arr.length; i++) {\n if (res.indexOf(arr[i]) === -1) {\n res.push(arr[i]);\n }\n }\n return res;\n}\n</code></pre>\n" }, { "answer_id": 47652283, "author": "Mitul Panchal", "author_id": 4002757, "author_profile": "https://Stackoverflow.com/users/4002757", "pm_score": 3, "selected": false, "text": "<p>It has one parameter: an array numbers of objects. Each object in the array has two integer properties denoted by x and y. The function must return a count of all such objects in the array that satisfy <code>numbers.x == numbers.y</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var numbers = [ { x: 1, y: 1 },\r\n { x: 2, y: 3 },\r\n { x: 3, y: 3 },\r\n { x: 3, y: 4 },\r\n { x: 4, y: 5 } ];\r\nvar count = 0; \r\nvar n = numbers.length;\r\nfor (var i =0;i&lt;n;i++)\r\n{\r\n if(numbers[i].x==numbers[i].y)\r\n {count+=1;}\r\n}\r\n\r\nalert(count);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 48435485, "author": "Neil Girardi", "author_id": 1500241, "author_profile": "https://Stackoverflow.com/users/1500241", "pm_score": 2, "selected": false, "text": "<p>If you're working with ES6 You can use a set:</p>\n\n<pre><code>function arrayHas( array, element ) {\n const s = new Set(array);\n return s.has(element)\n}\n</code></pre>\n\n<p>This should be more performant than just about any other method</p>\n" }, { "answer_id": 51040131, "author": "Durgpal Singh", "author_id": 1759015, "author_profile": "https://Stackoverflow.com/users/1759015", "pm_score": 2, "selected": false, "text": "<p>I recommended to use underscore library because its return the value and its supported for all browsers. </p>\n\n<p><a href=\"https://underscorejs.org/\" rel=\"nofollow noreferrer\">underscorejs</a></p>\n\n<pre><code> var findValue = _.find(array, function(item) {\n return item.id == obj.id;\n });\n</code></pre>\n" }, { "answer_id": 52735194, "author": "Shashwat Gupta", "author_id": 7765900, "author_profile": "https://Stackoverflow.com/users/7765900", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Simple solution : ES6 Features \"<strong>includes</strong>\" method</p>\n</blockquote>\n\n<pre><code>let arr = [1, 2, 3, 2, 3, 2, 3, 4];\n\n arr.includes(2) // true\n\n arr.includes(93) // false\n</code></pre>\n" }, { "answer_id": 53050132, "author": "Nitesh Ranjan", "author_id": 9095122, "author_profile": "https://Stackoverflow.com/users/9095122", "pm_score": 2, "selected": false, "text": "<p>In Addition to what others said, if you don't have a reference of the object which you want to search in the array, then you can do something like this.</p>\n\n<pre><code>let array = [1, 2, 3, 4, {\"key\": \"value\"}];\n\narray.some((element) =&gt; JSON.stringify(element) === JSON.stringify({\"key\": \"value\"})) // true\n\narray.some((element) =&gt; JSON.stringify(element) === JSON.stringify({})) // true\n</code></pre>\n\n<p>Array.some returns true if any element matches the given condition and returns false if none of the elements matches the given condition.</p>\n" }, { "answer_id": 53791481, "author": "Sanjay Magar", "author_id": 8376818, "author_profile": "https://Stackoverflow.com/users/8376818", "pm_score": 3, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> function countArray(originalArray) {\r\n \r\n var compressed = [];\r\n // make a copy of the input array\r\n var copyArray = originalArray.slice(0);\r\n \r\n // first loop goes over every element\r\n for (var i = 0; i &lt; originalArray.length; i++) {\r\n \r\n var count = 0; \r\n // loop over every element in the copy and see if it's the same\r\n for (var w = 0; w &lt; copyArray.length; w++) {\r\n if (originalArray[i] == copyArray[w]) {\r\n // increase amount of times duplicate is found\r\n count++;\r\n // sets item to undefined\r\n delete copyArray[w];\r\n }\r\n }\r\n \r\n if (count &gt; 0) {\r\n var a = new Object();\r\n a.value = originalArray[i];\r\n a.count = count;\r\n compressed.push(a);\r\n }\r\n }\r\n \r\n return compressed;\r\n };\r\n \r\n // It should go something like this:\r\n \r\n var testArray = new Array(\"dog\", \"dog\", \"cat\", \"buffalo\", \"wolf\", \"cat\", \"tiger\", \"cat\");\r\n var newArray = countArray(testArray);\r\n console.log(newArray);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 55559625, "author": "Sumer", "author_id": 6696684, "author_profile": "https://Stackoverflow.com/users/6696684", "pm_score": 3, "selected": false, "text": "<p>Surprised that this question still doesn't have latest syntax added, adding my 2 cents.</p>\n\n<p>Let's say we have array of Objects arrObj and we want to search obj in it.</p>\n\n<p>Array.prototype.<strong>indexOf</strong> -> (returns <strong>index or -1</strong>) is generally used for finding index of element in array.\nThis can also be used for searching object but only works if you are passing reference to same object.</p>\n\n<pre><code>let obj = { name: 'Sumer', age: 36 };\nlet arrObj = [obj, { name: 'Kishor', age: 46 }, { name: 'Rupen', age: 26 }];\n\n\nconsole.log(arrObj.indexOf(obj));// 0\nconsole.log(arrObj.indexOf({ name: 'Sumer', age: 36 })); //-1\n\nconsole.log([1, 3, 5, 2].indexOf(2)); //3\n</code></pre>\n\n<p>Array.prototype.<strong>includes</strong> -> (returns <strong>true</strong> or <strong>false</strong>)</p>\n\n<pre><code>console.log(arrObj.includes(obj)); //true\nconsole.log(arrObj.includes({ name: 'Sumer', age: 36 })); //false\n\nconsole.log([1, 3, 5, 2].includes(2)); //true\n</code></pre>\n\n<p>Array.prototype.<strong>find</strong> -> (takes callback, returns first <strong>value/object</strong> that returns true in CB).</p>\n\n<pre><code>console.log(arrObj.find(e =&gt; e.age &gt; 40)); //{ name: 'Kishor', age: 46 }\nconsole.log(arrObj.find(e =&gt; e.age &gt; 40)); //{ name: 'Kishor', age: 46 }\n\nconsole.log([1, 3, 5, 2].find(e =&gt; e &gt; 2)); //3\n</code></pre>\n\n<p>Array.prototype.<strong>findIndex</strong> -> (takes callback, returns <strong>index</strong> of first value/object that returns true in CB).</p>\n\n<pre><code>console.log(arrObj.findIndex(e =&gt; e.age &gt; 40)); //1\nconsole.log(arrObj.findIndex(e =&gt; e.age &gt; 40)); //1\n\nconsole.log([1, 3, 5, 2].findIndex(e =&gt; e &gt; 2)); //1\n</code></pre>\n\n<p>Since find and findIndex takes a callback, we can be fetch any object(even if we don't have the reference) from array by creatively setting the true condition.</p>\n" }, { "answer_id": 58346110, "author": "Shiva", "author_id": 6404433, "author_profile": "https://Stackoverflow.com/users/6404433", "pm_score": 4, "selected": false, "text": "<p>Simple solution for this requirement is using <code>find()</code></p>\n<p>If you're having array of objects like below,</p>\n<pre><code>var users = [{id: &quot;101&quot;, name: &quot;Choose one...&quot;},\n{id: &quot;102&quot;, name: &quot;shilpa&quot;},\n{id: &quot;103&quot;, name: &quot;anita&quot;},\n{id: &quot;104&quot;, name: &quot;admin&quot;},\n{id: &quot;105&quot;, name: &quot;user&quot;}];\n</code></pre>\n<p>Then you can check whether the object with your value is already present or not:</p>\n<pre><code>let data = users.find(object =&gt; object['id'] === '104');\n</code></pre>\n<p>if data is null then no admin, else it will return the existing object like:</p>\n<pre><code>{id: &quot;104&quot;, name: &quot;admin&quot;}\n</code></pre>\n<p>Then you can find the index of that object in the array and replace the object using the code:</p>\n<pre><code>let indexToUpdate = users.indexOf(data);\nlet newObject = {id: &quot;104&quot;, name: &quot;customer&quot;};\nusers[indexToUpdate] = newObject;//your new object\nconsole.log(users);\n</code></pre>\n<p>you will get value like:</p>\n<pre><code>[{id: &quot;101&quot;, name: &quot;Choose one...&quot;},\n{id: &quot;102&quot;, name: &quot;shilpa&quot;},\n{id: &quot;103&quot;, name: &quot;anita&quot;},\n{id: &quot;104&quot;, name: &quot;customer&quot;},\n{id: &quot;105&quot;, name: &quot;user&quot;}];\n</code></pre>\n" }, { "answer_id": 59627901, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 5, "selected": false, "text": "<h2>Performance</h2>\n\n<p>Today 2020.01.07 I perform tests on MacOs HighSierra 10.13.6 on Chrome v78.0.0, Safari v13.0.4 and Firefox v71.0.0 for 15 chosen solutions. Conclusions</p>\n\n<ul>\n<li>solutions based on <code>JSON</code>, <code>Set</code> and surprisingly <code>find</code> (K,N,O) are slowest on all browsers</li>\n<li>the es6 <code>includes</code> (F) is fast only on chrome</li>\n<li>the solutions based on <code>for</code> (C,D) and <code>indexOf</code> (G,H) are quite-fast on all browsers on small and big arrays so probably they are best choice for efficient solution</li>\n<li>the solutions where index decrease during loop, (B) is slower probably because the way of <a href=\"https://stackoverflow.com/questions/1950878/c-for-loop-indexing-is-forward-indexing-faster-in-new-cpus\">CPU cache works</a>. </li>\n<li>I also run test for big array when searched element was on position 66% of array length, and solutions based on <code>for</code> (C,D,E) gives similar results (~630 ops/sec - but the E on safari and firefox was 10-20% slower than C and D)</li>\n</ul>\n\n<h2>Results</h2>\n\n<p><a href=\"https://i.stack.imgur.com/YPIG1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/YPIG1.png\" alt=\"enter image description here\"></a></p>\n\n<h2>Details</h2>\n\n<p>I perform 2 tests cases: for array with 10 elements, and array with 1 milion elements. In both cases we put searched element in the array middle.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let log = (name,f) =&gt; console.log(`${name}: 3-${f(arr,'s10')} 's7'-${f(arr,'s7')} 6-${f(arr,6)} 's3'-${f(arr,'s3')}`)\r\n\r\nlet arr = [1,2,3,4,5,'s6','s7','s8','s9','s10'];\r\n//arr = new Array(1000000).fill(123); arr[500000]=7;\r\n\r\nfunction A(a, val) {\r\n var i = -1;\r\n var n = a.length;\r\n while (i++&lt;n) {\r\n if (a[i] === val) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n\r\nfunction B(a, val) {\r\n var i = a.length;\r\n while (i--) {\r\n if (a[i] === val) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n\r\nfunction C(a, val) {\r\n for (var i = 0; i &lt; a.length; i++) {\r\n if (a[i] === val) return true;\r\n }\r\n return false;\r\n}\r\n\r\nfunction D(a,val)\r\n{\r\n var len = a.length;\r\n for(var i = 0 ; i &lt; len;i++)\r\n {\r\n if(a[i] === val) return true;\r\n }\r\n return false;\r\n} \r\n\r\nfunction E(a, val){ \r\n var n = a.length-1;\r\n var t = n/2;\r\n for (var i = 0; i &lt;= t; i++) {\r\n if (a[i] === val || a[n-i] === val) return true;\r\n }\r\n return false;\r\n}\r\n\r\nfunction F(a,val) {\r\n return a.includes(val);\r\n}\r\n\r\nfunction G(a,val) {\r\n return a.indexOf(val)&gt;=0;\r\n}\r\n\r\nfunction H(a,val) {\r\n return !!~a.indexOf(val);\r\n}\r\n\r\nfunction I(a, val) {\r\n return a.findIndex(x=&gt; x==val)&gt;=0;\r\n}\r\n\r\nfunction J(a,val) {\r\n return a.some(x=&gt; x===val);\r\n}\r\n\r\nfunction K(a, val) {\r\n const s = JSON.stringify(val);\r\n return a.some(x =&gt; JSON.stringify(x) === s);\r\n}\r\n\r\nfunction L(a,val) {\r\n return !a.every(x=&gt; x!==val);\r\n}\r\n\r\nfunction M(a, val) {\r\n return !!a.find(x=&gt; x==val);\r\n}\r\n\r\nfunction N(a,val) {\r\n return a.filter(x=&gt;x===val).length &gt; 0;\r\n}\r\n\r\nfunction O(a, val) {\r\n return new Set(a).has(val);\r\n}\r\n\r\nlog('A',A);\r\nlog('B',B);\r\nlog('C',C);\r\nlog('D',D);\r\nlog('E',E);\r\nlog('F',F);\r\nlog('G',G);\r\nlog('H',H);\r\nlog('I',I);\r\nlog('J',J);\r\nlog('K',K);\r\nlog('L',L);\r\nlog('M',M);\r\nlog('N',N);\r\nlog('O',O);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>This shippet only presents functions used in performance tests - it not perform tests itself!</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Array small - 10 elements</strong></p>\n\n<p>You can perform tests in your machine <a href=\"https://jsperf.com/array-exist-element/1\" rel=\"noreferrer\">HERE</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/gDDCp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gDDCp.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Array big - 1.000.000 elements</strong></p>\n\n<p>You can perform tests in your machine <a href=\"https://jsperf.com/array-big-exist-element/1\" rel=\"noreferrer\">HERE</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/cTL3s.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/cTL3s.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 59874619, "author": "Majedur", "author_id": 3915410, "author_profile": "https://Stackoverflow.com/users/3915410", "pm_score": 2, "selected": false, "text": "<p><code>Object.keys</code> for getting all property names of the object and filter all values that exact or partial match with specified string.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function filterByValue(array, string) {\n return array.filter(o =&gt;\n Object.keys(o).some(k =&gt; o[k].toLowerCase().includes(string.toLowerCase())));\n}\n\nconst arrayOfObject = [{\n name: 'Paul',\n country: 'Canada',\n}, {\n name: 'Lea',\n country: 'Italy',\n}, {\n name: 'John',\n country: 'Italy'\n}];\n\nconsole.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]\nconsole.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You can also filter by specific key such as.</p>\n<pre><code>Object.keys(o).some(k =&gt; o.country.toLowerCase().includes(string.toLowerCase())));\n</code></pre>\n<p>Now you can just check array count after filtered to check value contains or not.</p>\n<p>Hope it's helpful.</p>\n" }, { "answer_id": 59920827, "author": "Mamunur Rashid", "author_id": 7940824, "author_profile": "https://Stackoverflow.com/users/7940824", "pm_score": 2, "selected": false, "text": "<p><strong>Adding a unique item to a another list</strong></p>\n\n<pre><code>searchResults: [\n {\n name: 'Hello',\n artist: 'Selana',\n album: 'Riga',\n id: 1,\n },\n {\n name: 'Hello;s',\n artist: 'Selana G',\n album: 'Riga1',\n id: 2,\n },\n {\n name: 'Hello2',\n artist: 'Selana',\n album: 'Riga11',\n id: 3,\n }\n ],\n playlistTracks: [\n {\n name: 'Hello',\n artist: 'Mamunuus',\n album: 'Riga',\n id: 4,\n },\n {\n name: 'Hello;s',\n artist: 'Mamunuus G',\n album: 'Riga1',\n id: 2,\n },\n {\n name: 'Hello2',\n artist: 'Mamunuus New',\n album: 'Riga11',\n id: 3,\n }\n ],\n playlistName: \"New PlayListTrack\",\n };\n }\n\n // Adding an unique track in the playList\n addTrack = track =&gt; {\n if(playlistTracks.find(savedTrack =&gt; savedTrack.id === track.id)) {\n return;\n }\n playlistTracks.push(track);\n\n this.setState({\n playlistTracks\n })\n };\n</code></pre>\n" }, { "answer_id": 61404171, "author": "Riwaj Chalise", "author_id": 10003098, "author_profile": "https://Stackoverflow.com/users/10003098", "pm_score": 3, "selected": false, "text": "<p><strong>Use indexOf()</strong></p>\n\n<p>You can use the indexOf() method to check whether a given value or element exists in an array or not. The indexOf() method returns the index of the element inside the array if it is found, and returns -1 if it not found. Let's take a look at the following example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var fruits = [\"Apple\", \"Banana\", \"Mango\", \"Orange\", \"Papaya\"];\r\nvar a = \"Mango\";\r\ncheckArray(a, fruits);\r\n\r\n\r\nfunction checkArray(a, fruits) {\r\n // Check if a value exists in the fruits array\r\n if (fruits.indexOf(a) !== -1) {\r\n return document.write(\"true\");\r\n } else {\r\n return document.write(\"false\");\r\n }\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Use include() Method</strong></p>\n\n<p>ES6 has introduced the includes() method to perform this task very easily. But, this method returns only true or false instead of index number:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var fruits = [\"Apple\", \"Banana\", \"Mango\", \"Orange\", \"Papaya\"];\r\nalert(fruits.includes(\"Banana\")); // Outputs: true\r\nalert(fruits.includes(\"Coconut\")); // Outputs: false\r\nalert(fruits.includes(\"Orange\")); // Outputs: true\r\nalert(fruits.includes(\"Cherry\")); // Outputs: false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>For further reference checkout <a href=\"https://www.tutorialrepublic.com/faq/how-to-check-if-a-value-exists-in-an-array-in-javascript.php\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 61984190, "author": "Md. Harun Or Rashid", "author_id": 2179062, "author_profile": "https://Stackoverflow.com/users/2179062", "pm_score": 2, "selected": false, "text": "<p>This may be a <strong>detailed and easy</strong> solution.</p>\n\n<pre><code>//plain array\nvar arr = ['a', 'b', 'c'];\nvar check = arr.includes('a');\nconsole.log(check); //returns true\nif (check)\n{\n // value exists in array\n //write some codes\n}\n\n// array with objects\nvar arr = [\n {x:'a', y:'b'},\n {x:'p', y:'q'}\n ];\n\n// if you want to check if x:'p' exists in arr\nvar check = arr.filter(function (elm){\n if (elm.x == 'p')\n {\n return elm; // returns length = 1 (object exists in array)\n }\n});\n\n// or y:'q' exists in arr\nvar check = arr.filter(function (elm){\n if (elm.y == 'q')\n {\n return elm; // returns length = 1 (object exists in array)\n }\n});\n\n// if you want to check, if the entire object {x:'p', y:'q'} exists in arr\nvar check = arr.filter(function (elm){\n if (elm.x == 'p' &amp;&amp; elm.y == 'q')\n {\n return elm; // returns length = 1 (object exists in array)\n }\n});\n\n// in all cases\nconsole.log(check.length); // returns 1\n\nif (check.length &gt; 0)\n{\n // returns true\n // object exists in array\n //write some codes\n}\n</code></pre>\n" }, { "answer_id": 62259894, "author": "da coconut", "author_id": 10105517, "author_profile": "https://Stackoverflow.com/users/10105517", "pm_score": 3, "selected": false, "text": "<p>use <code>Array.prototype.includes</code> for example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const fruits = ['coconut', 'banana', 'apple']\n\nconst doesFruitsHaveCoconut = fruits.includes('coconut')// true\n\nconsole.log(doesFruitsHaveCoconut)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>maybe read this documentation from MDN: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes</a></p>\n" }, { "answer_id": 65293687, "author": "MsiLucifer", "author_id": 14013826, "author_profile": "https://Stackoverflow.com/users/14013826", "pm_score": 0, "selected": false, "text": "<p>You can use findIndex function to check if an array has a specific value.</p>\n<pre><code>arrObj.findIndex(obj =&gt; obj === comparedValue) !== -1;\n</code></pre>\n<p>Returns true if arrObj contains comparedValue, false otherwise.</p>\n" }, { "answer_id": 68500364, "author": "francis", "author_id": 11209037, "author_profile": "https://Stackoverflow.com/users/11209037", "pm_score": 1, "selected": false, "text": "<p>Using RegExp:</p>\n<pre><code>console.log(new RegExp('26242').test(['23525', '26242', '25272'].join(''))) // true\n</code></pre>\n" }, { "answer_id": 70389359, "author": "Med Aziz CHETOUI", "author_id": 5253456, "author_profile": "https://Stackoverflow.com/users/5253456", "pm_score": 2, "selected": false, "text": "<p>The best default method to check if value exist in array JavaScript is <code>some()</code></p>\n<p><strong>Array.prototype.some()</strong></p>\n<p>The <code>some()</code> method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.</p>\n<pre><code>const array = [1, 2, 3, 4, 5];\n\n// checks whether an element is even\nconst even = (element) =&gt; element % 2 === 0;\n\nconsole.log(array.some(even));\n// expected output: true\n</code></pre>\n<p>The <code>some</code> method is the best one in <strong>Browser compatibility</strong>\n<a href=\"https://i.stack.imgur.com/uDTp4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uDTp4.png\" alt=\"Browser compatibility\" /></a></p>\n<p>For more documentation <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\">Array.prototype.some() - JavaScript | MDN</a></p>\n<p>Also you can use other two method is <code>find()</code> and <code>includes()</code>. with those method you can get your result but not the best one.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\">Array.prototype.find() - JavaScript | MDN</a></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\">Array.prototype.includes() - JavaScript | MDN</a></p>\n" }, { "answer_id": 70543468, "author": "Ran Turner", "author_id": 7494218, "author_profile": "https://Stackoverflow.com/users/7494218", "pm_score": 4, "selected": false, "text": "<p>There are a couple of method which makes this easy to achieve (<code>includes</code>, <code>some</code>, <code>find</code>, <code>findIndex</code>)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const array = [1, 2, 3, 4, 5, 6, 7];\n\nconsole.log(array.includes(3));\n//includes() determines whether an array includes a certain value among its entries\n\nconsole.log(array.some(x =&gt; x === 3)); \n//some() tests if at least one element in the array passes the test implemented by the provided function\n\nconsole.log(array.find(x =&gt; x === 3) ? true : false);\n//find() returns the value of the first element in the provided array that satisfies the provided testing function\n\nconsole.log(array.findIndex(x =&gt; x === 3) &gt; -1);\n//findIndex() returns the index of the first element in the array that satisfies the provided testing function, else returning -1.</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 72283811, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 1, "selected": false, "text": "<p>If you're just trying to check whether a value is included in a collection, It would be more appropriate to use a <code>Set</code>, As <code>Arrays</code> can have duplicate values whereas <code>Sets</code> cannot. Also, Replacing <code>array.includes</code> with <code>set.has</code> improves the performance from O(n<sup>2</sup>) to O(n). This will be useful when you have to look up multiple values for the same Set. so if you're just going to look up a single value, there's no benefit to use <code>set.has</code>, you can just use an <code>array.includes</code>.</p>\n<p>Created a <a href=\"https://jsbench.me/msl3b5k9r7/1\" rel=\"nofollow noreferrer\">jsbench</a> demo, You can run this to check the performance.</p>\n<p>Screenshot of the test execution <strong>:</strong></p>\n<p><a href=\"https://i.stack.imgur.com/tDfbw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tDfbw.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 73354963, "author": "Tiago Bértolo", "author_id": 1543163, "author_profile": "https://Stackoverflow.com/users/1543163", "pm_score": 0, "selected": false, "text": "<p>The fastest method in Javascript to find if an array contains a value is this:</p>\n<pre><code>function existsInArrayForIgnoreDataType(arr, targetElem) {\n for (let i = 0; i &lt; arr.length; i++) {\n if (arr[i] == targetElem) return true\n }\n return false\n }\n</code></pre>\n<p>You can find the complete study I did <a href=\"https://medium.com/@tiagobertolo/which-is-the-fastest-way-to-find-if-something-exists-in-an-array-in-javascript-49ab24051efb\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 73824762, "author": "Aurobindo Bhuyan", "author_id": 18467842, "author_profile": "https://Stackoverflow.com/users/18467842", "pm_score": 1, "selected": false, "text": "<p>There are several ways to find out.\nYou can use inbuilt Array methods. The most prominently used is Array find method.</p>\n<pre><code>const arr1 = [1, 2, 3, 4, 5]\nconst result = arr1.find(ele =&gt; ele === 4)\nconsole.log(result) //4\n\nconst result2 = arr1.find(ele =&gt; ele === 6)\nconsole.log(result2) //undefined\n/* \nIf the element is present inside the array\nthen it will return the first element that\nsatisfies the given condition. Otherwise\nundefined will return.\n*/\n\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
What is the most concise and efficient way to find out if a JavaScript array contains a value? This is the only way I know to do it: ``` function contains(a, obj) { for (var i = 0; i < a.length; i++) { if (a[i] === obj) { return true; } } return false; } ``` Is there a better and more concise way to accomplish this? This is very closely related to Stack Overflow question *[Best way to find an item in a JavaScript Array?](https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array)* which addresses finding objects in an array using `indexOf`.
Modern browsers have [`Array#includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#browser_compatibility), which does *exactly* that and [is widely supported](https://kangax.github.io/compat-table/es2016plus/#test-Array.prototype.includes) by everyone except IE: ```js console.log(['joe', 'jane', 'mary'].includes('jane')); //true ``` You can also use [`Array#indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf), which is less direct, but doesn't require polyfills for outdated browsers. ```js console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true ``` --- Many frameworks also offer similar methods: * jQuery: [`$.inArray(value, array, [fromIndex])`](https://api.jquery.com/jquery.inarray/) * Underscore.js: [`_.contains(array, value)`](https://underscorejs.org/#contains) (also aliased as `_.include` and `_.includes`) * Dojo Toolkit: [`dojo.indexOf(array, value, [fromIndex, findLast])`](https://dojotoolkit.org/reference-guide/1.10/dojo/indexOf.html) * Prototype: [`array.indexOf(value)`](http://api.prototypejs.org/language/Array/prototype/indexOf/) * MooTools: [`array.indexOf(value)`](https://mootools.net/core/docs/1.6.0/Types/Array#Array:indexOf) * MochiKit: [`findValue(array, value)`](http://mochi.github.io/mochikit/doc/html/MochiKit/Base.html#fn-findvalue) * MS Ajax: [`array.indexOf(value)`](https://web.archive.org/web/20140819232945/http://www.asp.net/ajaxlibrary/Reference.Array-indexOf-Function.ashx) * Ext: [`Ext.Array.contains(array, value)`](https://docs.sencha.com/extjs/7.5.1/modern/Ext.Array.html#method-contains) * Lodash: [`_.includes(array, value, [from])`](https://lodash.com/docs#includes) (is `_.contains` prior 4.0.0) * Ramda: [`R.includes(value, array)`](https://ramdajs.com/docs/#includes) Notice that some frameworks implement this as a function, while others add the function to the array prototype.
237,106
<p>I have a legacy DLL written in C that contains a function that returns a string, and I need to access this function from Delphi. The only info I have about the DLL is the VB declare for accessing the function:</p> <p>Public Declare Function DecryptStr Lib "strlib" (Str As String) As String </p> <p>I've tried the following without success:</p> <p>Declaration:</p> <pre><code>function DecryptStr(s: PChar): PChar; cdecl; external 'strlib.dll'; </code></pre> <p>Usage:</p> <pre><code>var p1, p2 : pchar; begin GetMem( p1, 255 ); StrPCopy( p2, 'some string to decrypt' ); p1 := DecryptStr( p2 ); end; </code></pre> <p>This consistently crashes the DLL with an Access Violation. I'm at a loss.</p> <p>Any suggestions ?</p>
[ { "answer_id": 237246, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "<p>I'm guessing here, but are you sure it's cdecl? If the VB declare isn't mentioning it, I'd assume it's in fact a STDCALL function (STDCALL is quite common on Windows, as almost all of its native API uses it). Calling a function of one calling convention as if it were of another calling convention can really mess up the stack, usually leading to a crash.</p>\n\n<p>Also, be sure to check whether the string is ANSI (LPSTR/LPCSTR) or UNICODE (LPWSTR/LPCWSTR). I don't know VB or Delphi, so I don't know what each one uses by default.</p>\n" }, { "answer_id": 237276, "author": "Mohammed Nasman", "author_id": 24462, "author_profile": "https://Stackoverflow.com/users/24462", "pm_score": 0, "selected": false, "text": "<p>I agree with CesarB, try to declare it with stdcall directive as:</p>\n\n<pre><code>function DecryptStr(s: PChar): PChar; stdcall; external 'strlib.dll';\n</code></pre>\n\n<p>if it doesn't work, post the VB declaration here.</p>\n" }, { "answer_id": 237656, "author": "Jozz", "author_id": 12351, "author_profile": "https://Stackoverflow.com/users/12351", "pm_score": 2, "selected": false, "text": "<p>p2 isn't initialized. StrPCopy copies the string to a random memory location. And most likely the calling convention is stdcall.</p>\n" }, { "answer_id": 237690, "author": "andrius", "author_id": 19865, "author_profile": "https://Stackoverflow.com/users/19865", "pm_score": 3, "selected": false, "text": "<p>Consider rewriting your test code as follows:</p>\n\n<pre><code>var\n p1, p2 : pchar;\nbegin\n GetMem( p1, 255 ); // initialize\n GetMem( p2, 255 );\n StrPLCopy( p2, 'some string to decrypt', 255 ); // prevent buffer overrun\n StrPLCopy( p1, DecryptStr( p2 ), 255); // make a copy since dll will free its internal buffer\nend;\n</code></pre>\n\n<p>If still fails within a call to DecryptStr, then read <a href=\"http://support.microsoft.com/kb/187912\" rel=\"noreferrer\">http://support.microsoft.com/kb/187912</a> carefully.</p>\n" }, { "answer_id": 238298, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 0, "selected": false, "text": "<p>The best way in these kind of situation is to debug your program and check the stack before and after executing the callback. How knows, it might even be a bug in the external DLL?</p>\n\n<p>This way you will see pretty easy how to correct this.</p>\n" }, { "answer_id": 238306, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 0, "selected": false, "text": "<p>Was the dll written in Borland C or C++Builder by any chance with the intention of being used with Delphi? In which case it could have been compiled using a pascal directive.</p>\n" }, { "answer_id": 239506, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 1, "selected": false, "text": "<p>As Jozz says, p2 (where you copy your string to) is never initialized in your example.</p>\n\n<p>Try this instead.</p>\n\n<pre><code>var\n p1, p2 : pchar;\nbegin\n GetMem( p2, 255 ); // allocate memory for 'some string...'\n StrPCopy( p2, 'some string to decrypt' );\n p1 := DecryptStr( p2 );\nend;\n</code></pre>\n\n<p>Also, the memory you allocated by calling Getmem(p1,...) would have been leaked, because p1 was overwritten by the function return from DecryptStr.</p>\n\n<p>However, I'd be a bit concerned about exactly what DecryptStr is returning, and who owns the memory pointed to by p1. If it's returning a pointer to memory allocated by the DLL you will need to be careful how that memory is freed. </p>\n" }, { "answer_id": 239550, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 0, "selected": false, "text": "<p>The suggestions that the strings must be \"initialised\" seem to be correct. This is because\nC will require that the string being passed in is null-terminated. Check that the character in the bufffer just after the end of the text is a null (#0).</p>\n\n<p>Why do you assume that the string passed in is exactly 255 chars long? You need to allocate Length(p1) + 1 bytes - for the chars in p1, and a #0 char at the end.</p>\n\n<p>Also, your code sample seems confused as to the use of p1 and p2. It looks like p1 is the buffer passed to the C DLL, which you allocate, and p2 is the returned string that the DLL allocates. But then the code would be (note use of p1 and p2)</p>\n\n<pre><code>var\n p1, p2 : pchar;\nbegin\n GetMem( p1, 255 );\n StrPCopy( p1, 'some string to decrypt' );\n p2 := DecryptStr( p1 );\nend;\n</code></pre>\n\n<p>Better variable names would help you make this clearer.</p>\n" }, { "answer_id": 15477354, "author": "Radu", "author_id": 1658112, "author_profile": "https://Stackoverflow.com/users/1658112", "pm_score": 0, "selected": false, "text": "<p>I'm dropping in my solution as I've sturggled quite a bit with it and haven't found it in any of the answers.</p>\n\n<p>The C++ function looks like this:</p>\n\n<pre><code>int __stdcall DoSomething(char * _name);\n</code></pre>\n\n<p>To get it working in Delphi, I declare the following function</p>\n\n<pre><code>function DoSomething(name: PAnsiChar): integer; stdcall; external 'somedll.dll';\n</code></pre>\n\n<p>And then when I make the call, I have a function that looks like this:</p>\n\n<pre><code>var s: PAnsiChar;\nbegin\n GetMem(s, 255);\n DoSomething(s);\n // s now contains the value returned from the C DLL\nend;\n</code></pre>\n\n<p>I have tried using PChar instead of PAnsiChar but all I get in return is garbage. Also, if I declare the function in Delphi with the parameter set to <em>var</em> , I get an exception when I try to read it.</p>\n\n<p>Hope this helps anyone..</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31510/" ]
I have a legacy DLL written in C that contains a function that returns a string, and I need to access this function from Delphi. The only info I have about the DLL is the VB declare for accessing the function: Public Declare Function DecryptStr Lib "strlib" (Str As String) As String I've tried the following without success: Declaration: ``` function DecryptStr(s: PChar): PChar; cdecl; external 'strlib.dll'; ``` Usage: ``` var p1, p2 : pchar; begin GetMem( p1, 255 ); StrPCopy( p2, 'some string to decrypt' ); p1 := DecryptStr( p2 ); end; ``` This consistently crashes the DLL with an Access Violation. I'm at a loss. Any suggestions ?
Consider rewriting your test code as follows: ``` var p1, p2 : pchar; begin GetMem( p1, 255 ); // initialize GetMem( p2, 255 ); StrPLCopy( p2, 'some string to decrypt', 255 ); // prevent buffer overrun StrPLCopy( p1, DecryptStr( p2 ), 255); // make a copy since dll will free its internal buffer end; ``` If still fails within a call to DecryptStr, then read <http://support.microsoft.com/kb/187912> carefully.
237,112
<p>Working on a project where a sequential set of methods must be run every <code>x</code> seconds. Right now I have the methods contained within another "parent method", and just sequentially call them right after another.</p> <pre><code>class DoTheseThings() { DoThis(); NowDoThat(); NowDoThis(); MoreWork(); AndImSpent(); } </code></pre> <p>Each method must run successfully without throwing an exception before the next step can be done. So now I wrapped each of those methods with a <code>while</code> and <code>try..catch</code>, then in the <code>catch</code> execute that method again.</p> <pre><code>while( !hadError ) { try { DoThis(); } catch(Exception doThisException ) { hadError = true; } } </code></pre> <p>This seems smelly and not very dry. Is there a better way to do this so I'm not wrapping any new functionality in the same methods. Isn't some kind of Delegate collection the proper way to implement this? </p> <p>Is there a more "proper" solution?</p>
[ { "answer_id": 237122, "author": "nyxtom", "author_id": 19753, "author_profile": "https://Stackoverflow.com/users/19753", "pm_score": 0, "selected": false, "text": "<p>What would be the reason that an error was occuring?</p>\n\n<p>If this were a resource issue, such as access to something like a connection or object, then you might want to look at using monitors, semaphores, or just locking. </p>\n\n<pre><code>lock (resource) \n{\n Dosomething(resource);\n}\n</code></pre>\n\n<p>This way if a previous method is accessing the resource, then you can wait until it releases the resource to continue. </p>\n\n<p>Ideally, you shouldn't have to run a loop to execute something each time it fails. It is failing at all, you would want to know about the issue and fix it. Having a loop to always just keep trying is not the right way to go here.</p>\n" }, { "answer_id": 237130, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 4, "selected": true, "text": "<pre><code>Action[] work=new Action[]{new Action(DoThis), new Action(NowDoThat), \n new Action(NowDoThis), new Action(MoreWork), new Action(AndImSpent)};\nint current =0;\nwhile(current!=work.Length)\n{\n try\n {\n work[current]();\n current++;\n }\n catch(Exception ex)\n {\n // log the error or whatever\n // maybe sleep a while to not kill the processors if a successful execution depends on time elapsed \n }\n}\n</code></pre>\n" }, { "answer_id": 237135, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Isn't some kind of Delegate collection the proper way to implement this?</p>\n</blockquote>\n\n<p>Delegate is a possible way to solve this problem.</p>\n\n<p>Just create a delegate something like:</p>\n\n<blockquote>\n <p>public delegate void WorkDelegate();</p>\n</blockquote>\n\n<p>and put them in arraylist which you can iterate over.</p>\n" }, { "answer_id": 237141, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "<p>I'd do what Ovidiu Pacurar suggests, only I'd use a <code>foreach</code> loop and leave dealing with array indexes up to the compiler.</p>\n" }, { "answer_id": 237197, "author": "Aristotle Ucab", "author_id": 31445, "author_profile": "https://Stackoverflow.com/users/31445", "pm_score": 1, "selected": false, "text": "<p>your example seems ok.. its a dry one but will do the job well!! actually if this methods execute db access.. you can use transaction to ensure integrity...</p>\n\n<p>if your dealing with shared variables for multi threader programs.. it is cleaner to use synchronization.. the most important thing in coding is that you write the proper code... that has less bugs.. and will do the task correctly..</p>\n" }, { "answer_id": 237238, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>Simple delegate approach:</p>\n\n<pre><code>Action&lt;Action&gt; tryForever = (action) =&gt; { \n bool success;\n do {\n try {\n action();\n success = true;\n } catch (Exception) {\n // should probably log or something here...\n }\n } while (!success);\n};\n\nvoid DoEverything() {\n tryForever(DoThis);\n tryForever(NowDoThat);\n tryForever(NowDoThis);\n tryForever(MoreWork);\n tryForever(AndImSpent);\n}\n</code></pre>\n\n<p>Stack approach:</p>\n\n<pre><code>void DoEverything() {\n Stack&lt;Action&gt; thingsToDo = new Stack&lt;Action&gt;(\n new Action[] { \n DoThis, NowDoThat, NowDoThis, MoreWork, AndImSpent \n }\n );\n\n Action action;\n while ((action = thingsToDo.Pop()) != null) {\n bool success;\n do {\n try {\n action();\n success = true;\n } catch (Exception) {\n }\n } while (!success);\n }\n</code></pre>\n" }, { "answer_id": 237245, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "<pre><code>public void DoTheseThings()\n{\n SafelyDoEach( new Action[]{\n DoThis,\n NowDoThat,\n NowDoThis,\n MoreWork,\n AndImSpent\n })\n}\n\npublic void SafelyDoEach( params Action[] actions )\n{\n try\n {\n foreach( var a in actions )\n a();\n }\n catch( Exception doThisException )\n {\n // blindly swallowing every exception like this is a terrible idea\n // you should really only be swallowing a specific MyAbortedException type\n return;\n }\n}\n</code></pre>\n" }, { "answer_id": 237298, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 2, "selected": false, "text": "<p>I have a personal religious belief that you shouldn't catch System.Exception, or more accurately, you should only catch the exceptions you know how to handle.</p>\n\n<p>That being said, I am going to assume that each one of the methods that you are calling are doing something different, and could result in different exceptions being thrown. Which means you would likely need to have different handlers for each method.</p>\n\n<p>If you follow my religion as well, and the second statement is true, then you are not repeating code unnecessarily. Unless you have other requirements, my recommendations to improve your code would be:</p>\n\n<p>1) Put the try-catch in each method, not around each method call.</p>\n\n<p>2) Have the catches within each method catch ONLY the exceptions you know about. </p>\n\n<p><a href=\"http://blogs.msdn.com/fxcop/archive/2006/06/14/631923.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/fxcop/archive/2006/06/14/631923.aspx</a> \n<a href=\"http://blogs.msdn.com/oldnewthing/archive/2005/01/14/352949.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2005/01/14/352949.aspx</a>\n<a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">http://www.joelonsoftware.com/articles/Wrong.html</a> </p>\n\n<p>HTH ...</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25300/" ]
Working on a project where a sequential set of methods must be run every `x` seconds. Right now I have the methods contained within another "parent method", and just sequentially call them right after another. ``` class DoTheseThings() { DoThis(); NowDoThat(); NowDoThis(); MoreWork(); AndImSpent(); } ``` Each method must run successfully without throwing an exception before the next step can be done. So now I wrapped each of those methods with a `while` and `try..catch`, then in the `catch` execute that method again. ``` while( !hadError ) { try { DoThis(); } catch(Exception doThisException ) { hadError = true; } } ``` This seems smelly and not very dry. Is there a better way to do this so I'm not wrapping any new functionality in the same methods. Isn't some kind of Delegate collection the proper way to implement this? Is there a more "proper" solution?
``` Action[] work=new Action[]{new Action(DoThis), new Action(NowDoThat), new Action(NowDoThis), new Action(MoreWork), new Action(AndImSpent)}; int current =0; while(current!=work.Length) { try { work[current](); current++; } catch(Exception ex) { // log the error or whatever // maybe sleep a while to not kill the processors if a successful execution depends on time elapsed } } ```
237,123
<p>I'm just learning to work with partial classes in VB.NET and VS2008. Specifically, I'm trying to extend a LINQ to SQL class that was automatically created by SqlMetal. </p> <p>The automatically generated class looks like this:</p> <pre><code>Partial Public Class DataContext Inherits System.Data.Linq.DataContext ... &lt;Table(Name:="dbo.Concessions")&gt; _ Partial Public Class Concession ... &lt;Column(Storage:="_Country", DbType:="Char(2)")&gt; _ Public Property Country() As String ... End Property ... End Class </code></pre> <p>In a separate file, here's what I'm trying to do:</p> <pre><code>Partial Public Class DataContext Partial Public Class Concession Public Function Foo() as String Return DoSomeProcessing(Me.Country) End Function End Class End Class </code></pre> <p>... but I get blue jaggies under '<code>Me.Country</code>' and the message <strong><code>'Country' is not a member of 'DataContext.Concession'</code></strong>. Both halves of the partial class are in the same namespace.</p> <p>So how do I access the properties of the automatically-generated half of the partial class, from my half of the partial class?</p>
[ { "answer_id": 237127, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 3, "selected": true, "text": "<p>Unless VB.NET generates different stuff in its LINQ to SQL files from C# the classes of the DB tables aren't within the DataContext class, just beside it.</p>\n\n<p>So you have the class <strong>MyNamespace.DataContext.Concession</strong> when the other half of the partial class is realy <strong>MyNamespace.Concession</strong></p>\n" }, { "answer_id": 5294777, "author": "Joe Niland", "author_id": 366965, "author_profile": "https://Stackoverflow.com/users/366965", "pm_score": 0, "selected": false, "text": "<p>(This related to VB.NET - might be differences with C# projects) </p>\n\n<p>I put my entities in their own namespace by configuring the Linq-to-SQL model property. </p>\n\n<p>e.g. MyCo.MyProj.Business.Entities</p>\n\n<p>I then add non-Linq business entities in there too, so they are all in the same namespace.</p>\n\n<p>However, when trying to do the above partial class additions, I found that the partial class (i.e. the one you generate, not the auto-generated LINQ class) MUST be in the same project as the Linq-to-SQL model. Otherwise in the Class View and Object Viewer you see two separate classes - seemingly in the same namespace, but not really. Not sure if this is a bug or I am doing something wrong.</p>\n\n<p>But, anyway, putting the partial class file in the same project as your model works.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I'm just learning to work with partial classes in VB.NET and VS2008. Specifically, I'm trying to extend a LINQ to SQL class that was automatically created by SqlMetal. The automatically generated class looks like this: ``` Partial Public Class DataContext Inherits System.Data.Linq.DataContext ... <Table(Name:="dbo.Concessions")> _ Partial Public Class Concession ... <Column(Storage:="_Country", DbType:="Char(2)")> _ Public Property Country() As String ... End Property ... End Class ``` In a separate file, here's what I'm trying to do: ``` Partial Public Class DataContext Partial Public Class Concession Public Function Foo() as String Return DoSomeProcessing(Me.Country) End Function End Class End Class ``` ... but I get blue jaggies under '`Me.Country`' and the message **`'Country' is not a member of 'DataContext.Concession'`**. Both halves of the partial class are in the same namespace. So how do I access the properties of the automatically-generated half of the partial class, from my half of the partial class?
Unless VB.NET generates different stuff in its LINQ to SQL files from C# the classes of the DB tables aren't within the DataContext class, just beside it. So you have the class **MyNamespace.DataContext.Concession** when the other half of the partial class is realy **MyNamespace.Concession**
237,131
<p>I have a <code>JPanel</code> extension that I've written and would like to be able to use it in the NetBeans designer. The component is simply adds some custom painting and continues to function as a container to be customised on each use. </p> <p>I have properties to expose in addition to the standard <code>JPanel</code> ones and have a custom <code>paintComponent()</code> method that I'd like to be able to see in use when building up GUIs. Ideally I'd like to associate an icon with the component as well so that its easily recognisable for my colleagues to work with.</p> <p>What's the best way of achieving this?</p>
[ { "answer_id": 237866, "author": "Rastislav Komara", "author_id": 22068, "author_profile": "https://Stackoverflow.com/users/22068", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.netbeans.org\" rel=\"nofollow noreferrer\">http://www.netbeans.org</a> search for Matisse.</p>\n" }, { "answer_id": 242551, "author": "Chobicus", "author_id": 1514822, "author_profile": "https://Stackoverflow.com/users/1514822", "pm_score": 3, "selected": true, "text": "<p>I made JPanel component in NetBeans with overridden paint method:</p>\n\n<pre><code>@Override\npublic void paint(Graphics g) {\n super.paint(g);\n Graphics2D g2 = (Graphics2D) g;\n ...\n //draw elements \n ...\n}\n</code></pre>\n\n<p>It has some custom properties accessible through NetBeans properties window.</p>\n\n<pre><code>public int getResolutionX() {\n return resolutionX;\n}\n\npublic void setResolutionX(int resolutionX) {\n this.resolutionX = resolutionX;\n}\n\npublic int getResolutionY() {\n return resolutionY;\n}\n\npublic void setResolutionY(int resolutionY) {\n this.resolutionY = resolutionY;\n}\n</code></pre>\n\n<p>I put it in my palette using: \nTools->Palette->Swing/AWT Components.</p>\n\n<p>It even has the same look I painted in my overridden paint method while I am doing drag/drop in another container. I didn't associate icon to it though.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 11235052, "author": "Andy Dingfelder", "author_id": 1484207, "author_profile": "https://Stackoverflow.com/users/1484207", "pm_score": 0, "selected": false, "text": "<p>You can add your custom component to the matisse GUI palatte.</p>\n\n<ol>\n<li>Build your project so the class file you want to use is part of the jar file</li>\n<li>Open a java class that has a form, and switch to design mode.\n3, Right click in the palatte and choose \"palatte manager\". </li>\n<li>Choose the \"add from jar\" button to select your jar. </li>\n<li>Choose the class you made, and add it to your palatte. </li>\n</ol>\n\n<p>Now your panel is known to netbeans, and you can drag it into new panels.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1867/" ]
I have a `JPanel` extension that I've written and would like to be able to use it in the NetBeans designer. The component is simply adds some custom painting and continues to function as a container to be customised on each use. I have properties to expose in addition to the standard `JPanel` ones and have a custom `paintComponent()` method that I'd like to be able to see in use when building up GUIs. Ideally I'd like to associate an icon with the component as well so that its easily recognisable for my colleagues to work with. What's the best way of achieving this?
I made JPanel component in NetBeans with overridden paint method: ``` @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; ... //draw elements ... } ``` It has some custom properties accessible through NetBeans properties window. ``` public int getResolutionX() { return resolutionX; } public void setResolutionX(int resolutionX) { this.resolutionX = resolutionX; } public int getResolutionY() { return resolutionY; } public void setResolutionY(int resolutionY) { this.resolutionY = resolutionY; } ``` I put it in my palette using: Tools->Palette->Swing/AWT Components. It even has the same look I painted in my overridden paint method while I am doing drag/drop in another container. I didn't associate icon to it though. Hope this helps.
237,140
<p>I was re-reading Effective Java (2nd edition) item 18, <a href="http://my.safaribooksonline.com/9780137150021/ch04lev1sec6" rel="nofollow noreferrer">prefer interfaces to abstract classes</a>. In that item Josh Bloch provides an example of a skeletal implementation of the <code>Map.Entry&lt;K,V&gt;</code> interface:</p> <pre><code>// Skeletal Implementation public abstract class AbstractMapEntry&lt;K,V&gt; implements Map.Entry&lt;K,V&gt; { // Primitive operations public abstract K getKey(); public abstract V getValue(); // ... remainder omitted } </code></pre> <p>Two questions stem from this example:</p> <ol> <li>Why are getKey and getValue explicitly declared here as abstract methods? They are part of the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.Entry.html" rel="nofollow noreferrer">Map.Entry</a> interface, so I don't see a reason for the redundant declaration in the abstract class.</li> <li><p>Why use the idiom of leaving these primitives methods, as Mr. Bloch refers to them, as abstract? Why not just do this:</p> <p>// Skeletal Implementation public abstract class AbstractMapEntry implements Map.Entry { private K key; private V value;</p> <pre><code> // Primitive operations public K getKey() {return key;} public V getValue() {return value;} // ... remainder omitted </code></pre> <p>}</p></li> </ol> <p>The benefits of this are that each subclass doesn't have to define its own set of fields, and can still access the key and value by their accessors. If a subclass truly needs to define its own behavior for the accessors, it can implement the Map.Entry interface directly. The other downside is that in the equals method provided by the skeletal implementation, the abstract accessors are called:</p> <pre><code>// Implements the general contract of Map.Entry.equals @Override public boolean equals(Object o) { if (o == this) return true; if (! (o instanceof Map.Entry)) return false; Map.Entry&lt;?,?&gt; arg = (Map.Entry) o; return equals(getKey(), arg.getKey()) &amp;&amp; equals(getValue(), arg.getValue()); } </code></pre> <p>Bloch warns against calling overridable methods (item 17) from classes designed for inheritance as it leaves the superclass vulnerable to changes made by subclasses. Maybe this is a matter of opinion, but I was hoping to determine whether there's more to the story, as Bloch doesn't really elaborate on this in the book.</p>
[ { "answer_id": 237194, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 0, "selected": false, "text": "<p>One reason that <code>AbstractMapEntry#getKey</code> and <code>getValue</code> are abstract (i.e. unimplemented) is that <code>Map.Entry</code> is an inner interface to <code>Map</code>. Using nested classes/interfaces is how Java implements composition. The idea in composition is that the composed part is not a first-class concept. Rather, the composed part only make sense if it is contained in the whole. In this case, the composed part is <code>Map.Entry</code> and the root object of the composite is <code>Map</code>. Obviously the concept expressed is that a <code>Map</code> has many <code>Map.Entry</code>s. </p>\n\n<p>Therefore the semantics of <code>AbstractMapEntry#getKey</code> and <code>getValue</code> will depend essentially on the implementation of <code>Map</code> that we're talking about. A plain old getter implementation as you've written will work just fine for <code>HashMap</code>. It won't work for something like <code>ConcurrentHashMap</code> which demands thread-safety. It's likely that <code>ConcurrentHashMap</code>'s implementation of <code>getKey</code> and <code>getValue</code> make defensive copies. (Recommend checking the source code for yourself).</p>\n\n<p>Another reason not to implement <code>getKey</code> and <code>getValue</code> is that the characters that implement <code>Map</code> are radically different ranging from ones that should have never belonged (i.e. <code>Properties</code>) to completely different universes from an intuitive impls of <code>Map</code> (e.g. <code>Provider</code>, <code>TabularDataSupport</code>).</p>\n\n<p>In conclusion, <em>not</em> implementing <code>AbstractMapEntry#getKey</code> and <code>getValue</code>, because of this golden rule of API design:</p>\n\n<blockquote>\n <p>When in doubt, leave it out (see <a href=\"http://www.artima.com/intv/blochP.html\" rel=\"nofollow noreferrer\">here</a>)</p>\n</blockquote>\n" }, { "answer_id": 947857, "author": "objects", "author_id": 116339, "author_profile": "https://Stackoverflow.com/users/116339", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>I don't see any reason</p></li>\n<li><p>Allows the implementation to define how the key and value are stored.</p></li>\n</ol>\n" }, { "answer_id": 947928, "author": "Yishai", "author_id": 77779, "author_profile": "https://Stackoverflow.com/users/77779", "pm_score": 1, "selected": false, "text": "<ol>\n<li>I would say it helps emphasize what the concrete class is intended to deal with, instead of just leaving it up to the compiler to tell you (or you having to compare both to see what is missing). Kind of self-documenting code. But it certainly isn't necessary, it is more of a style thing, as far as I can see.</li>\n<li>There is more significant logic in returning these values than simple getter and setting. Every class I spot checked in the standard JDK(1.5) did something non-simple on at least one of the methods, so I would guess that he views such an implementation as too naive and it would encourage subclasses to use it instead of thinking through the problem on their own.</li>\n</ol>\n\n<p>Regarding the issue with equals, nothing would change if the abstract class implemented them because the issue is overrid<strong>able</strong>. In this case I would say that the equals is attempting to be carefully implemented to anticipate implementations. Normally equals in general should not be implemented to return true between itself and its subclass (although there are plenty that do) due to covariance issues (the superclass will think it equals the subclass, but the subclass won't think it equals the superclass), so this type of implementation of equals is tricky no matter what you do.</p>\n" }, { "answer_id": 4426552, "author": "John", "author_id": 266333, "author_profile": "https://Stackoverflow.com/users/266333", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Bloch warns against calling\n overridable methods (item 17) from\n classes designed for inheritance as it\n leaves the superclass vulnerable to\n changes made by subclasses</p>\n</blockquote>\n\n<p>He warns about calling overridable methods in the constructor, not in other methods.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8217/" ]
I was re-reading Effective Java (2nd edition) item 18, [prefer interfaces to abstract classes](http://my.safaribooksonline.com/9780137150021/ch04lev1sec6). In that item Josh Bloch provides an example of a skeletal implementation of the `Map.Entry<K,V>` interface: ``` // Skeletal Implementation public abstract class AbstractMapEntry<K,V> implements Map.Entry<K,V> { // Primitive operations public abstract K getKey(); public abstract V getValue(); // ... remainder omitted } ``` Two questions stem from this example: 1. Why are getKey and getValue explicitly declared here as abstract methods? They are part of the [Map.Entry](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.Entry.html) interface, so I don't see a reason for the redundant declaration in the abstract class. 2. Why use the idiom of leaving these primitives methods, as Mr. Bloch refers to them, as abstract? Why not just do this: // Skeletal Implementation public abstract class AbstractMapEntry implements Map.Entry { private K key; private V value; ``` // Primitive operations public K getKey() {return key;} public V getValue() {return value;} // ... remainder omitted ``` } The benefits of this are that each subclass doesn't have to define its own set of fields, and can still access the key and value by their accessors. If a subclass truly needs to define its own behavior for the accessors, it can implement the Map.Entry interface directly. The other downside is that in the equals method provided by the skeletal implementation, the abstract accessors are called: ``` // Implements the general contract of Map.Entry.equals @Override public boolean equals(Object o) { if (o == this) return true; if (! (o instanceof Map.Entry)) return false; Map.Entry<?,?> arg = (Map.Entry) o; return equals(getKey(), arg.getKey()) && equals(getValue(), arg.getValue()); } ``` Bloch warns against calling overridable methods (item 17) from classes designed for inheritance as it leaves the superclass vulnerable to changes made by subclasses. Maybe this is a matter of opinion, but I was hoping to determine whether there's more to the story, as Bloch doesn't really elaborate on this in the book.
1. I would say it helps emphasize what the concrete class is intended to deal with, instead of just leaving it up to the compiler to tell you (or you having to compare both to see what is missing). Kind of self-documenting code. But it certainly isn't necessary, it is more of a style thing, as far as I can see. 2. There is more significant logic in returning these values than simple getter and setting. Every class I spot checked in the standard JDK(1.5) did something non-simple on at least one of the methods, so I would guess that he views such an implementation as too naive and it would encourage subclasses to use it instead of thinking through the problem on their own. Regarding the issue with equals, nothing would change if the abstract class implemented them because the issue is overrid**able**. In this case I would say that the equals is attempting to be carefully implemented to anticipate implementations. Normally equals in general should not be implemented to return true between itself and its subclass (although there are plenty that do) due to covariance issues (the superclass will think it equals the subclass, but the subclass won't think it equals the superclass), so this type of implementation of equals is tricky no matter what you do.
237,145
<p>I have a radio button on my Windows Form. How can I determine if the CheckChanged event occurred due to a user clicking or selecting the radio button vs programatically setting the event with </p> <pre><code>this.radioButtonAdd.Checked = true; </code></pre> <p>I would like some code to take a different action depending on if the user clicked the button or I raised the event myself.</p> <p>Or maybe the better question is how do I handle the event when a user clicks vs when the state is changed in my code.</p>
[ { "answer_id": 237153, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>If there is a built-in method, then I am not aware of it.</p>\n\n<p>One way to handle it is by setting a global flag while the code is making changes that tells the event handler. For example, the code making the changes could look something like the following:</p>\n\n<pre><code>savedFlag = modifyingProgrammatically;\nmodifyingProgrammatically = true;\nthis.radioButtonAdd.Checked = true;\nmodifingProgrammatically = savedFlag;\n</code></pre>\n\n<p>Within your event handler:</p>\n\n<pre><code>if(modifyingProgramatically) {\n // The event was raised by an assignment within the code.\n} else {\n // The event was raised by a user action.\n}\n</code></pre>\n" }, { "answer_id": 237188, "author": "Omar Shahine", "author_id": 1496, "author_profile": "https://Stackoverflow.com/users/1496", "pm_score": 3, "selected": true, "text": "<p>I think I found a pretty good answer.</p>\n\n<p>All Windows Forms controls have a property called \"Tag\". its value can be any object.</p>\n\n<p>So if I want to ingore any programatic changes I can do the following:</p>\n\n<pre><code>radioButton.Tag = \"ignore\"\nradioButton.Checked = true\n</code></pre>\n\n<p>then in the event handler:</p>\n\n<pre><code>private void radioButton_CheckedChanged(object sender, EventArgs e)\n{\n if (radioButton.Checked)\n {\n // Tag will be null in cases where the user clicks\n if (this.radioButtonAdd.Tag == null)\n {\n // do something\n }\n else\n { \n // swallow action\n // reset Tag\n this.radioButtonAdd.Tag = null;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 237541, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 1, "selected": false, "text": "<p>You could also do something like changing a flag field value on MouseDown for the radio button, then reverting the flag value on MouseClick. Since the CheckedChanged event fires between the two, it can use the flag before it's reverted by the MouseClick event, and you don't have to worry about resetting its state.</p>\n\n<p>You may still have threading issues to resolve if you're using a field as a flag (don't know much about the application you're working on), but something like this should work:</p>\n\n<pre><code> private bool _mouseEvent;\n private void radioButton1_CheckedChanged(object sender, EventArgs e)\n {\n if (_mouseEvent)\n MessageBox.Show(\"Changed by mouse click.\");\n else\n MessageBox.Show(\"Changed from code.\");\n }\n\n private void radioButton1_MouseClick(object sender, MouseEventArgs e)\n {\n _mouseEvent = false;\n }\n\n private void radioButton1_MouseDown(object sender, MouseEventArgs e)\n {\n _mouseEvent = true;\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n // This simulates a change from code vs. a change from\n // a mouse click.\n if (radioButton1.Checked)\n radioButton2.Checked = true;\n else\n radioButton1.Checked = true;\n }\n</code></pre>\n\n<p>Alternately, you could separate your \"mouse-click-only\" application logic so that it's triggered by a different event (like MouseClick).</p>\n\n<p>Hope this helps.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1496/" ]
I have a radio button on my Windows Form. How can I determine if the CheckChanged event occurred due to a user clicking or selecting the radio button vs programatically setting the event with ``` this.radioButtonAdd.Checked = true; ``` I would like some code to take a different action depending on if the user clicked the button or I raised the event myself. Or maybe the better question is how do I handle the event when a user clicks vs when the state is changed in my code.
I think I found a pretty good answer. All Windows Forms controls have a property called "Tag". its value can be any object. So if I want to ingore any programatic changes I can do the following: ``` radioButton.Tag = "ignore" radioButton.Checked = true ``` then in the event handler: ``` private void radioButton_CheckedChanged(object sender, EventArgs e) { if (radioButton.Checked) { // Tag will be null in cases where the user clicks if (this.radioButtonAdd.Tag == null) { // do something } else { // swallow action // reset Tag this.radioButtonAdd.Tag = null; } } } ```
237,159
<p>I normally use the following idiom to check if a String can be converted to an integer.</p> <pre><code>public boolean isInteger( String input ) { try { Integer.parseInt( input ); return true; } catch( Exception e ) { return false; } } </code></pre> <p>Is it just me, or does this seem a bit hackish? What's a better way?</p> <hr> <p>See my answer (with benchmarks, based on the <a href="https://stackoverflow.com/a/237321/1288">earlier answer</a> by <a href="https://stackoverflow.com/users/28278/codingwithspike">CodingWithSpike</a>) to see why I've reversed my position and accepted <a href="https://stackoverflow.com/a/237204/1288">Jonas Klemming's answer</a> to this problem. I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.</p>
[ { "answer_id": 237161, "author": "Kristian", "author_id": 11429, "author_profile": "https://Stackoverflow.com/users/11429", "pm_score": 2, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>return Pattern.matches(\"-?\\\\d+\", input);\n</code></pre>\n" }, { "answer_id": 237163, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 6, "selected": false, "text": "<p>You have it, but you should only catch <code>NumberFormatException</code>.</p>\n" }, { "answer_id": 237166, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": false, "text": "<p>This is shorter, but shorter isn't necessarily better (and it won't catch integer values which are out of range, <a href=\"https://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java#237161\">as pointed out in danatel's comment</a>):</p>\n\n<pre><code>input.matches(\"^-?\\\\d+$\");\n</code></pre>\n\n<p>Personally, since the implementation is squirrelled away in a helper method and correctness trumps length, I would just go with something like what you have (minus catching the base <code>Exception</code> class rather than <code>NumberFormatException</code>).</p>\n" }, { "answer_id": 237179, "author": "lucas", "author_id": 31172, "author_profile": "https://Stackoverflow.com/users/31172", "pm_score": 0, "selected": false, "text": "<p>What you did works, but you probably shouldn't always check that way. Throwing exceptions should be reserved for \"exceptional\" situations (maybe that fits in your case, though), and are very costly in terms of performance.</p>\n" }, { "answer_id": 237204, "author": "Jonas K", "author_id": 26609, "author_profile": "https://Stackoverflow.com/users/26609", "pm_score": 9, "selected": true, "text": "<p>If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using <code>Integer.parseInt()</code>.</p>\n\n<pre><code>public static boolean isInteger(String str) {\n if (str == null) {\n return false;\n }\n int length = str.length();\n if (length == 0) {\n return false;\n }\n int i = 0;\n if (str.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i = 1;\n }\n for (; i &lt; length; i++) {\n char c = str.charAt(i);\n if (c &lt; '0' || c &gt; '9') {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 237240, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": -1, "selected": false, "text": "<pre><code>Integer.valueOf(string); \n</code></pre>\n\n<p>works for me most of the time!</p>\n" }, { "answer_id": 237321, "author": "CodingWithSpike", "author_id": 28278, "author_profile": "https://Stackoverflow.com/users/28278", "pm_score": 5, "selected": false, "text": "<p>Did a quick benchmark. Exceptions aren't actually that expensivve, unless you start popping back multiple methods and the JVM has to do a lot of work to get the execution stack in place. When staying in the same method, they aren't bad performers.</p>\n\n<pre><code> public void RunTests()\n {\n String str = \"1234567890\";\n\n long startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByException(str);\n long endTime = System.currentTimeMillis();\n System.out.print(\"ByException: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByRegex(str);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByRegex: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByJonas(str);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByJonas: \");\n System.out.println(endTime - startTime);\n }\n\n private boolean IsInt_ByException(String str)\n {\n try\n {\n Integer.parseInt(str);\n return true;\n }\n catch(NumberFormatException nfe)\n {\n return false;\n }\n }\n\n private boolean IsInt_ByRegex(String str)\n {\n return str.matches(\"^-?\\\\d+$\");\n }\n\n public boolean IsInt_ByJonas(String str)\n {\n if (str == null) {\n return false;\n }\n int length = str.length();\n if (length == 0) {\n return false;\n }\n int i = 0;\n if (str.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i = 1;\n }\n for (; i &lt; length; i++) {\n char c = str.charAt(i);\n if (c &lt;= '/' || c &gt;= ':') {\n return false;\n }\n }\n return true;\n }\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>ByException: 31</p>\n \n <p>ByRegex: 453 (note: re-compiling the pattern every time)</p>\n \n <p>ByJonas: 16</p>\n</blockquote>\n\n<p>I do agree that Jonas K's solution is the most robust too. Looks like he wins :)</p>\n" }, { "answer_id": 237614, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 2, "selected": false, "text": "<p>You can also use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html\" rel=\"nofollow noreferrer\">Scanner</a> class, and use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNextInt--\" rel=\"nofollow noreferrer\">hasNextInt()</a> - and this allows you to test for other types, too, like floats, etc.</p>\n" }, { "answer_id": 237689, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>It partly depend on what you mean by \"can be converted to an integer\".</p>\n\n<p>If you mean \"can be converted into an int in Java\" then the answer from Jonas is a good start, but doesn't quite finish the job. It would pass 999999999999999999999999999999 for example. I would add the normal try/catch call from your own question at the end of the method.</p>\n\n<p>The character-by-character checks will efficiently reject \"not an integer at all\" cases, leaving \"it's an integer but Java can't handle it\" cases to be caught by the slower exception route. You <em>could</em> do this bit by hand too, but it would be a <em>lot</em> more complicated.</p>\n" }, { "answer_id": 237714, "author": "Ran Biron", "author_id": 931, "author_profile": "https://Stackoverflow.com/users/931", "pm_score": -1, "selected": false, "text": "<pre><code>Number number;\ntry {\n number = NumberFormat.getInstance().parse(\"123\");\n} catch (ParseException e) {\n //not a number - do recovery.\n e.printStackTrace();\n}\n//use number\n</code></pre>\n" }, { "answer_id": 237895, "author": "Rastislav Komara", "author_id": 22068, "author_profile": "https://Stackoverflow.com/users/22068", "pm_score": 4, "selected": false, "text": "<p>Just one comment about regexp. Every example provided here is wrong!. If you want to use regexp don't forget that compiling the pattern take a lot of time. This:</p>\n\n<pre><code>str.matches(\"^-?\\\\d+$\")\n</code></pre>\n\n<p>and also this:</p>\n\n<pre><code>Pattern.matches(\"-?\\\\d+\", input);\n</code></pre>\n\n<p>causes compile of pattern in every method call. To used it correctly follow:</p>\n\n<pre><code>import java.util.regex.Pattern;\n\n/**\n * @author Rastislav Komara\n */\npublic class NaturalNumberChecker {\n public static final Pattern PATTERN = Pattern.compile(\"^\\\\d+$\");\n\n boolean isNaturalNumber(CharSequence input) {\n return input != null &amp;&amp; PATTERN.matcher(input).matches();\n }\n}\n</code></pre>\n" }, { "answer_id": 237994, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": false, "text": "<p>I copied the code from rally25rs answer and added some tests for non-integer data. The results are undeniably in favor of the method posted by Jonas Klemming. The results for the Exception method that I originally posted are pretty good when you have integer data, but they're the worst when you don't, while the results for the RegEx solution (that I'll bet a lot of people use) were <em>consistently</em> bad. See <a href=\"https://stackoverflow.com/a/7324087/1288\">Felipe's answer</a> for a compiled regex example, which is much faster.</p>\n\n<pre><code>public void runTests()\n{\n String big_int = \"1234567890\";\n String non_int = \"1234XY7890\";\n\n long startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByException(big_int);\n long endTime = System.currentTimeMillis();\n System.out.print(\"ByException - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByException(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByException - non-integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByRegex(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByRegex - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByRegex(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByRegex - non-integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByJonas(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByJonas - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByJonas(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByJonas - non-integer data: \");\n System.out.println(endTime - startTime);\n}\n\nprivate boolean IsInt_ByException(String str)\n{\n try\n {\n Integer.parseInt(str);\n return true;\n }\n catch(NumberFormatException nfe)\n {\n return false;\n }\n}\n\nprivate boolean IsInt_ByRegex(String str)\n{\n return str.matches(\"^-?\\\\d+$\");\n}\n\npublic boolean IsInt_ByJonas(String str)\n{\n if (str == null) {\n return false;\n }\n int length = str.length();\n if (length == 0) {\n return false;\n }\n int i = 0;\n if (str.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i = 1;\n }\n for (; i &lt; length; i++) {\n char c = str.charAt(i);\n if (c &lt;= '/' || c &gt;= ':') {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>ByException - integer data: 47\nByException - non-integer data: 547\n\nByRegex - integer data: 390\nByRegex - non-integer data: 313\n\nByJonas - integer data: 0\nByJonas - non-integer data: 16\n</code></pre>\n" }, { "answer_id": 239470, "author": "Łukasz Bownik", "author_id": 24028, "author_profile": "https://Stackoverflow.com/users/24028", "pm_score": 5, "selected": false, "text": "<pre><code>org.apache.commons.lang.StringUtils.isNumeric \n</code></pre>\n\n<p>though Java's standard lib really misses such utility functions</p>\n\n<p>I think that Apache Commons is a \"must have\" for every Java programmer</p>\n\n<p>too bad it isn't ported to Java5 yet</p>\n" }, { "answer_id": 7324087, "author": "Felipe", "author_id": 484601, "author_profile": "https://Stackoverflow.com/users/484601", "pm_score": 5, "selected": false, "text": "<p>Since there's possibility that people still visit here and will be biased against Regex after the benchmarks... So i'm gonna give an updated version of the benchmark, with a compiled version of the Regex. Which opposed to the previous benchmarks, this one shows Regex solution actually has consistently good performance.</p>\n\n<p>Copied from Bill the Lizard and updated with compiled version:</p>\n\n<pre><code>private final Pattern pattern = Pattern.compile(\"^-?\\\\d+$\");\n\npublic void runTests() {\n String big_int = \"1234567890\";\n String non_int = \"1234XY7890\";\n\n long startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByException(big_int);\n long endTime = System.currentTimeMillis();\n System.out.print(\"ByException - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByException(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByException - non-integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByRegex(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByRegex - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByRegex(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByRegex - non-integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for (int i = 0; i &lt; 100000; i++)\n IsInt_ByCompiledRegex(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByCompiledRegex - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for (int i = 0; i &lt; 100000; i++)\n IsInt_ByCompiledRegex(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByCompiledRegex - non-integer data: \");\n System.out.println(endTime - startTime);\n\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByJonas(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByJonas - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i &lt; 100000; i++)\n IsInt_ByJonas(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByJonas - non-integer data: \");\n System.out.println(endTime - startTime);\n}\n\nprivate boolean IsInt_ByException(String str)\n{\n try\n {\n Integer.parseInt(str);\n return true;\n }\n catch(NumberFormatException nfe)\n {\n return false;\n }\n}\n\nprivate boolean IsInt_ByRegex(String str)\n{\n return str.matches(\"^-?\\\\d+$\");\n}\n\nprivate boolean IsInt_ByCompiledRegex(String str) {\n return pattern.matcher(str).find();\n}\n\npublic boolean IsInt_ByJonas(String str)\n{\n if (str == null) {\n return false;\n }\n int length = str.length();\n if (length == 0) {\n return false;\n }\n int i = 0;\n if (str.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i = 1;\n }\n for (; i &lt; length; i++) {\n char c = str.charAt(i);\n if (c &lt;= '/' || c &gt;= ':') {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>ByException - integer data: 45\nByException - non-integer data: 465\n\nByRegex - integer data: 272\nByRegex - non-integer data: 131\n\nByCompiledRegex - integer data: 45\nByCompiledRegex - non-integer data: 26\n\nByJonas - integer data: 8\nByJonas - non-integer data: 2\n</code></pre>\n" }, { "answer_id": 9936636, "author": "callejero", "author_id": 1302331, "author_profile": "https://Stackoverflow.com/users/1302331", "pm_score": 0, "selected": false, "text": "<p>This would work only for positive integers.</p>\n\n<pre><code>public static boolean isInt(String str) {\n if (str != null &amp;&amp; str.length() != 0) {\n for (int i = 0; i &lt; str.length(); i++) {\n if (!Character.isDigit(str.charAt(i))) return false;\n }\n }\n return true; \n}\n</code></pre>\n" }, { "answer_id": 10410242, "author": "mobra66", "author_id": 1369503, "author_profile": "https://Stackoverflow.com/users/1369503", "pm_score": 1, "selected": false, "text": "<p>You probably need to take the use case in account too:</p>\n\n<p>If most of the time you expect numbers to be valid, then catching the exception is only causing a performance overhead when attempting to convert invalid numbers. Whereas calling some <code>isInteger()</code> method and then convert using <code>Integer.parseInt()</code> will <em>always</em> cause a performance overhead for valid numbers - the strings are parsed twice, once by the check and once by the conversion.</p>\n" }, { "answer_id": 13868966, "author": "Kaitie", "author_id": 1902372, "author_profile": "https://Stackoverflow.com/users/1902372", "pm_score": 3, "selected": false, "text": "<p>You can use the matches method of the string class. The [0-9] represents all the values it can be, the + means it must be at least one character long, and the * means it can be zero or more characters long. </p>\n\n<pre><code>boolean isNumeric = yourString.matches(\"[0-9]+\"); // 1 or more characters long, numbers only\nboolean isNumeric = yourString.matches(\"[0-9]*\"); // 0 or more characters long, numbers only\n</code></pre>\n" }, { "answer_id": 17874157, "author": "duggu", "author_id": 1722818, "author_profile": "https://Stackoverflow.com/users/1722818", "pm_score": 2, "selected": false, "text": "<p>You just check <strong>NumberFormatException</strong>:-</p>\n\n<pre><code> String value=\"123\";\n try \n { \n int s=Integer.parseInt(any_int_val);\n // do something when integer values comes \n } \n catch(NumberFormatException nfe) \n { \n // do something when string values comes \n } \n</code></pre>\n" }, { "answer_id": 22012491, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 2, "selected": false, "text": "<p>You may try apache utils</p>\n\n<pre><code>NumberUtils.isCreatable(myText)\n</code></pre>\n\n<p><a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/math/NumberUtils.html#isCreatable-java.lang.String-\" rel=\"nofollow noreferrer\">See the javadoc here</a></p>\n" }, { "answer_id": 22469209, "author": "realPK", "author_id": 853001, "author_profile": "https://Stackoverflow.com/users/853001", "pm_score": 2, "selected": false, "text": "<p>If your String array contains pure Integers and Strings, code below should work. You only have to look at first character.\ne.g. [\"4\",\"44\",\"abc\",\"77\",\"bond\"]</p>\n\n<pre><code>if (Character.isDigit(string.charAt(0))) {\n //Do something with int\n}\n</code></pre>\n" }, { "answer_id": 23630046, "author": "Sae1962", "author_id": 265140, "author_profile": "https://Stackoverflow.com/users/265140", "pm_score": -1, "selected": false, "text": "<p>For those readers who arrive here like me years after the question was asked, I have a more general solution for this question.</p>\n\n<pre><code>/**\n * Checks, if the string represents a number.\n *\n * @param string the string\n * @return true, if the string is a number\n */\npublic static boolean isANumber(final String string) {\n if (string != null) {\n final int length = string.length();\n if (length != 0) {\n int i = 0;\n if (string.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i++;\n }\n for (; i &lt; length; i++) {\n final char c = string.charAt(i);\n if ((c &lt;= PERIOD) || ((c &gt;= COLON))) {\n final String strC = Character.toString(c).toUpperCase();\n final boolean isExponent = strC.equals(\"E\");\n final boolean isPeriod = (c == PERIOD);\n final boolean isPlus = (c == PLUS);\n\n if (!isExponent &amp;&amp; !isPeriod &amp;&amp; !isPlus) {\n return false;\n }\n }\n }\n return true;\n }\n }\n return false;\n}\n</code></pre>\n" }, { "answer_id": 25069800, "author": "Wayne", "author_id": 3109012, "author_profile": "https://Stackoverflow.com/users/3109012", "pm_score": 1, "selected": false, "text": "<p>This is a modification of <strong>Jonas</strong>' code that checks if the string is within range to be cast into an integer. </p>\n\n<pre><code>public static boolean isInteger(String str) {\n if (str == null) {\n return false;\n }\n int length = str.length();\n int i = 0;\n\n // set the length and value for highest positive int or lowest negative int\n int maxlength = 10;\n String maxnum = String.valueOf(Integer.MAX_VALUE);\n if (str.charAt(0) == '-') { \n maxlength = 11;\n i = 1;\n maxnum = String.valueOf(Integer.MIN_VALUE);\n } \n\n // verify digit length does not exceed int range\n if (length &gt; maxlength) { \n return false; \n }\n\n // verify that all characters are numbers\n if (maxlength == 11 &amp;&amp; length == 1) {\n return false;\n }\n for (int num = i; num &lt; length; num++) {\n char c = str.charAt(num);\n if (c &lt; '0' || c &gt; '9') {\n return false;\n }\n }\n\n // verify that number value is within int range\n if (length == maxlength) {\n for (; i &lt; length; i++) {\n if (str.charAt(i) &lt; maxnum.charAt(i)) {\n return true;\n }\n else if (str.charAt(i) &gt; maxnum.charAt(i)) {\n return false;\n }\n }\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 27562595, "author": "Niroshan Abeywickrama", "author_id": 4377200, "author_profile": "https://Stackoverflow.com/users/4377200", "pm_score": 0, "selected": false, "text": "<p>This works for me. Simply to identify whether a String is a primitive or a number.</p>\n\n<pre><code>private boolean isPrimitive(String value){\n boolean status=true;\n if(value.length()&lt;1)\n return false;\n for(int i = 0;i&lt;value.length();i++){\n char c=value.charAt(i);\n if(Character.isDigit(c) || c=='.'){\n\n }else{\n status=false;\n break;\n }\n }\n return status;\n }\n</code></pre>\n" }, { "answer_id": 29329799, "author": "Roger F. Gay", "author_id": 490484, "author_profile": "https://Stackoverflow.com/users/490484", "pm_score": 0, "selected": false, "text": "<p>To check for all int chars, you can simply use a double negative. </p>\n\n<p>if (!searchString.matches(\"[^0-9]+$\")) ...</p>\n\n<p>[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.</p>\n" }, { "answer_id": 29810655, "author": "mark_infinite", "author_id": 4794229, "author_profile": "https://Stackoverflow.com/users/4794229", "pm_score": 1, "selected": false, "text": "<p>I believe there's zero risk running into an exception, because as you can see below you always safely parse <code>int</code> to <code>String</code> and not the other way around.</p>\n<p>So:</p>\n<ol>\n<li><p>You <strong>check</strong> if every slot of character in your string matches at least\none of the characters <strong>{&quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;}</strong>.</p>\n<pre><code>if(aString.substring(j, j+1).equals(String.valueOf(i)))\n</code></pre>\n</li>\n<li><p>You <strong>sum</strong> all the times that you encountered in the slots the above\ncharacters.</p>\n<pre><code>digits++;\n</code></pre>\n</li>\n<li><p>And finally you <strong>check</strong> if the times that you encountered integers as\ncharacters equals with the length of the given string.</p>\n<pre><code>if(digits == aString.length())\n</code></pre>\n</li>\n</ol>\n<p>And in practice we have:</p>\n<pre><code> String aString = &quot;1234224245&quot;;\n int digits = 0;//count how many digits you encountered\n for(int j=0;j&lt;aString.length();j++){\n for(int i=0;i&lt;=9;i++){\n if(aString.substring(j, j+1).equals(String.valueOf(i)))\n digits++;\n }\n }\n if(digits == aString.length()){\n System.out.println(&quot;It's an integer!!&quot;);\n }\n else{\n System.out.println(&quot;It's not an integer!!&quot;);\n }\n \n String anotherString = &quot;1234f22a4245&quot;;\n int anotherDigits = 0;//count how many digits you encountered\n for(int j=0;j&lt;anotherString.length();j++){\n for(int i=0;i&lt;=9;i++){\n if(anotherString.substring(j, j+1).equals(String.valueOf(i)))\n anotherDigits++;\n }\n }\n if(anotherDigits == anotherString.length()){\n System.out.println(&quot;It's an integer!!&quot;);\n }\n else{\n System.out.println(&quot;It's not an integer!!&quot;);\n }\n</code></pre>\n<p>And the results are:</p>\n<blockquote>\n<p>It's an integer!!</p>\n<p>It's not an integer!!</p>\n</blockquote>\n<p>Similarly, you can validate if a <code>String</code> is a <code>float</code> or a <code>double</code> but in those cases you have to encounter <strong>only one .</strong> (dot) in the String and of course check if <code>digits == (aString.length()-1)</code></p>\n<blockquote>\n<p>Again, there's zero risk running into a parsing exception here, but if you plan on parsing a string that it is known that contains a number (let's say <strong>int</strong> data type) you must first check if it fits in the data type. Otherwise you must cast it.</p>\n</blockquote>\n<p>I hope I helped</p>\n" }, { "answer_id": 31218166, "author": "shellbye", "author_id": 1398065, "author_profile": "https://Stackoverflow.com/users/1398065", "pm_score": -1, "selected": false, "text": "<p>Find this may helpful:</p>\n\n<pre><code>public static boolean isInteger(String self) {\n try {\n Integer.valueOf(self.trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 31292785, "author": "timxyz", "author_id": 359627, "author_profile": "https://Stackoverflow.com/users/359627", "pm_score": 1, "selected": false, "text": "<p>If you are using the Android API you can use:</p>\n\n<pre><code>TextUtils.isDigitsOnly(str);\n</code></pre>\n" }, { "answer_id": 34651222, "author": "abalcerek", "author_id": 3187921, "author_profile": "https://Stackoverflow.com/users/3187921", "pm_score": 4, "selected": false, "text": "<p>There is guava version:</p>\n\n<pre><code>import com.google.common.primitives.Ints;\n\nInteger intValue = Ints.tryParse(stringValue);\n</code></pre>\n\n<p>It will return null instead of throwing an exception if it fails to parse string.</p>\n" }, { "answer_id": 36540208, "author": "salaheddine", "author_id": 3357630, "author_profile": "https://Stackoverflow.com/users/3357630", "pm_score": -1, "selected": false, "text": "<pre><code>public class HelloWorld{\n\n static boolean validateIP(String s){\n String[] value = s.split(\"\\\\.\");\n if(value.length!=4) return false;\n int[] v = new int[4];\n for(int i=0;i&lt;4;i++){\n for(int j=0;j&lt;value[i].length();j++){\n if(!Character.isDigit(value[i].charAt(j))) \n return false;\n }\n v[i]=Integer.parseInt(value[i]);\n if(!(v[i]&gt;=0 &amp;&amp; v[i]&lt;=255)) return false;\n }\n return true;\n }\n\n public static void main(String[] argv){\n String test = \"12.23.8.9j\";\n if(validateIP(test)){\n System.out.println(\"\"+test);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 36782502, "author": "Gabriel Kaffka", "author_id": 2297767, "author_profile": "https://Stackoverflow.com/users/2297767", "pm_score": 2, "selected": false, "text": "<p>Another option:</p>\n\n<pre><code>private boolean isNumber(String s) {\n boolean isNumber = true;\n for (char c : s.toCharArray()) {\n isNumber = isNumber &amp;&amp; Character.isDigit(c);\n }\n return isNumber;\n}\n</code></pre>\n" }, { "answer_id": 40358657, "author": "Ellrohir", "author_id": 3204544, "author_profile": "https://Stackoverflow.com/users/3204544", "pm_score": 0, "selected": false, "text": "<p>I have seen a lot of answers here, but most of them are able to determine whether the String is numeric, but they fail checking whether the number is in Integer range...</p>\n\n<p>Therefore I purpose something like this:</p>\n\n<pre><code>public static boolean isInteger(String str) {\n if (str == null || str.isEmpty()) {\n return false;\n }\n try {\n long value = Long.valueOf(str);\n return value &gt;= -2147483648 &amp;&amp; value &lt;= 2147483647;\n } catch (Exception ex) {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 42985788, "author": "gil.fernandes", "author_id": 2735286, "author_profile": "https://Stackoverflow.com/users/2735286", "pm_score": 2, "selected": false, "text": "<p>This is a Java 8 variation of Jonas Klemming answer:</p>\n\n<pre><code>public static boolean isInteger(String str) {\n return str != null &amp;&amp; str.length() &gt; 0 &amp;&amp;\n IntStream.range(0, str.length()).allMatch(i -&gt; i == 0 &amp;&amp; (str.charAt(i) == '-' || str.charAt(i) == '+')\n || Character.isDigit(str.charAt(i)));\n}\n</code></pre>\n\n<p>Test code:</p>\n\n<pre><code>public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n Arrays.asList(\"1231231\", \"-1232312312\", \"+12313123131\", \"qwqe123123211\", \"2\", \"0000000001111\", \"\", \"123-\", \"++123\",\n \"123-23\", null, \"+-123\").forEach(s -&gt; {\n System.out.printf(\"%15s %s%n\", s, isInteger(s));\n });\n}\n</code></pre>\n\n<p>Results of the test code:</p>\n\n<pre><code> 1231231 true\n -1232312312 true\n +12313123131 true\n qwqe123123211 false\n 2 true\n 0000000001111 true\n false\n 123- false\n ++123 false\n 123-23 false\n null false\n +-123 false\n</code></pre>\n" }, { "answer_id": 45873328, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If you want to check if the string represents an integer that fits in an int type, I did a little modification to the jonas' answer, so that strings that represent integers bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE, will now return false. For example: \"3147483647\" will return false because 3147483647 is bigger than 2147483647, and likewise, \"-2147483649\" will also return false because -2147483649 is smaller than -2147483648.</p>\n\n<pre><code>public static boolean isInt(String s) {\n if(s == null) {\n return false;\n }\n s = s.trim(); //Don't get tricked by whitespaces.\n int len = s.length();\n if(len == 0) {\n return false;\n }\n //The bottom limit of an int is -2147483648 which is 11 chars long.\n //[note that the upper limit (2147483647) is only 10 chars long]\n //Thus any string with more than 11 chars, even if represents a valid integer, \n //it won't fit in an int.\n if(len &gt; 11) {\n return false;\n }\n char c = s.charAt(0);\n int i = 0;\n //I don't mind the plus sign, so \"+13\" will return true.\n if(c == '-' || c == '+') {\n //A single \"+\" or \"-\" is not a valid integer.\n if(len == 1) {\n return false;\n }\n i = 1;\n }\n //Check if all chars are digits\n for(; i &lt; len; i++) {\n c = s.charAt(i);\n if(c &lt; '0' || c &gt; '9') {\n return false;\n }\n }\n //If we reached this point then we know for sure that the string has at\n //most 11 chars and that they're all digits (the first one might be a '+'\n // or '-' thought).\n //Now we just need to check, for 10 and 11 chars long strings, if the numbers\n //represented by the them don't surpass the limits.\n c = s.charAt(0);\n char l;\n String limit;\n if(len == 10 &amp;&amp; c != '-' &amp;&amp; c != '+') {\n limit = \"2147483647\";\n //Now we are going to compare each char of the string with the char in\n //the limit string that has the same index, so if the string is \"ABC\" and\n //the limit string is \"DEF\" then we are gonna compare A to D, B to E and so on.\n //c is the current string's char and l is the corresponding limit's char\n //Note that the loop only continues if c == l. Now imagine that our string\n //is \"2150000000\", 2 == 2 (next), 1 == 1 (next), 5 &gt; 4 as you can see,\n //because 5 &gt; 4 we can guarantee that the string will represent a bigger integer.\n //Similarly, if our string was \"2139999999\", when we find out that 3 &lt; 4,\n //we can also guarantee that the integer represented will fit in an int.\n for(i = 0; i &lt; len; i++) {\n c = s.charAt(i);\n l = limit.charAt(i);\n if(c &gt; l) {\n return false;\n }\n if(c &lt; l) {\n return true;\n }\n }\n }\n c = s.charAt(0);\n if(len == 11) {\n //If the first char is neither '+' nor '-' then 11 digits represent a \n //bigger integer than 2147483647 (10 digits).\n if(c != '+' &amp;&amp; c != '-') {\n return false;\n }\n limit = (c == '-') ? \"-2147483648\" : \"+2147483647\";\n //Here we're applying the same logic that we applied in the previous case\n //ignoring the first char.\n for(i = 1; i &lt; len; i++) {\n c = s.charAt(i);\n l = limit.charAt(i);\n if(c &gt; l) {\n return false;\n }\n if(c &lt; l) {\n return true;\n }\n }\n }\n //The string passed all tests, so it must represent a number that fits\n //in an int...\n return true;\n}\n</code></pre>\n" }, { "answer_id": 51116899, "author": "Tihamer", "author_id": 2882939, "author_profile": "https://Stackoverflow.com/users/2882939", "pm_score": 0, "selected": false, "text": "<p><strong>When explanations are more important than performance</strong></p>\n\n<p>I noticed many discussions centering how efficient certain solutions are, but none on <em>why</em> an string is not an integer. Also, everyone seemed to assume that the number \"2.00\" is not equal to \"2\". Mathematically and humanly speaking, they <em>are</em> equal (even though computer science says that they are not, and for good reason). This is why the \"Integer.parseInt\" solutions above are weak (depending on your requirements).</p>\n\n<p>At any rate, to make software smarter and more human-friendly, we need to create software that thinks like we do and explains <em>why</em> something failed. In this case:</p>\n\n<pre><code>public static boolean isIntegerFromDecimalString(String possibleInteger) {\npossibleInteger = possibleInteger.trim();\ntry {\n // Integer parsing works great for \"regular\" integers like 42 or 13.\n int num = Integer.parseInt(possibleInteger);\n System.out.println(\"The possibleInteger=\"+possibleInteger+\" is a pure integer.\");\n return true;\n} catch (NumberFormatException e) {\n if (possibleInteger.equals(\".\")) {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it is only a decimal point.\");\n return false;\n } else if (possibleInteger.startsWith(\".\") &amp;&amp; possibleInteger.matches(\"\\\\.[0-9]*\")) {\n if (possibleInteger.matches(\"\\\\.[0]*\")) {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is an integer because it starts with a decimal point and afterwards is all zeros.\");\n return true;\n } else {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it starts with a decimal point and afterwards is not all zeros.\");\n return false;\n }\n } else if (possibleInteger.endsWith(\".\") &amp;&amp; possibleInteger.matches(\"[0-9]*\\\\.\")) {\n System.out.println(\"The possibleInteger=\"+possibleInteger+\" is an impure integer (ends with decimal point).\");\n return true;\n } else if (possibleInteger.contains(\".\")) {\n String[] partsOfPossibleInteger = possibleInteger.split(\"\\\\.\");\n if (partsOfPossibleInteger.length == 2) {\n //System.out.println(\"The possibleInteger=\" + possibleInteger + \" is split into '\" + partsOfPossibleInteger[0] + \"' and '\" + partsOfPossibleInteger[1] + \"'.\");\n if (partsOfPossibleInteger[0].matches(\"[0-9]*\")) {\n if (partsOfPossibleInteger[1].matches(\"[0]*\")) {\n System.out.println(\"The possibleInteger=\"+possibleInteger+\" is an impure integer (ends with all zeros after the decimal point).\");\n return true;\n } else if (partsOfPossibleInteger[1].matches(\"[0-9]*\")) {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it the numbers after the decimal point (\" + \n partsOfPossibleInteger[1] + \") are not all zeros.\");\n return false;\n } else {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it the 'numbers' after the decimal point (\" + \n partsOfPossibleInteger[1] + \") are not all numeric digits.\");\n return false;\n }\n } else {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it the 'number' before the decimal point (\" + \n partsOfPossibleInteger[0] + \") is not a number.\");\n return false;\n }\n } else {\n System.out.println(\"The possibleInteger=\"+possibleInteger+\" is NOT an integer because it has a strange number of decimal-period separated parts (\" +\n partsOfPossibleInteger.length + \").\");\n return false;\n }\n } // else\n System.out.println(\"The possibleInteger='\"+possibleInteger+\"' is NOT an integer, even though it has no decimal point.\");\n return false;\n}\n}\n</code></pre>\n\n<p>Test code:</p>\n\n<pre><code>String[] testData = {\"0\", \"0.\", \"0.0\", \".000\", \"2\", \"2.\", \"2.0\", \"2.0000\", \"3.14159\", \".0001\", \".\", \"$4.0\", \"3E24\", \"6.0221409e+23\"};\nint i = 0;\nfor (String possibleInteger : testData ) {\n System.out.println(\"\");\n System.out.println(i + \". possibleInteger='\" + possibleInteger +\"' isIntegerFromDecimalString=\" + isIntegerFromDecimalString(possibleInteger));\n i++;\n}\n</code></pre>\n" }, { "answer_id": 56903293, "author": "Balconsky", "author_id": 939497, "author_profile": "https://Stackoverflow.com/users/939497", "pm_score": 0, "selected": false, "text": "<p>I do not like method with regex, because regex can not check ranges (<code>Integer.MIN_VALUE</code>, <code>Integer.MAX_VALUE</code>).</p>\n\n<p>If you expect int value in most cases, and not int is something uncommon, then I suggest version with <code>Integer.valueOf</code> or <code>Integer.parseInt</code> with <code>NumberFormatException</code> catching. Advantage of this approach - your code has good readability:</p>\n\n<pre><code>public static boolean isInt(String s) {\n try {\n Integer.parseInt(s);\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n}\n</code></pre>\n\n<p>If you need to check if String is integer, and care about perfomance then the best way will be to use java jdk implementation of <code>Integer.parseInt</code>, but little modified (replacing throw with return false):</p>\n\n<p><strong>This function has good perfomence and garantee right result:</strong></p>\n\n<pre><code> public static boolean isInt(String s) {\n int radix = 10;\n\n if (s == null) {\n return false;\n }\n\n if (radix &lt; Character.MIN_RADIX) {\n return false;\n }\n\n if (radix &gt; Character.MAX_RADIX) {\n return false;\n }\n\n int result = 0;\n boolean negative = false;\n int i = 0, len = s.length();\n int limit = -Integer.MAX_VALUE;\n int multmin;\n int digit;\n\n if (len &gt; 0) {\n char firstChar = s.charAt(0);\n if (firstChar &lt; '0') { // Possible leading \"+\" or \"-\"\n if (firstChar == '-') {\n negative = true;\n limit = Integer.MIN_VALUE;\n } else if (firstChar != '+')\n return false;\n\n if (len == 1) // Cannot have lone \"+\" or \"-\"\n return false;\n i++;\n }\n multmin = limit / radix;\n while (i &lt; len) {\n // Accumulating negatively avoids surprises near MAX_VALUE\n digit = Character.digit(s.charAt(i++), radix);\n if (digit &lt; 0) {\n return false;\n }\n if (result &lt; multmin) {\n return false;\n }\n result *= radix;\n if (result &lt; limit + digit) {\n return false;\n }\n result -= digit;\n }\n } else {\n return false;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 62519971, "author": "Guildenstern", "author_id": 1725151, "author_profile": "https://Stackoverflow.com/users/1725151", "pm_score": 0, "selected": false, "text": "<p>You could:</p>\n<ol>\n<li>Check that the string is a number</li>\n<li>Check that it is not too long to be parsed as a <code>long</code></li>\n<li>Check if the resulting <code>long</code> value is small enough to be represented by an <code>int</code></li>\n</ol>\n<p>(Assuming you for some reason would have to implement this yourself: you should probably first take a look at <code>com.google.common.primitives.Ints.tryParse(String)</code> and see if that is good enough for your purposes (as suggested <a href=\"https://stackoverflow.com/a/34651222/1725151\">in another answer</a>).)</p>\n<pre><code>// Credit to Rastislav Komara’s answer: https://stackoverflow.com/a/237895/1725151\nprivate static final Pattern nonZero = Pattern.compile(&quot;^-?[1-9]\\\\d*$&quot;);\n\n// See if `str` can be parsed as an `int` (does not trim)\n// Strings like `0023` are rejected (leading zeros).\npublic static boolean parsableAsInt(@Nonnull String str) {\n if (str.isEmpty()) {\n return false;\n }\n if (str.equals(&quot;0&quot;)) {\n return true;\n }\n if (canParseAsLong(str)) {\n long value = Long.valueOf(str);\n if (value &gt;= Integer.MIN_VALUE &amp;&amp; value &lt;= Integer.MAX_VALUE) {\n return true;\n }\n }\n return false;\n}\n\nprivate static boolean canParseAsLong(String str) {\n final int intMaxLength = 11;\n return str.length() &lt;= intMaxLength &amp;&amp; nonZero.matcher(str).matches();\n}\n</code></pre>\n<p>This method can also be converted to return <code>Optional&lt;Integer&gt;</code> so that you don’t have to parse the string twice in the client code (once to check if it’s possible and the second time to do it “for real”). For example:</p>\n<pre><code>if (canParseAsLong(str)) {\n long value = Long.valueOf(str);\n if (value &gt;= Integer.MIN_VALUE &amp;&amp; value &lt;= Integer.MAX_VALUE) {\n return Optional.of((int) value);\n }\n}\n</code></pre>\n" }, { "answer_id": 63143029, "author": "Yossarian42", "author_id": 9905745, "author_profile": "https://Stackoverflow.com/users/9905745", "pm_score": 0, "selected": false, "text": "<p>a little improvement to @Jonas K anwser, this function will rule out one single operator like <code>&quot;*&quot;</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean isInteger(String str) {\n // null pointer\n if (str == null) {\n return false;\n }\n int len = str.length();\n // empty string\n if (len == 0) {\n return false;\n }\n // one digit, cannot begin with 0\n if (len == 1) {\n char c = str.charAt(0);\n if ((c &lt; '1') || (c &gt; '9')) {\n return false;\n }\n }\n\n for (int i = 0; i &lt; len; i++) {\n char c = str.charAt(i);\n // check positive, negative sign\n if (i == 0) {\n if (c == '-' || c == '+') {\n continue;\n }\n }\n // check each character matches [0-9]\n if ((c &lt; '0') || (c &gt; '9')) {\n return false;\n }\n }\n return true;\n}\n\n</code></pre>\n" }, { "answer_id": 64089400, "author": "Anu", "author_id": 7713486, "author_profile": "https://Stackoverflow.com/users/7713486", "pm_score": 0, "selected": false, "text": "<p>I recently (today) needed to figure out a quick way to do this and of course I was going to use the exception approach for ease when the monkey on the shoulder (conscience) woke up so it took me down this old familiar rabbit hole; no exceptions are not that much more expensive in fact sometimes exceptions are faster (old AIX multiprocessor systems) but regardless it’s to elegant so I did something that the younger me never did and to my amazement nobody here did either (apologize if someone did and I missed it I honestly did not find) : so what did I think we all missed; taking a look at how the JRE implemented it, yes they threw an exception but we can always skip that part.</p>\n<p>The younger me from 10 years ago would have felt this to be beneath him, but then again he is a loud mouthed show off with a poor temperament and a god complex so there is that.</p>\n<p>I am putting this here for the benefit of anyone coming here in the future. Here is what I found:</p>\n<pre><code>public static int parseInt(String s, int radix) throws NumberFormatException\n{\n /*\n * WARNING: This method may be invoked early during VM initialization\n * before IntegerCache is initialized. Care must be taken to not use\n * the valueOf method.\n */\n\n if (s == null) {\n throw new NumberFormatException(&quot;null&quot;);\n }\n\n if (radix &lt; Character.MIN_RADIX) {\n throw new NumberFormatException(&quot;radix &quot; + radix +\n &quot; less than Character.MIN_RADIX&quot;);\n }\n\n if (radix &gt; Character.MAX_RADIX) {\n throw new NumberFormatException(&quot;radix &quot; + radix +\n &quot; greater than Character.MAX_RADIX&quot;);\n }\n\n int result = 0;\n boolean negative = false;\n int i = 0, len = s.length();\n int limit = -Integer.MAX_VALUE;\n int multmin;\n int digit;\n\n if (len &gt; 0) {\n char firstChar = s.charAt(0);\n if (firstChar &lt; '0') { // Possible leading &quot;+&quot; or &quot;-&quot;\n if (firstChar == '-') {\n negative = true;\n limit = Integer.MIN_VALUE;\n } else if (firstChar != '+')\n throw NumberFormatException.forInputString(s);\n\n if (len == 1) // Cannot have lone &quot;+&quot; or &quot;-&quot;\n throw NumberFormatException.forInputString(s);\n i++;\n }\n multmin = limit / radix;\n while (i &lt; len) {\n // Accumulating negatively avoids surprises near MAX_VALUE\n digit = Character.digit(s.charAt(i++),radix);\n if (digit &lt; 0) {\n throw NumberFormatException.forInputString(s);\n }\n if (result &lt; multmin) {\n throw NumberFormatException.forInputString(s);\n }\n result *= radix;\n if (result &lt; limit + digit) {\n throw NumberFormatException.forInputString(s);\n }\n result -= digit;\n }\n } else {\n throw NumberFormatException.forInputString(s);\n }\n return negative ? result : -result;\n}\n</code></pre>\n" }, { "answer_id": 64694246, "author": "Old Nick", "author_id": 5227689, "author_profile": "https://Stackoverflow.com/users/5227689", "pm_score": 0, "selected": false, "text": "<p>several answers here saying to try parsing to an integer and catching the NumberFormatException but you should not do this.</p>\n<p>That way would create exception object and generates a stack trace each time you called it and it was not an integer.</p>\n<p>A better way with Java 8 would be to use a stream:</p>\n<pre><code>boolean isInteger = returnValue.chars().allMatch(Character::isDigit);\n</code></pre>\n" }, { "answer_id": 65262555, "author": "Gk Mohammad Emon", "author_id": 7200133, "author_profile": "https://Stackoverflow.com/users/7200133", "pm_score": 0, "selected": false, "text": "<p>For <strong>kotlin</strong>, <code>isDigitsOnly()</code> <em>(Also for Java's <code>TextUtils.isDigitsOnly()</code>)</em> of <code>String</code> always returns false it has a negative sign in front though the rest of the character is digit only. For example -</p>\n<pre><code>/** For kotlin*/\nvar str = &quot;-123&quot; \nstr.isDigitsOnly() //Result will be false \n\n/** For Java */\nString str = &quot;-123&quot;\nTextUtils.isDigitsOnly(str) //Result will be also false \n</code></pre>\n<p>So I made a quick fix by this -</p>\n<pre><code> var isDigit=str.matches(&quot;-?\\\\d+(\\\\.\\\\d+)?&quot;.toRegex()) \n/** Result will be true for now*/\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
I normally use the following idiom to check if a String can be converted to an integer. ``` public boolean isInteger( String input ) { try { Integer.parseInt( input ); return true; } catch( Exception e ) { return false; } } ``` Is it just me, or does this seem a bit hackish? What's a better way? --- See my answer (with benchmarks, based on the [earlier answer](https://stackoverflow.com/a/237321/1288) by [CodingWithSpike](https://stackoverflow.com/users/28278/codingwithspike)) to see why I've reversed my position and accepted [Jonas Klemming's answer](https://stackoverflow.com/a/237204/1288) to this problem. I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.
If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using `Integer.parseInt()`. ``` public static boolean isInteger(String str) { if (str == null) { return false; } int length = str.length(); if (length == 0) { return false; } int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; } ```
237,201
<p>I'm trying to perform a simple LINQ query on the Columns property of a DataTable:</p> <pre><code>from c in myDataTable.Columns.AsQueryable() select c.ColumnName </code></pre> <p>However, what I get is this:</p> <blockquote> <p>Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'c'.</p> </blockquote> <p>How can I get the DataColumnCollection to play nice with LINQ?</p>
[ { "answer_id": 237224, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 8, "selected": true, "text": "<p>How about:</p>\n\n<pre><code>var x = from c in dt.Columns.Cast&lt;DataColumn&gt;()\n select c.ColumnName;\n</code></pre>\n" }, { "answer_id": 9996173, "author": "Cobra", "author_id": 1071574, "author_profile": "https://Stackoverflow.com/users/1071574", "pm_score": 4, "selected": false, "text": "<p>You could also use:</p>\n\n<pre><code>var x = from DataColumn c in myDataTable.Columns\n select c.ColumnName\n</code></pre>\n\n<p>It will effectively do the same as Dave's code: \"in a query expression, an explicitly typed iteration variable translates to an invocation of Cast(IEnumerable)\", according to the <a href=\"http://msdn.microsoft.com/en-us/library/bb341406.aspx\" rel=\"noreferrer\"><code>Enumerable.Cast&lt;TResult&gt; Method</code></a> MSDN article.</p>\n" }, { "answer_id": 49302799, "author": "MarkusE", "author_id": 3405498, "author_profile": "https://Stackoverflow.com/users/3405498", "pm_score": 4, "selected": false, "text": "<p>With Linq Method Syntax:</p>\n\n<pre><code>var x = myDataTable.Columns.Cast&lt;DataColumn&gt;().Select(c =&gt; c.ColumnName);\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31516/" ]
I'm trying to perform a simple LINQ query on the Columns property of a DataTable: ``` from c in myDataTable.Columns.AsQueryable() select c.ColumnName ``` However, what I get is this: > > Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'c'. > > > How can I get the DataColumnCollection to play nice with LINQ?
How about: ``` var x = from c in dt.Columns.Cast<DataColumn>() select c.ColumnName; ```
237,220
<p>I'm looking for an algorithm that places tick marks on an axis, given a range to display, a width to display it in, and a function to measure a string width for a tick mark.</p> <p>For example, given that I need to display between 1e-6 and 5e-6 and a width to display in pixels, the algorithm would determine that I should put tickmarks (for example) at 1e-6, 2e-6, 3e-6, 4e-6, and 5e-6. Given a smaller width, it might decide that the optimal placement is only at the even positions, i.e. 2e-6 and 4e-6 (since putting more tickmarks would cause them to overlap).</p> <p>A smart algorithm would give preference to tickmarks at multiples of 10, 5, and 2. Also, a smart algorithm would be symmetric around zero.</p>
[ { "answer_id": 239058, "author": "mindvirus", "author_id": 31455, "author_profile": "https://Stackoverflow.com/users/31455", "pm_score": 2, "selected": false, "text": "<p>Take the longest of the segments about zero (or the whole graph, if zero is not in the range) - for example, if you have something on the range [-5, 1], take [-5,0].</p>\n\n<p>Figure out approximately how long this segment will be, in ticks. This is just dividing the length by the width of a tick. So suppose the method says that we can put 11 ticks in from -5 to 0. This is our upper bound. For the shorter side, we'll just mirror the result on the longer side.</p>\n\n<p>Now try to put in as many (up to 11) ticks in, such that the marker for each tick in the form i*10*10^n, i*5*10^n, i*2*10^n, where n is an integer, and i is the index of the tick. Now it's an optimization problem - we want to maximize the number of ticks we can put in, while at the same time minimizing the distance between the last tick and the end of the result. So assign a score for getting as many ticks as we can, less than our upper bound, and assign a score to getting the last tick close to n - you'll have to experiment here.</p>\n\n<p>In the above example, try n = 1. We get 1 tick (at i=0). n = 2 gives us 1 tick, and we're further from the lower bound, so we know that we have to go the other way. n = 0 gives us 6 ticks, at each integer point point. n = -1 gives us 12 ticks (0, -0.5, ..., -5.0). n = -2 gives us 24 ticks, and so on. The scoring algorithm will give them each a score - higher means a better method.</p>\n\n<p>Do this again for the i * 5 * 10^n, and i*2*10^n, and take the one with the best score.</p>\n\n<p>(as an example scoring algorithm, say that the score is the distance to the last tick times the maximum number of ticks minus the number needed. This will likely be bad, but it'll serve as a decent starting point).</p>\n" }, { "answer_id": 239164, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 1, "selected": false, "text": "<p>I've been using the jQuery <a href=\"https://github.com/flot/flot/blob/master/API.md\" rel=\"nofollow noreferrer\">flot</a> graph library. It's open source and does axis/tick generation quite well. I'd suggest looking at it's code and pinching some ideas from there.</p>\n" }, { "answer_id": 42593802, "author": "Giorgio Barchiesi", "author_id": 681877, "author_profile": "https://Stackoverflow.com/users/681877", "pm_score": 1, "selected": false, "text": "<p>This simple algorithm yields an interval that is multiple of 1, 2, or 5 times a power of 10. And the axis range gets divided in at least 5 intervals. The code sample is in java language:</p>\n\n<pre><code>protected double calculateInterval(double range) {\n double x = Math.pow(10.0, Math.floor(Math.log10(range)));\n if (range / x &gt;= 5)\n return x;\n else if (range / (x / 2.0) &gt;= 5)\n return x / 2.0;\n else\n return x / 5.0;\n}\n</code></pre>\n\n<p>This is an alternative, for minimum 10 intervals:</p>\n\n<pre><code>protected double calculateInterval(double range) {\n double x = Math.pow(10.0, Math.floor(Math.log10(range)));\n if (range / (x / 2.0) &gt;= 10)\n return x / 2.0;\n else if (range / (x / 5.0) &gt;= 10)\n return x / 5.0;\n else\n return x / 10.0;\n}\n</code></pre>\n" }, { "answer_id": 49911176, "author": "Andrew", "author_id": 2321042, "author_profile": "https://Stackoverflow.com/users/2321042", "pm_score": 4, "selected": false, "text": "<p>As I didn't like any of the solutions I've found so far, I implemented my own. It's in C# but it can be easily translated into any other language.</p>\n\n<p>It basically chooses from a list of possible steps the smallest one that displays all values, <strong>without leaving any value exactly in the edge</strong>, lets you easily select which possible steps you want to use (without having to edit ugly <code>if-else if</code> blocks), and supports any range of values. I used a C# <code>Tuple</code> to return three values just for a quick and simple demonstration.</p>\n\n<pre><code>private static Tuple&lt;decimal, decimal, decimal&gt; GetScaleDetails(decimal min, decimal max)\n{\n // Minimal increment to avoid round extreme values to be on the edge of the chart\n decimal epsilon = (max - min) / 1e6m;\n max += epsilon;\n min -= epsilon;\n decimal range = max - min;\n\n // Target number of values to be displayed on the Y axis (it may be less)\n int stepCount = 20;\n // First approximation\n decimal roughStep = range / (stepCount - 1);\n\n // Set best step for the range\n decimal[] goodNormalizedSteps = { 1, 1.5m, 2, 2.5m, 5, 7.5m, 10 }; // keep the 10 at the end\n // Or use these if you prefer: { 1, 2, 5, 10 };\n\n // Normalize rough step to find the normalized one that fits best\n decimal stepPower = (decimal)Math.Pow(10, -Math.Floor(Math.Log10((double)Math.Abs(roughStep))));\n var normalizedStep = roughStep * stepPower;\n var goodNormalizedStep = goodNormalizedSteps.First(n =&gt; n &gt;= normalizedStep);\n decimal step = goodNormalizedStep / stepPower;\n\n // Determine the scale limits based on the chosen step.\n decimal scaleMax = Math.Ceiling(max / step) * step;\n decimal scaleMin = Math.Floor(min / step) * step;\n\n return new Tuple&lt;decimal, decimal, decimal&gt;(scaleMin, scaleMax, step);\n}\n\nstatic void Main()\n{\n // Dummy code to show a usage example.\n var minimumValue = data.Min();\n var maximumValue = data.Max();\n var results = GetScaleDetails(minimumValue, maximumValue);\n chart.YAxis.MinValue = results.Item1;\n chart.YAxis.MaxValue = results.Item2;\n chart.YAxis.Step = results.Item3;\n}\n</code></pre>\n" }, { "answer_id": 73313693, "author": "Gregor Watters Härtl", "author_id": 18413363, "author_profile": "https://Stackoverflow.com/users/18413363", "pm_score": 2, "selected": false, "text": "<p>Funnily enough, just over a week ago I came here looking for an answer to the same question, but went away again and decided to come up with my own algorithm. I am here to share, in case it is of any use.</p>\n<p>I wrote the code in Python to try and bust out a solution as quickly as possible, but it can easily be ported to any other language.</p>\n<p>The function below calculates the appropriate interval (which I have allowed to be either <code>10**n</code>, <code>2*10**n</code>, <code>4*10**n</code> or <code>5*10**n</code>) for a given range of data, and then calculates the locations at which to place the ticks (based on which numbers within the range are divisble by the interval). I have not used the modulo <code>%</code> operator, since it does not work properly with floating-point numbers due to floating-point arithmetic rounding errors.</p>\n<p>Code:</p>\n<pre><code>import math\n\n\ndef get_tick_positions(data: list):\n if len(data) == 0:\n return []\n retpoints = []\n data_range = max(data) - min(data)\n lower_bound = min(data) - data_range/10\n upper_bound = max(data) + data_range/10\n view_range = upper_bound - lower_bound\n num = lower_bound\n n = math.floor(math.log10(view_range) - 1)\n interval = 10**n\n num_ticks = 1\n while num &lt;= upper_bound:\n num += interval\n num_ticks += 1\n if num_ticks &gt; 10:\n if interval == 10 ** n:\n interval = 2 * 10 ** n\n elif interval == 2 * 10 ** n:\n interval = 4 * 10 ** n\n elif interval == 4 * 10 ** n:\n interval = 5 * 10 ** n\n else:\n n += 1\n interval = 10 ** n\n num = lower_bound\n num_ticks = 1\n if view_range &gt;= 10:\n copy_interval = interval\n else:\n if interval == 10 ** n:\n copy_interval = 1\n elif interval == 2 * 10 ** n:\n copy_interval = 2\n elif interval == 4 * 10 ** n:\n copy_interval = 4\n else:\n copy_interval = 5\n first_val = 0\n prev_val = 0\n times = 0\n temp_log = math.log10(interval)\n if math.isclose(lower_bound, 0):\n first_val = 0\n elif lower_bound &lt; 0:\n if upper_bound &lt; -2*interval:\n if n &lt; 0:\n copy_ub = round(upper_bound*10**(abs(temp_log) + 1))\n times = copy_ub // round(interval*10**(abs(temp_log) + 1)) + 2\n else:\n times = upper_bound // round(interval) + 2\n while first_val &gt;= lower_bound:\n prev_val = first_val\n first_val = times * copy_interval\n if n &lt; 0:\n first_val *= (10**n)\n times -= 1\n first_val = prev_val\n times += 3\n else:\n if lower_bound &gt; 2*interval:\n if n &lt; 0:\n copy_ub = round(lower_bound*10**(abs(temp_log) + 1))\n times = copy_ub // round(interval*10**(abs(temp_log) + 1)) - 2\n else:\n times = lower_bound // round(interval) - 2\n while first_val &lt; lower_bound:\n first_val = times*copy_interval\n if n &lt; 0:\n first_val *= (10**n)\n times += 1\n if n &lt; 0:\n retpoints.append(first_val)\n else:\n retpoints.append(round(first_val))\n val = first_val\n times = 1\n while val &lt;= upper_bound:\n val = first_val + times * interval\n if n &lt; 0:\n retpoints.append(val)\n else:\n retpoints.append(round(val))\n times += 1\n retpoints.pop()\n return retpoints\n</code></pre>\n<p>When passing in the following three data-points to the function</p>\n<p><code>points = [-0.00493, -0.0003892, -0.00003292]</code></p>\n<p>... the output I get (as a list) is as follows:</p>\n<p><code>[-0.005, -0.004, -0.003, -0.002, -0.001, 0.0]</code></p>\n<p>When passing this:</p>\n<p><code>points = [1.399, 38.23823, 8309.33, 112990.12]</code></p>\n<p>... I get:</p>\n<p><code>[0, 20000, 40000, 60000, 80000, 100000, 120000]</code></p>\n<p>When passing this:</p>\n<p><code>points = [-54, -32, -19, -17, -13, -11, -8, -4, 12, 15, 68]</code></p>\n<p>... I get:</p>\n<p><code>[-60, -40, -20, 0, 20, 40, 60, 80]</code></p>\n<p>... which all seem to be a decent choice of positions for placing ticks.</p>\n<p>The function is written to allow 5-10 ticks, but that could easily be changed if you so please.</p>\n<p>Whether the list of data supplied contains ordered or unordered data it does not matter, since it is only the minimum and maximum data points within the list that matter.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
I'm looking for an algorithm that places tick marks on an axis, given a range to display, a width to display it in, and a function to measure a string width for a tick mark. For example, given that I need to display between 1e-6 and 5e-6 and a width to display in pixels, the algorithm would determine that I should put tickmarks (for example) at 1e-6, 2e-6, 3e-6, 4e-6, and 5e-6. Given a smaller width, it might decide that the optimal placement is only at the even positions, i.e. 2e-6 and 4e-6 (since putting more tickmarks would cause them to overlap). A smart algorithm would give preference to tickmarks at multiples of 10, 5, and 2. Also, a smart algorithm would be symmetric around zero.
As I didn't like any of the solutions I've found so far, I implemented my own. It's in C# but it can be easily translated into any other language. It basically chooses from a list of possible steps the smallest one that displays all values, **without leaving any value exactly in the edge**, lets you easily select which possible steps you want to use (without having to edit ugly `if-else if` blocks), and supports any range of values. I used a C# `Tuple` to return three values just for a quick and simple demonstration. ``` private static Tuple<decimal, decimal, decimal> GetScaleDetails(decimal min, decimal max) { // Minimal increment to avoid round extreme values to be on the edge of the chart decimal epsilon = (max - min) / 1e6m; max += epsilon; min -= epsilon; decimal range = max - min; // Target number of values to be displayed on the Y axis (it may be less) int stepCount = 20; // First approximation decimal roughStep = range / (stepCount - 1); // Set best step for the range decimal[] goodNormalizedSteps = { 1, 1.5m, 2, 2.5m, 5, 7.5m, 10 }; // keep the 10 at the end // Or use these if you prefer: { 1, 2, 5, 10 }; // Normalize rough step to find the normalized one that fits best decimal stepPower = (decimal)Math.Pow(10, -Math.Floor(Math.Log10((double)Math.Abs(roughStep)))); var normalizedStep = roughStep * stepPower; var goodNormalizedStep = goodNormalizedSteps.First(n => n >= normalizedStep); decimal step = goodNormalizedStep / stepPower; // Determine the scale limits based on the chosen step. decimal scaleMax = Math.Ceiling(max / step) * step; decimal scaleMin = Math.Floor(min / step) * step; return new Tuple<decimal, decimal, decimal>(scaleMin, scaleMax, step); } static void Main() { // Dummy code to show a usage example. var minimumValue = data.Min(); var maximumValue = data.Max(); var results = GetScaleDetails(minimumValue, maximumValue); chart.YAxis.MinValue = results.Item1; chart.YAxis.MaxValue = results.Item2; chart.YAxis.Step = results.Item3; } ```
237,222
<p>This code:</p> <pre><code>public class WidgetPlatform { public Widget LeftmostWidget { get; set; } public Widget RightmostWidget { get; set; } public String GetWidgetNames() { return LeftmostWidget.Name + " " + RightmostWidget.Name; } } </code></pre> <p>doesn't contain any repetition worth worrying about, but it isn't particularly robust. Because the Widgets aren't null-checked, we're leaving an opening for a bug. We could do a null check, but that feels like work. Here's what I really want:</p> <pre><code>public class WidgetPlatform { [Required] public Widget LeftmostWidget { get; set; } [Required] public Widget RightmostWidget { get; set; } public String GetWidgetNames() { return LeftmostWidget.Name + " " + RightmostWidget.Name; } } </code></pre> <p>Ideally, it would cause a compile error (the best sort of error) if the object was instantiated without setting the Widgets, but that seems like a tall order. Is there a way to make this syntax work that at least throws an error on instantiation? There's a (relatively) obvious way to do it with reflection if all of the null-checked objects inherit from the same type, but without multiple inheritance that will get ugly pretty fast.</p>
[ { "answer_id": 237248, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": false, "text": "<p>Whats wrong with Constructors ?</p>\n\n<pre><code>public class WidgetPlatform\n{\n public Widget LeftmostWidget { get; set; }\n public Widget RightmostWidget { get; set; }\n\n public WidgetPlatform()\n {\n this.LeftMostWidget = new Widget();\n this.RightMostWidget = new Widget();\n }\n\n public WidgetPlatform(Widget left, Widget right)\n {\n if(left == null || right == null)\n throw new ArgumentNullException(\"Eeep!\");\n\n this.LeftMostWidget = left;\n this.RightMostWidget = right;\n }\n\n\n public String GetWidgetNames()\n {\n return LeftmostWidget.Name + \" \" + RightmostWidget.Name;\n }\n}\n</code></pre>\n" }, { "answer_id": 237442, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 0, "selected": false, "text": "<p>There is a school of thought that it is best to encapsulate your constructors, and it seems that it would be approperiate here. reference:</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0321509366\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Emergent-Design-Evolutionary-Professional-Development/dp/0321509366</a></p>\n\n<p>You might consider:</p>\n\n<pre><code>public class WidgetPlatform\n {\n /// &lt;summary&gt;\n /// Hide the constructor.\n /// &lt;/summary&gt;\n private WidgetPlatform(Widget left, Widget right)\n {\n this.LeftmostWidget = left;\n this.RightmostWidget = right;\n }\n\n public Widget LeftmostWidget\n {\n get;\n private set;\n }\n\n public Widget RightmostWidget\n {\n get;\n private set;\n }\n\n public static WidgetPlatform GetInstance(Widget left, Widget right)\n {\n return new WidgetPlatform(left, right);\n }\n }\n</code></pre>\n\n<p>In GetInstance you can check for null, and decide what to do about it, or not ... you have lots of options at this point.</p>\n\n<p>Hope that helps ...</p>\n" }, { "answer_id": 237478, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<pre><code>public class WidgetPlatform\n{\n public Widget LeftWidget\n {\n get;\n private set;\n }\n\n public Widget RightWidget\n {\n get;\n private set;\n }\n\n WidgetPlatForm(Widget w1, Widget w2)\n {\n if (w1 == null || w2 == null)\n throw new ArgumentException();\n\n this.LeftWidget = w1;\n this.RightWidget = w2; \n }\n\n // Etc\n}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30761/" ]
This code: ``` public class WidgetPlatform { public Widget LeftmostWidget { get; set; } public Widget RightmostWidget { get; set; } public String GetWidgetNames() { return LeftmostWidget.Name + " " + RightmostWidget.Name; } } ``` doesn't contain any repetition worth worrying about, but it isn't particularly robust. Because the Widgets aren't null-checked, we're leaving an opening for a bug. We could do a null check, but that feels like work. Here's what I really want: ``` public class WidgetPlatform { [Required] public Widget LeftmostWidget { get; set; } [Required] public Widget RightmostWidget { get; set; } public String GetWidgetNames() { return LeftmostWidget.Name + " " + RightmostWidget.Name; } } ``` Ideally, it would cause a compile error (the best sort of error) if the object was instantiated without setting the Widgets, but that seems like a tall order. Is there a way to make this syntax work that at least throws an error on instantiation? There's a (relatively) obvious way to do it with reflection if all of the null-checked objects inherit from the same type, but without multiple inheritance that will get ugly pretty fast.
Whats wrong with Constructors ? ``` public class WidgetPlatform { public Widget LeftmostWidget { get; set; } public Widget RightmostWidget { get; set; } public WidgetPlatform() { this.LeftMostWidget = new Widget(); this.RightMostWidget = new Widget(); } public WidgetPlatform(Widget left, Widget right) { if(left == null || right == null) throw new ArgumentNullException("Eeep!"); this.LeftMostWidget = left; this.RightMostWidget = right; } public String GetWidgetNames() { return LeftmostWidget.Name + " " + RightmostWidget.Name; } } ```
237,235
<p>In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the url.</p> <pre><code>t = loader.get_template("sometemplate") c = Context({ 'foo': 'bar', 'url': 'http://127.0.0.1/test?a=1&amp;b=2', }) print t.render(c) </code></pre> <p>After rendering it produces: <code>http://127.0.0.1/test?a=1&amp;amp;amp;b=2</code></p> <p>Note the ampersand is HTML encoded as "&amp;amp;". One way around the problem is to pass each parameter separately to my template and construct the url in the template, however I'd like to avoid doing that.</p> <p>Is there a way to disable HTML encoding of context parameters or at the very least avoid encoding of ampersands?</p>
[ { "answer_id": 237243, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": true, "text": "<p>To turn it off for a single variable, use <code>mark_safe</code>:</p>\n\n<pre><code>from django.utils.safestring import mark_safe\n\nt = loader.get_template(\"sometemplate\")\nc = Context({\n 'foo': 'bar',\n 'url': mark_safe('http://127.0.0.1/test?a=1&amp;b=2'),\n})\nprint t.render(c)\n</code></pre>\n\n<p>Alternatively, to totally turn autoescaping off from your Python code, <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#auto-escaping-considerations\" rel=\"noreferrer\">use the <code>autoescape</code> argument when initialising a <code>Context</code></a>:</p>\n\n<pre><code>c = Context({\n 'foo': 'bar',\n 'url': 'http://127.0.0.1/test?a=1&amp;b=2',\n}, autoescape=False)\n</code></pre>\n\n<p>The <a href=\"http://docs.djangoproject.com/en/dev/topics/templates/#how-to-turn-it-off\" rel=\"noreferrer\">How to turn [Automatic HTML escaping] off</a> section of the documentation covers some of the in-template options if you'd rather do it there.</p>\n" }, { "answer_id": 237443, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 3, "selected": false, "text": "<p>Or just use the \"safe\" filter in your template.</p>\n\n<p>Also, I cannot stress enough how important it is to be familiar with Django's documentation; many common questions like this have easy-to-find answers and explanations (<a href=\"http://docs.djangoproject.com/en/dev/topics/templates/#id2\" rel=\"noreferrer\">like this one</a>), and reading through the docs and getting a feel for how everything works will drastically decrease the amount of time you need to spend ask \"why did it do that\" and increase the amount of time you spend building things that work the way you want.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26592/" ]
In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the url. ``` t = loader.get_template("sometemplate") c = Context({ 'foo': 'bar', 'url': 'http://127.0.0.1/test?a=1&b=2', }) print t.render(c) ``` After rendering it produces: `http://127.0.0.1/test?a=1&amp;amp;b=2` Note the ampersand is HTML encoded as "&amp;". One way around the problem is to pass each parameter separately to my template and construct the url in the template, however I'd like to avoid doing that. Is there a way to disable HTML encoding of context parameters or at the very least avoid encoding of ampersands?
To turn it off for a single variable, use `mark_safe`: ``` from django.utils.safestring import mark_safe t = loader.get_template("sometemplate") c = Context({ 'foo': 'bar', 'url': mark_safe('http://127.0.0.1/test?a=1&b=2'), }) print t.render(c) ``` Alternatively, to totally turn autoescaping off from your Python code, [use the `autoescape` argument when initialising a `Context`](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#auto-escaping-considerations): ``` c = Context({ 'foo': 'bar', 'url': 'http://127.0.0.1/test?a=1&b=2', }, autoescape=False) ``` The [How to turn [Automatic HTML escaping] off](http://docs.djangoproject.com/en/dev/topics/templates/#how-to-turn-it-off) section of the documentation covers some of the in-template options if you'd rather do it there.
237,254
<p>The <a href="http://docs.jquery.com/Events/bind#typedatafn" rel="noreferrer">jQuery documentation</a> says the library has built-in support for the following events: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and error.</p> <p>I need to handle cut, copy, and paste events. How best to do that? FWIW, I only need to worry about WebKit (lucky me!).</p> <p>UPDATE: I'm working on a "widget" in a Dashboard-like environment. It uses WebKit, so it only really matters (for my purposes) whether these events are supported there, which it looks like they are.</p>
[ { "answer_id": 237303, "author": "dansays", "author_id": 1923, "author_profile": "https://Stackoverflow.com/users/1923", "pm_score": 4, "selected": false, "text": "<p>Various clipboard events are available in Javascript, though support is spotty. QuicksMode.org has a <a href=\"http://www.quirksmode.org/dom/events/cutcopypaste.html\" rel=\"noreferrer\">compatibility grid</a> and <a href=\"http://www.quirksmode.org/dom/events/tests/cutcopypaste.html\" rel=\"noreferrer\">test page</a>. The events are not exposed through jQuery, so you'll either have to extend the library or use native Javascript events. </p>\n" }, { "answer_id": 238835, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 8, "selected": true, "text": "<p>You can add and remove events of any kind by using the <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\"><code>.on()</code></a> and <a href=\"http://api.jquery.com/off\" rel=\"noreferrer\"><code>off()</code></a> methods</p>\n\n<p>Try this, for instance</p>\n\n<pre><code>jQuery(document).on('paste', function(e){ alert('pasting!') });\n</code></pre>\n\n<p>jQuery is actually quite indifferent to whether the event type you assign is supported by the browser, so you can assign arbitrary event types to elements (and general objects) such as:</p>\n\n<pre><code>jQuery('p').on('foobar2000', function(e){ alert(e.type); });\n</code></pre>\n\n<p>In case of custom event types, you must <a href=\"http://api.jquery.com/trigger\" rel=\"noreferrer\"><code>.trigger()</code></a> them \"manually\" in your code, like this:</p>\n\n<pre><code>jQuery('p').trigger('foobar2000');\n</code></pre>\n\n<p>Neat eh?</p>\n\n<p>Furthermore, to work with proprietary/custom DOM events in a cross-browser compatible way, you may need to use/write an \"jQuery event plugin\" ... example of which may be seen in <del><a href=\"http://plugins.jquery.com/files/jquery.event.wheel.js.txt\" rel=\"noreferrer\">jquery.event.wheel.js</a></del> Brandon Aaron's <a href=\"https://github.com/brandonaaron/jquery-mousewheel\" rel=\"noreferrer\">Mousewheel plugin</a></p>\n" }, { "answer_id": 241158, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 3, "selected": false, "text": "<p>Mozilla supports an \"input\" event which I'm having trouble finding useful documentation for. At the very least, I know it fires on paste.</p>\n\n<pre><code> this.addEventListener('input',\n function(){//stuff here},\n false\n );\n</code></pre>\n" }, { "answer_id": 32357998, "author": "Yan Pak", "author_id": 1068013, "author_profile": "https://Stackoverflow.com/users/1068013", "pm_score": 1, "selected": false, "text": "<p>As jQuery 1.7 you can use <strong>bind(...)</strong> and <strong>unbind(...)</strong> methods for attaching and removing respectively handlers.</p>\n\n<p>Here are examples align your questuion:</p>\n\n<pre><code>$('#someElementId').bind('paste', function(){return false;});\n</code></pre>\n\n<p>- this one will block any attempts to paste from clipboard into element body. You can use also <strong>cut</strong>, <strong>copy</strong> and others as event types (see links bellow)</p>\n\n<pre><code>$('#someElementId').bind('copy', function(){return alert('Hey fella! Do not forget about copyrights!');});\n</code></pre>\n\n<p>So, in other cases, when you want to remove those handlers, you can use <strong>unbind()</strong> method:</p>\n\n<pre><code>$('#someElementId').unbind('copy');\n</code></pre>\n\n<p>Here some useful links:</p>\n\n<ul>\n<li><a href=\"http://api.jquery.com/bind/\" rel=\"nofollow\">bind()</a></li>\n<li><a href=\"http://api.jquery.com/unbind/\" rel=\"nofollow\">unbind()</a></li>\n<li><a href=\"http://api.jquery.com/category/events/\" rel=\"nofollow\">full list of event types</a></li>\n</ul>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
The [jQuery documentation](http://docs.jquery.com/Events/bind#typedatafn) says the library has built-in support for the following events: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and error. I need to handle cut, copy, and paste events. How best to do that? FWIW, I only need to worry about WebKit (lucky me!). UPDATE: I'm working on a "widget" in a Dashboard-like environment. It uses WebKit, so it only really matters (for my purposes) whether these events are supported there, which it looks like they are.
You can add and remove events of any kind by using the [`.on()`](http://api.jquery.com/on/) and [`off()`](http://api.jquery.com/off) methods Try this, for instance ``` jQuery(document).on('paste', function(e){ alert('pasting!') }); ``` jQuery is actually quite indifferent to whether the event type you assign is supported by the browser, so you can assign arbitrary event types to elements (and general objects) such as: ``` jQuery('p').on('foobar2000', function(e){ alert(e.type); }); ``` In case of custom event types, you must [`.trigger()`](http://api.jquery.com/trigger) them "manually" in your code, like this: ``` jQuery('p').trigger('foobar2000'); ``` Neat eh? Furthermore, to work with proprietary/custom DOM events in a cross-browser compatible way, you may need to use/write an "jQuery event plugin" ... example of which may be seen in ~~[jquery.event.wheel.js](http://plugins.jquery.com/files/jquery.event.wheel.js.txt)~~ Brandon Aaron's [Mousewheel plugin](https://github.com/brandonaaron/jquery-mousewheel)
237,268
<p>Doing like so:</p> <p><code>Shell ("C:\Program Files\Internet Explorer\iexplore.exe -embedding http://www.websiteurl.com")</code></p> <p>Doesn't work how I need it as I essentially need it to be able to redirect and prompt a user to download a file. Any ideas?</p>
[ { "answer_id": 237271, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "<p>There are a couple of things you could do. </p>\n\n<ul>\n<li><p>Use an external program like <code>wget</code> to get the file instead of IE. You can get wget for free at <a href=\"http://www.cygwin.com\" rel=\"nofollow noreferrer\">http://www.cygwin.com</a> with the cygnus tools. It's GPL, so just watch out if you have a commercial product. </p></li>\n<li><p>Write a little .NET program that uses the HttpWebRequest class to get the file and shell out to that program instead of IE. I don't think you're going to have a lot of luck shelling out to IE itself. Sounds like a, to paraphrase Steve Jobs, \"bag of hurt\".</p></li>\n</ul>\n" }, { "answer_id": 237274, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>If all you are trying to do is download a file, you can use <a href=\"http://vbnet.mvps.org/index.html?code/internet/urldownloadtofile.htm\" rel=\"nofollow noreferrer\">URLDownloadToFile</a>.</p>\n" }, { "answer_id": 237962, "author": "smbarbour", "author_id": 29115, "author_profile": "https://Stackoverflow.com/users/29115", "pm_score": 0, "selected": false, "text": "<p>The Internet Explorer interface is exposed to ActiveX via the WebBrowser control (contained in %systemroot%\\system32\\shlwapi.dll). While it may not be very elegant, you could easily place the control somewhere off the visible area of the form.</p>\n\n<p>The control is very simple to use.</p>\n" }, { "answer_id": 239355, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Your best bet is creating separate download application using some .NET http object in order to download the file.\nI'd recommend WebClient.</p>\n\n<p>If you really gotta stick to VB6, I'm sure you can use some basic socket work in order to download the file directly.</p>\n" }, { "answer_id": 239493, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<p>Internet Explorer exposes a COM accessible interface you can use. If you really have to. I'd recommend against it - its comparatively slow, error-prone, cumbersome and resource-intensive. </p>\n\n<p>What solves your problem more elegantly is using <code>WinHTTPRequest</code>. In your Project, reference \"Microsoft WinHTTP Services, version 5.1\", and then go on like this:</p>\n\n<pre><code>Dim HttpRequest As New WinHttp.WinHttpRequest\nDim TargetUrl As String\nDim TargetFile As String\nDim FileNum As Integer\n\nTargetFile = \"C:\\foo.doc\"\n\nTargetUrl = \"http://www.websiteurl.com\"\nHttpRequest.Open Method:=\"GET\", Url:=TargetUrl, Async:=False\nHttpRequest.Send\n\nIf HttpRequest.Status = 302 Then\n\n TargetUrl = HttpRequest.GetResponseHeader(\"Location\")\n HttpRequest.Open Method:=\"GET\", Url:=TargetUrl, Async:=False\n HttpRequest.Send\n\n If HttpRequest.Status = \"200\" Then\n\n FileNum = FreeFile\n Open TargetFile For Binary As #FileNum\n Put #FileNum, 1, HttpRequest.ResponseBody\n Close FileNum \n\n Debug.Print \"Successfully witten \" &amp; TargetFile\n Else\n Debug.Print \"Download failed. Received HTTP status: \" &amp; HttpRequest.Status\n End If\nElse\n Debug.Print \"Expected Redirect. Received HTTP status: \" &amp; HttpRequest.Status\nEnd If\n</code></pre>\n\n<p>Hard-coding <code>\"C:\\foo.doc\"</code> does of course not make much sense. I'd use the file name the server supplies in the response headers (<code>\"Content-Type\"</code> or <code>\"Content-Disposition\"</code>, depending on what you expect).</p>\n" }, { "answer_id": 244273, "author": "MarkJ", "author_id": 15639, "author_profile": "https://Stackoverflow.com/users/15639", "pm_score": 0, "selected": false, "text": "<p>Another option besides the <a href=\"http://vbnet.mvps.org/index.html?code/internet/urldownloadtofile.htm\" rel=\"nofollow noreferrer\">URLDownloadToFile</a> API call suggested by Glomek is to use the <a href=\"http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2560\" rel=\"nofollow noreferrer\">AsyncRead</a> method built into VB6.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Doing like so: `Shell ("C:\Program Files\Internet Explorer\iexplore.exe -embedding http://www.websiteurl.com")` Doesn't work how I need it as I essentially need it to be able to redirect and prompt a user to download a file. Any ideas?
Internet Explorer exposes a COM accessible interface you can use. If you really have to. I'd recommend against it - its comparatively slow, error-prone, cumbersome and resource-intensive. What solves your problem more elegantly is using `WinHTTPRequest`. In your Project, reference "Microsoft WinHTTP Services, version 5.1", and then go on like this: ``` Dim HttpRequest As New WinHttp.WinHttpRequest Dim TargetUrl As String Dim TargetFile As String Dim FileNum As Integer TargetFile = "C:\foo.doc" TargetUrl = "http://www.websiteurl.com" HttpRequest.Open Method:="GET", Url:=TargetUrl, Async:=False HttpRequest.Send If HttpRequest.Status = 302 Then TargetUrl = HttpRequest.GetResponseHeader("Location") HttpRequest.Open Method:="GET", Url:=TargetUrl, Async:=False HttpRequest.Send If HttpRequest.Status = "200" Then FileNum = FreeFile Open TargetFile For Binary As #FileNum Put #FileNum, 1, HttpRequest.ResponseBody Close FileNum Debug.Print "Successfully witten " & TargetFile Else Debug.Print "Download failed. Received HTTP status: " & HttpRequest.Status End If Else Debug.Print "Expected Redirect. Received HTTP status: " & HttpRequest.Status End If ``` Hard-coding `"C:\foo.doc"` does of course not make much sense. I'd use the file name the server supplies in the response headers (`"Content-Type"` or `"Content-Disposition"`, depending on what you expect).
237,269
<p>I am thinking of running this custom targets to find out more about my project build status - jalopy - jdepend - cvs tagdiff report - custom task for NoUnit - generate UML diagram. ESS-Model</p> <p>What are your views?</p>
[ { "answer_id": 240701, "author": "jim", "author_id": 27628, "author_profile": "https://Stackoverflow.com/users/27628", "pm_score": 1, "selected": false, "text": "<p>I think that it's a great idea and use it myself. That way I'll never forget to run it.</p>\n\n<p>I also keep the reports for a decent amount of time and eventually create a spreadsheet of \"progress\".</p>\n\n<p>In your main ant task - call another task to do \"whatever\"\n </p>\n\n<p>and\nJDepend.xml ...</p>\n\n<p>\n\n \n \n \n </p>\n\n<pre><code>&lt;target name=\"statsAll\"&gt;\n &lt;!-- master file that describes where everything is --&gt;\n &lt;property file=\"./ant/ant-global.properties\" prefix=\"ant-global\" /&gt;\n &lt;tstamp&gt;\n &lt;format property=\"gen.time\" pattern=\"yyyyMMdd_hh\"/&gt;\n &lt;/tstamp&gt;\n &lt;echo message=\"LOG:./ant/logs/jdepend.${version.FILETAG}.${gen.time}.rpt\"/&gt;\n &lt;!-- generate stats to see if we're improving --&gt;\n &lt;jdepend \n outputfile=\"./ant/logs/jdepend.${version.FILETAG}.${gen.time}.rpt\" &gt;\n &lt;exclude name=\"java.*\"/&gt;\n &lt;exclude name=\"javax.*\"/&gt;\n &lt;classespath&gt;\n &lt;pathelement location=\"./jar\" /&gt;\n &lt;/classespath&gt;\n &lt;classpath location=\"./jar\" /&gt;\n &lt;/jdepend&gt;\n&lt;/target&gt;\n\n&lt;target name=\"doJDepend\" depends=\"getVersion,statsAll\"&gt;\n &lt;echo message=\"FTP'ing report\"/&gt;\n &lt;ftp verbose=\"yes\" passive=\"yes\" depends=\"yes\"\n remotedir=\"/videojet/metrics\" server=\"xxxxx\"\n userid=\"xxxx\" password=\"xxxxx\"\n binary=\"no\"\n systemTypeKey=\"UNIX\"&gt;\n &lt;fileset dir=\"./ant/logs/\" casesensitive=\"no\"&gt;\n &lt;include name=\"**/jdepend.${version.FILETAG}*.rpt\"/&gt;\n &lt;exclude name=\"**/*.txt\"/&gt;\n &lt;/fileset&gt;\n &lt;/ftp&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p></p>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/000149.html\" rel=\"nofollow noreferrer\">Magic build machine</a></p>\n" }, { "answer_id": 240950, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 0, "selected": false, "text": "<p>I second the 'good idea' part, although for a project of reasonable size you might want to make it part of an automated build, like one of the CI Servers (Bamboo, Contiuum).</p>\n\n<p>You might also consider a code coverage tool to see how your test coverage is going. </p>\n\n<p>This will ensure the reports get run on a regular basis, could give you somewhere to publish them and won't slow down the developer's quick turnaround development cycle.</p>\n" }, { "answer_id": 489604, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 0, "selected": false, "text": "<p>I also think some reports about your project are a good idea. My template-project for an ant-build-script (<a href=\"http://antiplate.origo.ethz.ch/\" rel=\"nofollow noreferrer\">Antiplate</a>) has at the moment the following reports: Junitreport, emma-report, PMD, CPD and Checkstyle. I'm thinking about including a JDepend-report.</p>\n\n<p>At work we use these templates and using Hudson as continuous-integration-system. Hudson creates wonderful graphs for these reports and how the measures changed with the builds.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am thinking of running this custom targets to find out more about my project build status - jalopy - jdepend - cvs tagdiff report - custom task for NoUnit - generate UML diagram. ESS-Model What are your views?
I think that it's a great idea and use it myself. That way I'll never forget to run it. I also keep the reports for a decent amount of time and eventually create a spreadsheet of "progress". In your main ant task - call another task to do "whatever" and JDepend.xml ... ``` <target name="statsAll"> <!-- master file that describes where everything is --> <property file="./ant/ant-global.properties" prefix="ant-global" /> <tstamp> <format property="gen.time" pattern="yyyyMMdd_hh"/> </tstamp> <echo message="LOG:./ant/logs/jdepend.${version.FILETAG}.${gen.time}.rpt"/> <!-- generate stats to see if we're improving --> <jdepend outputfile="./ant/logs/jdepend.${version.FILETAG}.${gen.time}.rpt" > <exclude name="java.*"/> <exclude name="javax.*"/> <classespath> <pathelement location="./jar" /> </classespath> <classpath location="./jar" /> </jdepend> </target> <target name="doJDepend" depends="getVersion,statsAll"> <echo message="FTP'ing report"/> <ftp verbose="yes" passive="yes" depends="yes" remotedir="/videojet/metrics" server="xxxxx" userid="xxxx" password="xxxxx" binary="no" systemTypeKey="UNIX"> <fileset dir="./ant/logs/" casesensitive="no"> <include name="**/jdepend.${version.FILETAG}*.rpt"/> <exclude name="**/*.txt"/> </fileset> </ftp> </target> ``` [Magic build machine](http://www.codinghorror.com/blog/archives/000149.html)
237,275
<p>I'm constructing a method to take in an ArrayList(presumably full of objects) and then list all the fields(and their values) for each object in the ArrayList.</p> <p>Currently my code is as follows:</p> <pre><code>public static void ListArrayListMembers(ArrayList list) { foreach (Object obj in list) { Type type = obj.GetType(); string field = type.GetFields().ToString(); Console.WriteLine(field); } } </code></pre> <p>Of course, I understand the immediate issue with this code: if it worked it'd only print one field per object in the ArrayList. I'll fix this later - right now I'm just curious how to get all of the public fields associated with an object.</p>
[ { "answer_id": 237278, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 6, "selected": true, "text": "<pre><code>foreach (Object obj in list) {\n Type type = obj.GetType();\n\n foreach (var f in type.GetFields().Where(f =&gt; f.IsPublic)) {\n Console.WriteLine(\n String.Format(\"Name: {0} Value: {1}\", f.Name, f.GetValue(obj));\n } \n}\n</code></pre>\n\n<p>Note that this code requires .NET 3.5 to work ;-)</p>\n" }, { "answer_id": 237292, "author": "nyxtom", "author_id": 19753, "author_profile": "https://Stackoverflow.com/users/19753", "pm_score": 2, "selected": false, "text": "<pre><code>public static void ListArrayListMembers(ArrayList list)\n{\n foreach (Object obj in list)\n {\n Type type = obj.GetType();\n Console.WriteLine(\"{0} -- \", type.Name);\n Console.WriteLine(\" Properties: \");\n foreach (PropertyInfo prop in type.GetProperties())\n {\n Console.WriteLine(\"\\t{0} {1} = {2}\", prop.PropertyType.Name, \n prop.Name, prop.GetValue(obj, null));\n }\n Console.WriteLine(\" Fields: \");\n foreach (FieldInfo field in type.GetFields())\n {\n Console.WriteLine(\"\\t{0} {1} = {2}\", field.FieldType.Name, \n field.Name, field.GetValue(obj));\n }\n }\n}\n</code></pre>\n\n<p>I'd like to mention that looking for IsPublic in the fields is not necessary as type.GetFields() as defined by <a href=\"http://msdn.microsoft.com/en-us/library/ch9714z3.aspx\" rel=\"noreferrer\">MSDN</a> states:</p>\n\n<p>Return Value - \nType: System.Reflection.FieldInfo[]</p>\n\n<p>An array of FieldInfo objects representing all the <strong>public fields</strong> defined for the current Type.</p>\n" }, { "answer_id": 237295, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 1, "selected": false, "text": "<pre><code> static void ListArrayListMembers(ArrayList list)\n {\n foreach (object obj in list)\n {\n Type type = obj.GetType();\n foreach (FieldInfo field in type.GetFields(BindingFlags.Public))\n {\n Console.WriteLine(field.Name + \" = \" + field.GetValue(obj).ToString());\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 237308, "author": "Jonathan Webb", "author_id": 1518, "author_profile": "https://Stackoverflow.com/users/1518", "pm_score": 3, "selected": false, "text": "<p>You can obtain all the object Fields declared directly in the class with the BindingFlags:</p>\n\n<pre><code>GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)\n</code></pre>\n\n<p>and all object Fields including inherited with:</p>\n\n<pre><code>GetFields(BindingFlags.Public | BindingFlags.Instance)\n</code></pre>\n" }, { "answer_id": 237817, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>Of course, another question would be \"why have you got public fields?\" - properties being preferable. As an abstraction, note that reflection isn't the only option: it is also possible for a type to expose it's properties on-the-fly at runtime (like how an untyped <code>DataTable</code>/<code>DataView</code> exposes columns as properties).</p>\n\n<p>To support this (while also supporting simple objects), you would use <code>TypeDescriptor</code>:</p>\n\n<pre><code> foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))\n {\n Console.WriteLine(\"{0}={1}\", prop.Name, prop.GetValue(obj));\n }\n</code></pre>\n\n<p>This also allows for numerous extensibility options - for example, vastly <a href=\"http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx\" rel=\"noreferrer\">speeding up reflection</a> (without changing any code).</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2153/" ]
I'm constructing a method to take in an ArrayList(presumably full of objects) and then list all the fields(and their values) for each object in the ArrayList. Currently my code is as follows: ``` public static void ListArrayListMembers(ArrayList list) { foreach (Object obj in list) { Type type = obj.GetType(); string field = type.GetFields().ToString(); Console.WriteLine(field); } } ``` Of course, I understand the immediate issue with this code: if it worked it'd only print one field per object in the ArrayList. I'll fix this later - right now I'm just curious how to get all of the public fields associated with an object.
``` foreach (Object obj in list) { Type type = obj.GetType(); foreach (var f in type.GetFields().Where(f => f.IsPublic)) { Console.WriteLine( String.Format("Name: {0} Value: {1}", f.Name, f.GetValue(obj)); } } ``` Note that this code requires .NET 3.5 to work ;-)
237,282
<p>At work, we have one of those nasty communal urinals. There is no flush handle. Rather, it has a motion sensor that sometimes triggers when you stand in front of it and sometimes doesn't. When it triggers, a tank fills, which when full is used to flush the urinal.</p> <p>In my many trips before this nastraption, I have pondered both what the algorithm is the box uses to determine when to turn on and what would be the optimal algorithm, in terms of conserving water while still maintaining a relatively pleasant urinal experience.</p> <p>I'll share my answer once folks have had a chance to share their ideas.</p>
[ { "answer_id": 237286, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 1, "selected": false, "text": "<p>I would trigger on sense but use a slow fill in the hope that by the time it actually flushes, someone else has had a slash. This approach would minimise stinky stagnation and occasionally skip a flush cycle.</p>\n" }, { "answer_id": 237301, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "<p>How do you know that it really isn't a camera that feeds its video to a bank of monitors in the basement where Milton triggers the flush when he sees you walk away from the urinal?</p>\n\n<p>/me puts on his tin-foil hat</p>\n" }, { "answer_id": 237315, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 5, "selected": true, "text": "<pre><code>OnUserEnter()\n{\n if (UsersDetected == 0)\n {\n FirstDetectionTime = Now();\n }\n UsersDetected++;\n CurrentlyInUse = true;\n}\n\nOnUserExit()\n{\n CurrentlyInUse = false;\n if (UsersDetected &gt;= MaxUsersBetweenFlushes || \n Now() - FirstDetectionTime &gt; StinkInterval)\n {\n Flush();\n }\n}\n\nOnTimer()\n{\n if (!CurrentlyInUse &amp;&amp; \n UsersDetected &gt; 0 &amp;&amp; \n Now() - FirstDetectionTime &gt; StinkInterval)\n {\n Flush();\n }\n}\n\nFlush()\n{\n FlushTheUrinal();\n UsersDetected = 0;\n}\n</code></pre>\n" }, { "answer_id": 237430, "author": "MrBoJangles", "author_id": 13578, "author_profile": "https://Stackoverflow.com/users/13578", "pm_score": 0, "selected": false, "text": "<p>At the risk of sounding Ludditish, I think the best solution is a handle. But that isn't the question. I would assume the mechanism is very simple. Someone moves in front of it, a count starts. When the count is fulfilled, the urinal is \"primed\". When the person moves away, the trigger is pulled, and the sensor turns off for an arbitrary amount of time (I don't think it has or needs any awareness of the act of flushing/tank-refilling). </p>\n\n<p>Am I overthinking this?</p>\n" }, { "answer_id": 262467, "author": "steffenj", "author_id": 15328, "author_profile": "https://Stackoverflow.com/users/15328", "pm_score": 2, "selected": false, "text": "<p>The best water-conserving algorithm is a urinal without a handle and a broken sensor. </p>\n\n<p>This seems to be the state of our urinal most of the time, so i suppose it has to be intentionally designed to do that in order to conserve precious drinking water.</p>\n" }, { "answer_id": 262519, "author": "steffenj", "author_id": 15328, "author_profile": "https://Stackoverflow.com/users/15328", "pm_score": 1, "selected": false, "text": "<p>The \"parallel-processing\" (aka \"multi-user\") urinals in our school always triggered a complete flush each time before the break bell rings and of course shortly after the \"break-is-over\" bell. Very simple and effective.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
At work, we have one of those nasty communal urinals. There is no flush handle. Rather, it has a motion sensor that sometimes triggers when you stand in front of it and sometimes doesn't. When it triggers, a tank fills, which when full is used to flush the urinal. In my many trips before this nastraption, I have pondered both what the algorithm is the box uses to determine when to turn on and what would be the optimal algorithm, in terms of conserving water while still maintaining a relatively pleasant urinal experience. I'll share my answer once folks have had a chance to share their ideas.
``` OnUserEnter() { if (UsersDetected == 0) { FirstDetectionTime = Now(); } UsersDetected++; CurrentlyInUse = true; } OnUserExit() { CurrentlyInUse = false; if (UsersDetected >= MaxUsersBetweenFlushes || Now() - FirstDetectionTime > StinkInterval) { Flush(); } } OnTimer() { if (!CurrentlyInUse && UsersDetected > 0 && Now() - FirstDetectionTime > StinkInterval) { Flush(); } } Flush() { FlushTheUrinal(); UsersDetected = 0; } ```
237,289
<p>I'm looking for a way to configure the color used for line numbering (as in: <code>:set nu</code>) in Vim. The default on most platforms seems to be yellow (which is also used for some highlighted tokens). I would <em>like</em> to color the line numbers a dim gray; somewhere in the vicinity of <code>#555</code>. I'm not picky though, any subdued color would be acceptable.</p>
[ { "answer_id": 237293, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "<p>Try:</p>\n\n<pre><code>help hl-LineNr\n</code></pre>\n\n<p>I found this through:</p>\n\n<pre><code>help 'number'\n</code></pre>\n\n<p>which is the way to get help on the <code>'number'</code> option, instead of the <code>:number</code> command.</p>\n\n<p>To actually change the displayed colour:</p>\n\n<pre><code>:highlight LineNr ctermfg=grey\n</code></pre>\n\n<p>This would change the foreground colour for LineNr on a character terminal to grey. If you are using gVim, you can:</p>\n\n<pre><code>:highlight LineNr guifg=#050505\n</code></pre>\n" }, { "answer_id": 12344075, "author": "Roshambo", "author_id": 610051, "author_profile": "https://Stackoverflow.com/users/610051", "pm_score": 4, "selected": false, "text": "<p>In MacVim (with Vim 7.3 at it's core) I've found <code>CursorLineNr</code> to work:</p>\n\n<p><code>hi CursorLineNr guifg=#050505</code></p>\n" }, { "answer_id": 32128209, "author": "qasimalbaqali", "author_id": 4708186, "author_profile": "https://Stackoverflow.com/users/4708186", "pm_score": 5, "selected": false, "text": "<p>To change the line numbers permanently add the below to your <code>.vimrc</code></p>\n\n<p><code>highlight LineNr term=bold cterm=NONE ctermfg=DarkGrey ctermbg=NONE gui=NONE guifg=DarkGrey guibg=NONE</code></p>\n\n<p>Of course you change the <code>ctermfg</code> and <code>guifg</code> to whatever color you want.</p>\n" }, { "answer_id": 37102917, "author": "Jabba", "author_id": 232485, "author_profile": "https://Stackoverflow.com/users/232485", "pm_score": 2, "selected": false, "text": "<p>I didn't like the colors provided by the selected color scheme so I modified the color of the line numbers this way:</p>\n\n<pre><code>colorscheme trivial256 \" for light background\nhi LineNr term=bold cterm=bold ctermfg=2 guifg=Grey guibg=Grey90\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9815/" ]
I'm looking for a way to configure the color used for line numbering (as in: `:set nu`) in Vim. The default on most platforms seems to be yellow (which is also used for some highlighted tokens). I would *like* to color the line numbers a dim gray; somewhere in the vicinity of `#555`. I'm not picky though, any subdued color would be acceptable.
Try: ``` help hl-LineNr ``` I found this through: ``` help 'number' ``` which is the way to get help on the `'number'` option, instead of the `:number` command. To actually change the displayed colour: ``` :highlight LineNr ctermfg=grey ``` This would change the foreground colour for LineNr on a character terminal to grey. If you are using gVim, you can: ``` :highlight LineNr guifg=#050505 ```
237,310
<p>I'm currently displaying a UIViewController like this:</p> <pre><code>[[self navigationController] presentModalViewController:modalViewController animated:YES]; </code></pre> <p>and hiding it like this:</p> <pre><code>[self.navigationController dismissModalViewControllerAnimated:YES]; </code></pre> <p>The animation is "slide up from the bottom"... then slide back down. How can I change the animation style? Can I made it fade in/out?</p> <p>Cheers!</p>
[ { "answer_id": 237355, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 7, "selected": true, "text": "<p>Marcus Zarra posted a great solution to this on the SDK mailing list:</p>\n\n<pre><code>UIViewController *controller = [[[MyViewController alloc] init] autorelease];\nUIViewAnimationTransition trans = UIViewAnimationTransitionCurlUp;\n[UIView beginAnimations: nil context: nil];\n[UIView setAnimationTransition: trans forView: [self window] cache: YES];\n[navController presentModalViewController: controller animated: NO];\n[UIView commitAnimations];\n</code></pre>\n\n<p>There are transitions for flipping and page-curling. If you are set on fading, can try adjusting your new view's alpha:</p>\n\n<pre><code>UIViewController *controller = [[[MyViewController alloc] init] autorelease];\ncontroller.view.alpha = 0.0;\n[navController presentModalViewController: controller animated: NO];\n[UIView beginAnimations: nil context: nil];\ncontroller.view.alpha = 1.0;\n[UIView commitAnimations];\n</code></pre>\n\n<p>However, what you probably want is a crossfade, or at least a fade-over. When the UINavigationController switches to a new view, it removes the old one. For this effect, you're probably better off just adding a new view to your existing UIViewController and fading its alpha in over time.</p>\n\n<p>Note: If you are not in your app delegate [self window] will not work. Use self.view.window , thanks to user412500's post for pointing this out.</p>\n" }, { "answer_id": 2006694, "author": "Simo Salminen", "author_id": 72544, "author_profile": "https://Stackoverflow.com/users/72544", "pm_score": 8, "selected": false, "text": "<p>For iPhone 3.0+, a basic crossfade is easiest to do like this:</p>\n\n<pre><code>modalViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;\n[[self navigationController] presentModalViewController:modalViewController\n animated:YES];\n</code></pre>\n" }, { "answer_id": 3632081, "author": "user412500", "author_id": 412500, "author_profile": "https://Stackoverflow.com/users/412500", "pm_score": 2, "selected": false, "text": "<p>It should be <code>[self.view.window]</code> in order for the code to work</p>\n\n<p>(at least that's the way that it is in ios 3.2)</p>\n" }, { "answer_id": 3892490, "author": "Peter DeWeese", "author_id": 431053, "author_profile": "https://Stackoverflow.com/users/431053", "pm_score": 3, "selected": false, "text": "<p>To update for alpha fading in iOS 4:</p>\n\n<pre><code>modalController.view.alpha = 0.0;\n[self.view.window.rootViewController presentModalViewController:modalController animated:NO];\n[UIView animateWithDuration:0.5\n animations:^{modalController.view.alpha = 1.0;}];\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I'm currently displaying a UIViewController like this: ``` [[self navigationController] presentModalViewController:modalViewController animated:YES]; ``` and hiding it like this: ``` [self.navigationController dismissModalViewControllerAnimated:YES]; ``` The animation is "slide up from the bottom"... then slide back down. How can I change the animation style? Can I made it fade in/out? Cheers!
Marcus Zarra posted a great solution to this on the SDK mailing list: ``` UIViewController *controller = [[[MyViewController alloc] init] autorelease]; UIViewAnimationTransition trans = UIViewAnimationTransitionCurlUp; [UIView beginAnimations: nil context: nil]; [UIView setAnimationTransition: trans forView: [self window] cache: YES]; [navController presentModalViewController: controller animated: NO]; [UIView commitAnimations]; ``` There are transitions for flipping and page-curling. If you are set on fading, can try adjusting your new view's alpha: ``` UIViewController *controller = [[[MyViewController alloc] init] autorelease]; controller.view.alpha = 0.0; [navController presentModalViewController: controller animated: NO]; [UIView beginAnimations: nil context: nil]; controller.view.alpha = 1.0; [UIView commitAnimations]; ``` However, what you probably want is a crossfade, or at least a fade-over. When the UINavigationController switches to a new view, it removes the old one. For this effect, you're probably better off just adding a new view to your existing UIViewController and fading its alpha in over time. Note: If you are not in your app delegate [self window] will not work. Use self.view.window , thanks to user412500's post for pointing this out.
237,322
<p>You'd think it would be easy, but keep reading. I can change many of the styles associated with a resizable JQuery Dialog, but not the handles. The code below isolates the problem. Why does the handle disappear entirely? There must be some logic I'm interfering with in ui.resizable.js, but I don't see it.</p> <pre><code>&lt;script type="text/javascript" language="JavaScript" src="jquery126.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="JavaScript" src="ui/ui.core.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="JavaScript" src="ui/ui.dialog.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="JavaScript" src="ui/ui.resizable.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="JavaScript" src="ui/ui.draggable.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(foo); function foo() { $("#dlg").dialog() } &lt;/script&gt; &lt;style type="text/css"&gt; .ui-resizable-n { background: green; } &lt;/style&gt; &lt;div id=dlg title="my title"&gt;this is&lt;br&gt;my text&lt;/div&gt; </code></pre>
[ { "answer_id": 237393, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<p>I believe the background of the resizeable borders are set as images, which in CSS stacking is on top of backgrounds. Try setting:</p>\n\n<pre><code>.ui-resizable-n{\n background-image:none;\n background-color:green;\n}\n</code></pre>\n" }, { "answer_id": 237953, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 2, "selected": true, "text": "<p>I was able to get it to work. I couldn't find the line of code my css was in conflict with, but when I added positioning and size related css, things worked. There must be some logic that says, \"use the default css unless the programmer has supplied his own\". So, while I thought I was appending info, I was somehow swapping info.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
You'd think it would be easy, but keep reading. I can change many of the styles associated with a resizable JQuery Dialog, but not the handles. The code below isolates the problem. Why does the handle disappear entirely? There must be some logic I'm interfering with in ui.resizable.js, but I don't see it. ``` <script type="text/javascript" language="JavaScript" src="jquery126.js"></script> <script type="text/javascript" language="JavaScript" src="ui/ui.core.js"></script> <script type="text/javascript" language="JavaScript" src="ui/ui.dialog.js"></script> <script type="text/javascript" language="JavaScript" src="ui/ui.resizable.js"></script> <script type="text/javascript" language="JavaScript" src="ui/ui.draggable.js"></script> <script> $(document).ready(foo); function foo() { $("#dlg").dialog() } </script> <style type="text/css"> .ui-resizable-n { background: green; } </style> <div id=dlg title="my title">this is<br>my text</div> ```
I was able to get it to work. I couldn't find the line of code my css was in conflict with, but when I added positioning and size related css, things worked. There must be some logic that says, "use the default css unless the programmer has supplied his own". So, while I thought I was appending info, I was somehow swapping info.
237,326
<p>In particular, would it be possible to have <strong>code similar to this c++ code executed at compile time in c#</strong>?</p> <pre><code>template &lt;int N&gt; struct Factorial { enum { value = N * Factorial&lt;N - 1&gt;::value }; }; template &lt;&gt; struct Factorial&lt;0&gt; { enum { value = 1 }; }; // Factorial&lt;4&gt;::value == 24 // Factorial&lt;0&gt;::value == 1 void foo() { int x = Factorial&lt;4&gt;::value; // == 24 int y = Factorial&lt;0&gt;::value; // == 1 } </code></pre>
[ { "answer_id": 237329, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": false, "text": "<p>No, metaprogramming is not possible in C#.</p>\n" }, { "answer_id": 237513, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "<p>To a <strong>very</strong> limited extent, C# something that could be interpreted as meta-programming. But really it's nothing more than overload resolution. It's a real stretch to call it meta programming. </p>\n\n<p>Example:</p>\n\n<pre><code>static string SomeFunc&lt;T&gt;(T value) {\n return \"Generic\";\n}\nstatic string SomeFunc(int value) {\n return \"Non-Generic\";\n}\n\nstatic void Example() {\n SomeFunc(42); // Non-Generic\n SomeFunc((object)42); // Generic\n}\n</code></pre>\n" }, { "answer_id": 237651, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 6, "selected": true, "text": "<p>No, metaprogramming of this complexity is not supported directly by the C# language. However, like <a href=\"https://stackoverflow.com/questions/237326/is-metaprogramming-possible-in-c#237644\">@littlegeek</a> said, the <a href=\"http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx\" rel=\"noreferrer\">Text Template Transformation Toolkit</a> included with Visual Studio will allow you to achieve code generation of any complexity.</p>\n" }, { "answer_id": 238083, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 3, "selected": false, "text": "<p>The essential difference between .NET Generics and C++ Templates is that generics are specialized at runtime. Templates are expanded at compile time. The dynamic behavior of generics makes things like Linq, expression trees, Type.MakeGenericType(), language independence and code re-use possible.</p>\n\n<p>But there is a price, you can't for example use operators on values of the generic type argument. You can't write a std::complex class in C#. And no compile-time metaprogramming.</p>\n" }, { "answer_id": 281050, "author": "thAAAnos", "author_id": 36557, "author_profile": "https://Stackoverflow.com/users/36557", "pm_score": 3, "selected": false, "text": "<p>You must be carefull when talking about compile-time when dealing with Java or .Net languages. \nIn those languages you can perform more powerfull metaprogamming (in the broader sense - reflection- ) than C++ due to the fact that \"compilation time\" (JIT) can be postponed after \"run time\" ;)</p>\n" }, { "answer_id": 409320, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 2, "selected": false, "text": "<p>It is going to be possible. Watch Anders Hejlsberg's <a href=\"http://channel9.msdn.com/pdc2008/TL16/\" rel=\"nofollow noreferrer\">The Future of C#</a> talk.</p>\n" }, { "answer_id": 2343843, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 3, "selected": false, "text": "<p>Most people insist on trying to metaprogram from inside their favorite language. That doesn't work if the language doesn't support metaprogramming well; other answers have observed that C# does not.</p>\n\n<p>A way around this is to do metaprogramming from <em>outside</em> the language, using \n<a href=\"http://www.semdesigns.com/products/DMS/ProgramTransformation.html?Home=DMSToolkit\" rel=\"nofollow noreferrer\">program transformation tools</a>. Such tools can parse source code, and carry out arbitrary transformations on it (that's what metaprogramming does anyway) and then spit out the revised program.</p>\n\n<p>If you have a general purpose program transformation system, that can parse arbitrary languages, you can then do metaprogramming on/with whatever language you like.\nSee our <a href=\"http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html\" rel=\"nofollow noreferrer\">DMS Software Reengineering Toolkit</a> for such a tool, that have robust front ends for C, C++, Java, C#, COBOL, PHP and a number of other programming langauges, and has been used for metaprogramming on all of these. </p>\n\n<p>DMS succeeds because it provides a regular method and support infrastructure for complete access to the program structure as ASTs, and in most cases additional data such a symbol tables, type information, control and data flow analysis, all necessary to do sophisticated program manipulation. </p>\n\n<p>EDIT (in response to comment): One could apply DMS to implement the OP's task on C#. </p>\n" }, { "answer_id": 9393268, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 5, "selected": false, "text": "<p>Metaprogramming is possible in .NET (see compiler compilers, regular expressions, code DOM, reflection etc.) but C# is not capable of <em>template</em> metaprogramming because it does not have that language feature.</p>\n" }, { "answer_id": 19924853, "author": "piojo", "author_id": 1682146, "author_profile": "https://Stackoverflow.com/users/1682146", "pm_score": 2, "selected": false, "text": "<p>Not in the way you're asking, but you can use some of the old C++ tricks to generate classes whose traits are specified statically:</p>\n\n<pre><code>abstract class Integer\n{\n public abstract int Get { get; }\n}\n\npublic class One : Integer { public override int Get { return 1; } } }\npublic class Two : Integer { public override int Get { return 2; } } }\npublic class Three : Integer { public override int Get { return 3; } } }\n\npublic class FixedStorage&lt;T, N&gt; where N : Integer, new()\n{\n T[] storage;\n public FixedStorage()\n {\n storage = new T[new N().Get];\n }\n public T Get(int i)\n {\n return storage[i];\n }\n}\n</code></pre>\n\n<p>Using this, you could define spatial classes:</p>\n\n<pre><code>public class Vector3 : FixedStorage&lt;float, Three&gt; {}\npublic class Vector2 : FixedStorage&lt;float, Two&gt; {}\npublic class GridCell : FixedStorage&lt;int, Two&gt; {}\n</code></pre>\n\n<p>I use this technique in a library that has a lot of subclasses, where adding a new data member requires a lot of boilerplate.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
In particular, would it be possible to have **code similar to this c++ code executed at compile time in c#**? ``` template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; // Factorial<4>::value == 24 // Factorial<0>::value == 1 void foo() { int x = Factorial<4>::value; // == 24 int y = Factorial<0>::value; // == 1 } ```
No, metaprogramming of this complexity is not supported directly by the C# language. However, like [@littlegeek](https://stackoverflow.com/questions/237326/is-metaprogramming-possible-in-c#237644) said, the [Text Template Transformation Toolkit](http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx) included with Visual Studio will allow you to achieve code generation of any complexity.
237,327
<p>The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data:</p> <pre><code>if table t has a row exists that has key X: update t set mystuff... where mykey=X else insert into t mystuff... </code></pre> <p>Since Oracle doesn't have a specific UPSERT statement, what's the best way to do this?</p>
[ { "answer_id": 237328, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 8, "selected": false, "text": "<p>The <a href=\"http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606\" rel=\"noreferrer\">MERGE statement</a> merges data between two tables. Using DUAL\nallows us to use this command. Note that this is not protected against concurrent access.</p>\n\n<pre><code>create or replace\nprocedure ups(xa number)\nas\nbegin\n merge into mergetest m using dual on (a = xa)\n when not matched then insert (a,b) values (xa,1)\n when matched then update set b = b+1;\nend ups;\n/\ndrop table mergetest;\ncreate table mergetest(a number, b number);\ncall ups(10);\ncall ups(10);\ncall ups(20);\nselect * from mergetest;\n\nA B\n---------------------- ----------------------\n10 2\n20 1\n</code></pre>\n" }, { "answer_id": 239579, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 7, "selected": true, "text": "<p>An alternative to MERGE (the \"old fashioned way\"):</p>\n\n<pre><code>begin\n insert into t (mykey, mystuff) \n values ('X', 123);\nexception\n when dup_val_on_index then\n update t \n set mystuff = 123 \n where mykey = 'X';\nend; \n</code></pre>\n" }, { "answer_id": 243564, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 6, "selected": false, "text": "<p>Another alternative without the exception check:</p>\n\n<pre><code>UPDATE tablename\n SET val1 = in_val1,\n val2 = in_val2\n WHERE val3 = in_val3;\n\nIF ( sql%rowcount = 0 )\n THEN\n INSERT INTO tablename\n VALUES (in_val1, in_val2, in_val3);\nEND IF;\n</code></pre>\n" }, { "answer_id": 2233798, "author": "Anon", "author_id": 269949, "author_profile": "https://Stackoverflow.com/users/269949", "pm_score": -1, "selected": false, "text": "<p>From <a href=\"http://www.praetoriate.com/oracle_tips_upserts.htm\" rel=\"nofollow noreferrer\">http://www.praetoriate.com/oracle_tips_upserts.htm</a>:</p>\n\n<p>\"In Oracle9i, an UPSERT can accomplish this task in a single statement:\"</p>\n\n<pre><code>INSERT\nFIRST WHEN\n credit_limit &gt;=100000\nTHEN INTO\n rich_customers\nVALUES(cust_id,cust_credit_limit)\n INTO customers\nELSE\n INTO customers SELECT * FROM new_customers;\n</code></pre>\n" }, { "answer_id": 2692441, "author": "MyDeveloperDay", "author_id": 323236, "author_profile": "https://Stackoverflow.com/users/323236", "pm_score": 7, "selected": false, "text": "<p>The dual example above which is in PL/SQL was great becuase I wanted to do something similar, but I wanted it client side...so here is the SQL I used to send a similar statement direct from some C#</p>\n\n<pre><code>MERGE INTO Employee USING dual ON ( \"id\"=2097153 )\nWHEN MATCHED THEN UPDATE SET \"last\"=\"smith\" , \"name\"=\"john\"\nWHEN NOT MATCHED THEN INSERT (\"id\",\"last\",\"name\") \n VALUES ( 2097153,\"smith\", \"john\" )\n</code></pre>\n\n<p>However from a C# perspective this provide to be slower than doing the update and seeing if the rows affected was 0 and doing the insert if it was.</p>\n" }, { "answer_id": 5307242, "author": "r4bitt", "author_id": 442005, "author_profile": "https://Stackoverflow.com/users/442005", "pm_score": -1, "selected": false, "text": "<p>Try this,</p>\n\n<pre><code>insert into b_building_property (\n select\n 'AREA_IN_COMMON_USE_DOUBLE','Area in Common Use','DOUBLE', null, 9000, 9\n from dual\n)\nminus\n(\n select * from b_building_property where id = 9\n)\n;\n</code></pre>\n" }, { "answer_id": 8275054, "author": "AnthonyVO", "author_id": 438458, "author_profile": "https://Stackoverflow.com/users/438458", "pm_score": 4, "selected": false, "text": "<p>A note regarding the two solutions that suggest:</p>\n\n<p>1) Insert, if exception then update,</p>\n\n<p>or</p>\n\n<p>2) Update, if sql%rowcount = 0 then insert</p>\n\n<p>The question of whether to insert or update first is also application dependent. Are you expecting more inserts or more updates? The one that is most likely to succeed should go first. </p>\n\n<p>If you pick the wrong one you will get a bunch of unnecessary index reads. Not a huge deal but still something to consider.</p>\n" }, { "answer_id": 14031952, "author": "Hubbitus", "author_id": 307525, "author_profile": "https://Stackoverflow.com/users/307525", "pm_score": 5, "selected": false, "text": "<p>I'd like Grommit answer, except it require dupe values. I found solution where it may appear once: <a href=\"http://forums.devshed.com/showpost.php?p=1182653&amp;postcount=2\" rel=\"noreferrer\">http://forums.devshed.com/showpost.php?p=1182653&amp;postcount=2</a></p>\n\n<pre><code>MERGE INTO KBS.NUFUS_MUHTARLIK B\nUSING (\n SELECT '028-01' CILT, '25' SAYFA, '6' KUTUK, '46603404838' MERNIS_NO\n FROM DUAL\n) E\nON (B.MERNIS_NO = E.MERNIS_NO)\nWHEN MATCHED THEN\n UPDATE SET B.CILT = E.CILT, B.SAYFA = E.SAYFA, B.KUTUK = E.KUTUK\nWHEN NOT MATCHED THEN\n INSERT ( CILT, SAYFA, KUTUK, MERNIS_NO)\n VALUES (E.CILT, E.SAYFA, E.KUTUK, E.MERNIS_NO); \n</code></pre>\n" }, { "answer_id": 21310345, "author": "test1", "author_id": 3228109, "author_profile": "https://Stackoverflow.com/users/3228109", "pm_score": 5, "selected": false, "text": "<ol>\n<li>insert if not exists </li>\n<li>update:</li>\n</ol>\n\n<pre> \nINSERT INTO mytable (id1, t1) \n SELECT 11, 'x1' FROM DUAL \n WHERE NOT EXISTS (SELECT id1 FROM mytble WHERE id1 = 11); \n\nUPDATE mytable SET t1 = 'x1' WHERE id1 = 11;\n</pre>\n" }, { "answer_id": 22777749, "author": "Evgeniy Berezovsky", "author_id": 709537, "author_profile": "https://Stackoverflow.com/users/709537", "pm_score": 5, "selected": false, "text": "<p>None of the answers given so far is <strong>safe in the face of concurrent accesses</strong>, as pointed out in Tim Sylvester's comment, and will raise exceptions in case of races. To fix that, the insert/update combo must be wrapped in some kind of loop statement, so that in case of an exception the whole thing is retried.</p>\n\n<p>As an example, here's how Grommit's code can be wrapped in a loop to make it safe when run concurrently:</p>\n\n<pre><code>PROCEDURE MyProc (\n ...\n) IS\nBEGIN\n LOOP\n BEGIN\n MERGE INTO Employee USING dual ON ( \"id\"=2097153 )\n WHEN MATCHED THEN UPDATE SET \"last\"=\"smith\" , \"name\"=\"john\"\n WHEN NOT MATCHED THEN INSERT (\"id\",\"last\",\"name\") \n VALUES ( 2097153,\"smith\", \"john\" );\n EXIT; -- success? -&gt; exit loop\n EXCEPTION\n WHEN NO_DATA_FOUND THEN -- the entry was concurrently deleted\n NULL; -- exception? -&gt; no op, i.e. continue looping\n WHEN DUP_VAL_ON_INDEX THEN -- an entry was concurrently inserted\n NULL; -- exception? -&gt; no op, i.e. continue looping\n END;\n END LOOP;\nEND; \n</code></pre>\n\n<p>N.B. In transaction mode <code>SERIALIZABLE</code>, which I don't recommend btw, you might run into\n<a href=\"https://stackoverflow.com/questions/19923171/how-to-make-merge-serializable/\">ORA-08177: can't serialize access for this transaction</a> exceptions instead.</p>\n" }, { "answer_id": 27906848, "author": "Arturo Hernandez", "author_id": 937703, "author_profile": "https://Stackoverflow.com/users/937703", "pm_score": 4, "selected": false, "text": "<p>I've been using the first code sample for years. Notice notfound rather than count.</p>\n<pre><code>UPDATE tablename SET val1 = in_val1, val2 = in_val2\n WHERE val3 = in_val3;\nIF ( sql%notfound ) THEN\n INSERT INTO tablename\n VALUES (in_val1, in_val2, in_val3);\nEND IF;\n</code></pre>\n<p>The code below is the possibly new and improved code</p>\n<pre><code>MERGE INTO tablename USING dual ON ( val3 = in_val3 )\nWHEN MATCHED THEN UPDATE SET val1 = in_val1, val2 = in_val2\nWHEN NOT MATCHED THEN INSERT \n VALUES (in_val1, in_val2, in_val3)\n</code></pre>\n<p>In the first example the update does an index lookup. It has to, in order to update the right row. Oracle opens an implicit cursor, and we use it to wrap a corresponding insert so we know that the insert will only happen when the key does not exist. But the insert is an independent command and it has to do a second lookup. I don't know the inner workings of the merge command but since the command is a single unit, Oracle could execute the correct insert or update with a single index lookup.</p>\n<p>I think merge is better when you do have some processing to be done that means taking data from some tables and updating a table, possibly inserting or deleting rows. But for the single row case, you may consider the first case since the syntax is more common.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data: ``` if table t has a row exists that has key X: update t set mystuff... where mykey=X else insert into t mystuff... ``` Since Oracle doesn't have a specific UPSERT statement, what's the best way to do this?
An alternative to MERGE (the "old fashioned way"): ``` begin insert into t (mykey, mystuff) values ('X', 123); exception when dup_val_on_index then update t set mystuff = 123 where mykey = 'X'; end; ```
237,350
<p>I am trying to call a setTimeout from within a setInterval callback:</p> <pre><code>function callback() { //assign myVar var myVar = document.getElementById("givenID"); //... //now wait 2 secs then call some code that uses myVAr setTimeout("myVar.innerHTML = 'TEST'", 2000); } setInterval("callback();", 10000); </code></pre> <p>setInterval works as expected but setTimeout call is failing. I guess the problem is related to the fact that I am referencing a variable (myVar) that's not in scope.</p> <p>What's the best way to solve this?</p>
[ { "answer_id": 237375, "author": "Michael Gundlach", "author_id": 4105, "author_profile": "https://Stackoverflow.com/users/4105", "pm_score": 1, "selected": false, "text": "<p>Run it in Firefox and check Tools | Error Console. if setTimeout fails it may tell you why there.</p>\n\n<p>Also, try replacing <code>\"someFunction();\"</code> with <code>\"alert('hi')\"</code> (no semicolon) and see if that works. If so, the problem is narrowed down significantly.</p>\n" }, { "answer_id": 237387, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 2, "selected": false, "text": "<p>As a matter of best-practice, try not to use strings as parameters to <code>setTimeout</code> and <code>setInterval</code> because that will invoke <code>eval</code> ... Using the following form might also make this problem easier to understand/debug:</p>\n\n<pre><code>setInterval(function () {\n // do stuff\n // ...\n // now wait 2 secs then call someFunction\n setTimeout(someFunction, 2000);\n}, 10000);\n</code></pre>\n" }, { "answer_id": 237388, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": true, "text": "<p>This is a perfect candidate for closures:</p>\n\n<pre><code>setInterval(\n function ()\n {\n var myVar = document.getElementById(\"givenID\");\n setTimeout(\n function()\n {\n // myVar is available because the inner closure \n // gets the outer closures scope\n myVar.innerHTML = \"Junk\";\n },2000);\n }, 10000);\n</code></pre>\n\n<p>Your problem is scope related, and this would work around that.</p>\n" }, { "answer_id": 6884195, "author": "svinec", "author_id": 870802, "author_profile": "https://Stackoverflow.com/users/870802", "pm_score": 4, "selected": false, "text": "<p>I had a similar problem. The issue was that I was trying to call a method from within itself through a setTimeout(). Something like this, WHICH DIDN'T WORK FOR ME:</p>\n\n<pre><code>function myObject() {\n\n this.egoist = function() {\n setTimeout( 'this.egoist()', 200 );\n }\n\n}\n\nmyObject001 = new myObject();\nmyObject001.egoist();\n</code></pre>\n\n<p>The following ALSO DIDN'T WORK:</p>\n\n<pre><code>... setTimeout( egoist, 200 );\n... setTimeout( egoist(), 200 );\n... setTimeout( this.egoist, 200 );\n... setTimeout( this.egoist(), 200 );\n... setTimeout( function() { this.egoist() }, 200 );\n</code></pre>\n\n<p>The solution was to use with() statement like so:</p>\n\n<pre><code>function myObject() {\n\n this.egoist = function() {\n with (this) { setTimeout( function() { egoist() }, 200 );}\n }\n\n}\n\nmyObject001 = new myObject();\nmyObject001.egoist();\n</code></pre>\n\n<p>Of course, this is an endless cycle, but the point I'm making here is different.</p>\n\n<p>Hope this helps :)</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311500/" ]
I am trying to call a setTimeout from within a setInterval callback: ``` function callback() { //assign myVar var myVar = document.getElementById("givenID"); //... //now wait 2 secs then call some code that uses myVAr setTimeout("myVar.innerHTML = 'TEST'", 2000); } setInterval("callback();", 10000); ``` setInterval works as expected but setTimeout call is failing. I guess the problem is related to the fact that I am referencing a variable (myVar) that's not in scope. What's the best way to solve this?
This is a perfect candidate for closures: ``` setInterval( function () { var myVar = document.getElementById("givenID"); setTimeout( function() { // myVar is available because the inner closure // gets the outer closures scope myVar.innerHTML = "Junk"; },2000); }, 10000); ``` Your problem is scope related, and this would work around that.
237,367
<p>When I connect to a MySQL database using PDO, the way I need to connect is:</p> <pre><code>$pdoConnection = new PDO("mysql:host=hostname;dbname=databasename",user,password); </code></pre> <p>But, for PostgreSQL, the DSN is more standard (IMO):</p> <pre><code>$pdoConnection = new PDO("pgsql:host=hostname;dbname=databasename;user=username;password=thepassword"); </code></pre> <p>Is there any reason why MySQL cannot use a single string? Or is this just because of the versions I am using (PHP 5.2, MySQL 5.0, PostgreSQL 8.1)?</p>
[ { "answer_id": 1314757, "author": "Wez Furlong", "author_id": 149111, "author_profile": "https://Stackoverflow.com/users/149111", "pm_score": 7, "selected": false, "text": "<p>As the person that implemented both, I can tell you that the reason is that by passing the string through as-is to postgres (and ODBC) the PDO driver code for those databases does not need to be updated as the underlying library adds new features.</p>\n\n<p>Since MySQL does not have its own connection string parsing code, we invented a mechanism for passing data in to the underlying MySQL function calls, which have a very specific API with fixed parameters.</p>\n\n<p>No accident; it's very deliberate.</p>\n" }, { "answer_id": 37436321, "author": "mindplay.dk", "author_id": 283851, "author_profile": "https://Stackoverflow.com/users/283851", "pm_score": 2, "selected": false, "text": "<p>Yep, this API inconsistency is a major annoyance.</p>\n\n<p>As a work-around, I pack the actual DSN string with an optional username and password using query-string syntax - then parse and construct like this:</p>\n\n\n\n<pre><code>parse_str($connection_string, $params);\n\n$pdo = new PDO($params['dsn'], @$params['username'], @$params['password']);\n</code></pre>\n\n<p>So for PostgreSQL, use a <code>$connection_string</code> like:</p>\n\n<pre><code>dsn=pgsql:host=localhost;dbname=test;user=root;password=root\n</code></pre>\n\n<p>And for MySQL, use a string like:</p>\n\n<pre><code>dsn=mysql:host=localhost;dbname=testdb&amp;username=root&amp;password=root\n</code></pre>\n\n<p>Kind of lame, but it's simple and it works.</p>\n" }, { "answer_id": 59037037, "author": "Shish", "author_id": 982134, "author_profile": "https://Stackoverflow.com/users/982134", "pm_score": 0, "selected": false, "text": "<p>This question is more than 10 years old, but I still end up here every time I create a new project that uses PDO... I'm writing my solution here so that I can save myself the trouble next time :P</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class MyPDO extends PDO {\n public function __construct($dsn, $options = null) {\n $user=null;\n $pass=null;\n\n if (preg_match(\"/user=([^;]*)/\", $dsn, $matches)) {\n $user=$matches[1];\n }\n if (preg_match(\"/password=([^;]*)/\", $dsn, $matches)) {\n $pass=$matches[1];\n }\n\n parent::__construct($dsn, $user, $pass, $options);\n }\n}\n</code></pre>\n" }, { "answer_id": 62587863, "author": "Alexios Tsiaparas", "author_id": 1231926, "author_profile": "https://Stackoverflow.com/users/1231926", "pm_score": 3, "selected": false, "text": "<p>This has been resolved in PHP 7.4, as can be seen in <a href=\"https://www.php.net/manual/en/migration74.new-features.php\" rel=\"noreferrer\">the new features</a>.</p>\n<p>I have confirmed it locally that we can write:</p>\n<pre><code>$dbh = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8mb4;user=root;password=')\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23089/" ]
When I connect to a MySQL database using PDO, the way I need to connect is: ``` $pdoConnection = new PDO("mysql:host=hostname;dbname=databasename",user,password); ``` But, for PostgreSQL, the DSN is more standard (IMO): ``` $pdoConnection = new PDO("pgsql:host=hostname;dbname=databasename;user=username;password=thepassword"); ``` Is there any reason why MySQL cannot use a single string? Or is this just because of the versions I am using (PHP 5.2, MySQL 5.0, PostgreSQL 8.1)?
As the person that implemented both, I can tell you that the reason is that by passing the string through as-is to postgres (and ODBC) the PDO driver code for those databases does not need to be updated as the underlying library adds new features. Since MySQL does not have its own connection string parsing code, we invented a mechanism for passing data in to the underlying MySQL function calls, which have a very specific API with fixed parameters. No accident; it's very deliberate.
237,370
<p>In some code I've inherited, I see frequent use of <code>size_t</code> with the <code>std</code> namespace qualifier. For example:</p> <pre><code>std::size_t n = sizeof( long ); </code></pre> <p>It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?).</p> <p>Isn't it true that <code>size_t</code> is built into C++ and therefore in the global namespace? Is a header file include needed to use <code>size_t</code> in C++?</p> <p>Another way to ask this question is, would the following program (with <em>no</em> includes) be expected to <em>compile</em> on all C++ compilers?</p> <pre><code>size_t foo() { return sizeof( long ); } </code></pre>
[ { "answer_id": 237374, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 2, "selected": false, "text": "<p>Sometimes other libraries will define their own size_t. For example boost. std::size_t specifies that you definitely want the c++ standard one. </p>\n\n<p>size_t is a c++ standard type and it is defined within the namespace std.</p>\n" }, { "answer_id": 237395, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 2, "selected": false, "text": "<p>size_t is not built into C++. And it is not defined by default. This one doesn't compile with GCC:</p>\n\n<pre><code>int main(int argc, char** argv) {\nsize_t size;\n}\n</code></pre>\n\n<p>That said, size_t is part of POSIX and if you use only basic things like <code>&lt;cstdlib&gt;</code>, you will likely end up having it defined.</p>\n\n<p>You could argue that std::size_t is the C++ equivalent of size_t. As Brian pointed out, std:: is used as namespace to avoid setting global variables which don't fit everybody. It's just like std::string, which could also have been defined in the root namespace.</p>\n" }, { "answer_id": 237398, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 5, "selected": false, "text": "<p>Section 17.4.1.2 of the C++ standard, paragraph 4, states that:</p>\n\n<p>\"In the C++ Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std.\"</p>\n\n<p>This includes items found in headers of the pattern <em>cname</em>, including <em>cstddef</em>, which defines size_t.</p>\n\n<p>So std::size_t is in fact correct.</p>\n" }, { "answer_id": 237882, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 4, "selected": false, "text": "<p>You can get <code>size_t</code> in the global namespace by including, for example, <code>&lt;stddef.h&gt;</code> instead of <code>&lt;cstddef&gt;</code>. I can't see any obvious benefit, and the feature is deprecated.</p>\n" }, { "answer_id": 283023, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 8, "selected": true, "text": "<p>There seems to be confusion among the stackoverflow crowd concerning this</p>\n\n<p><code>::size_t</code> is defined in the backward compatibility header <code>stddef.h</code> . It's been part of <code>ANSI/ISO C</code> and <code>ISO C++</code> since their very beginning. Every C++ implementation has to ship with <code>stddef.h</code> (compatibility) and <code>cstddef</code> where only the latter defines <code>std::size_t</code> and not necessarily <code>::size_t</code>. See Annex D of the C++ Standard.</p>\n" }, { "answer_id": 754760, "author": "Martin", "author_id": 91456, "author_profile": "https://Stackoverflow.com/users/91456", "pm_score": 2, "selected": false, "text": "<p>The GNU compiler headers contain something like</p>\n\n<pre>typedef long int __PTRDIFF_TYPE__;\ntypedef unsigned long int __SIZE_TYPE__;</pre>\n\n<p>Then stddef.h constains something like</p>\n\n<pre>typedef __PTRDIFF_TYPE__ ptrdiff_t;\ntypedef __SIZE_TYPE__ size_t;</pre>\n\n<p>And finally the cstddef file contains something like</p>\n\n<pre>\n#include &lt;stddef.h&gt;\n\nnamespace std {\n\n using ::ptrdiff_t;\n using ::size_t;\n\n}\n</pre>\n\n<p>I think that should make it clear. As long as you include &lt;cstddef&gt; you can use either size_t or std::size_t because size_t was typedefed outside the std namespace and was then included. Effectively you have</p>\n\n<pre>typedef long int ptrdiff_t;\ntypedef unsigned long int size_t;\n\nnamespace std {\n\n using ::ptrdiff_t;\n using ::size_t;\n\n}\n</pre>\n" }, { "answer_id": 850430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I think the clarifications are clear enough. The <code>std::size_t</code> makes good sense in C++ and <code>::size_t</code> make (at least) good sense in C.</p>\n\n<p>However a question remain. Namely whether it is safe to assume that <code>::size_t</code> and <code>std::size_t</code> are compatible?</p>\n\n<p>From a pure typesafe perspective they are not necessarily identical unless it is defined somewhere that they must be identical.</p>\n\n<p>I think many are using something a la:</p>\n\n<pre><code>----\n// a.hpp \n#include &lt;string&gt;\n\nvoid Foo( const std::string &amp; name, size_t value );\n\n-----\n// a.cpp\n#include \"a.hpp\"\n\nusing namespace std;\n\nvoid Foo( const string &amp; name, size_t value ) \n{\n ...\n}\n</code></pre>\n\n<p>So in the header you defintely use the <code>::size_t</code> while in the source file you'll use <code>std::size_t</code>. So they must be compatible, right? Otherwise you'll get a compiler error.</p>\n\n<p>/Michael S.</p>\n" }, { "answer_id": 1238084, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 2, "selected": false, "text": "<pre><code>std::size_t n = sizeof( long );\n</code></pre>\n\n<p>Actually, you haven't asked what specifically seems to be a bad practice int the above. Use of size_t, qualification with std namespace,... </p>\n\n<p>As the C++ Standard says (18.1), size_t is a type defined in the standard header . I'd suggest to drop any thoughts and impressions about possible inheritance from C language. C++ is a separate and different language and it's better to consider it as such. It has its own standard library and all elements of C++ Standard Library are defined within namespace std. However, it is possible to use elements of C Standard Library in C++ program.</p>\n\n<p>I'd consider including as a dirty hack. The C++ Standard states that the content of headers is the same or based on corresponding headers from the C Standard Library, but in number of cases, changes have been applied. In other words, it's not a direct copy &amp; paste of C headers into C++ headers. </p>\n\n<p>size_t is not a built-in type in C++. It is a type defined to specify what kind of integral type is used as a return type of sizeof() operator, because an actual return type of sizeof() is implementation defined, so the C++ Standard unifies by defining size_t.</p>\n\n<blockquote>\n <p>would the following program (with no\n includes) be expected to compile on\n all C++ compilers?</p>\n\n<pre><code>size_t foo()\n{\n return sizeof( long );\n}\n</code></pre>\n</blockquote>\n\n<p>The C++ Standard says (1.4):</p>\n\n<p><em>The names defined in the library have namespace scope (7.3). A C ++ translation unit (2.1) obtains access to these names by including the appropriate standard library header (16.2).</em></p>\n\n<p>The size_t is a name defined within std namespace, so every program that uses this name should include corresponding header, in this case.</p>\n\n<p>Next, the 3.7.3 chapter says:</p>\n\n<p><em>However, referring to std, std::bad_alloc, and std::size_t is ill-formed unless the name has been declared by including the appropriate header.</em></p>\n\n<p>Given that, program using size_t but not including header is ill-formed.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
In some code I've inherited, I see frequent use of `size_t` with the `std` namespace qualifier. For example: ``` std::size_t n = sizeof( long ); ``` It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?). Isn't it true that `size_t` is built into C++ and therefore in the global namespace? Is a header file include needed to use `size_t` in C++? Another way to ask this question is, would the following program (with *no* includes) be expected to *compile* on all C++ compilers? ``` size_t foo() { return sizeof( long ); } ```
There seems to be confusion among the stackoverflow crowd concerning this `::size_t` is defined in the backward compatibility header `stddef.h` . It's been part of `ANSI/ISO C` and `ISO C++` since their very beginning. Every C++ implementation has to ship with `stddef.h` (compatibility) and `cstddef` where only the latter defines `std::size_t` and not necessarily `::size_t`. See Annex D of the C++ Standard.
237,377
<p>Is there a better way to do this?</p> <pre><code>string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s .Select((a,i) =&gt; new {Value = a, Index = i}) .Where(b =&gt; b.Value.StartsWith("t")) .Select(c =&gt; c.Index); </code></pre> <p>i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.</p>
[ { "answer_id": 237379, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 3, "selected": false, "text": "<p>Seems fine to me. You might save a couple characters by changing the select to:</p>\n\n<pre><code>.Select((Value, Index) =&gt; new {Value, Index})\n</code></pre>\n" }, { "answer_id": 237451, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "<p>If you're just using the example as a way to learn LINQ, ignore this post.</p>\n\n<hr>\n\n<p>It's not clear to me that LINQ is actually the best way to do this. The code below seems like it would be more efficient since no new anonymous type needs to be created. Granted, your example may be contrived and the technique might be more useful in a different context, for example in a data structure where it could take advantage of an index on value, but the code below is reasonably straight-forward, understandable (no thought required) and arguably more efficient.</p>\n\n<pre><code>string[] s = {\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\"};\nList&lt;int&gt; matchingIndices = new List&lt;int&gt;();\n\nfor (int i = 0; i &lt; s.Length; ++i) \n{\n if (s[i].StartWith(\"t\"))\n {\n matchingIndices.Add(i);\n }\n}\n</code></pre>\n" }, { "answer_id": 237685, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>You could easily add your own extension method:</p>\n\n<pre><code>public static IEnumerable&lt;int&gt; IndexesWhere&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate)\n{\n int index=0;\n foreach (T element in source)\n {\n if (predicate(element))\n {\n yield return index;\n }\n index++;\n }\n}\n</code></pre>\n\n<p>Then use it with:</p>\n\n<pre><code>string[] s = {\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\"};\nvar x = s.IndexesWhere(t =&gt; t.StartsWith(\"t\"));\n</code></pre>\n" }, { "answer_id": 756224, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>There is also FindIndex method in Collection List for which you create a delete method which can return the index from the collection. you can refer to the following link in msdn <a href=\"http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx</a>.</p>\n" }, { "answer_id": 1036228, "author": "Terrence", "author_id": 84522, "author_profile": "https://Stackoverflow.com/users/84522", "pm_score": 1, "selected": false, "text": "<p>How about this? It's similar to the original poster's but I first select the indexes and then build a collection which matches the criteria. </p>\n\n<pre><code>var x = s.Select((a, i) =&gt; i).Where(i =&gt; s[i].StartsWith(\"t\"));\n</code></pre>\n\n<p>This is a tad less efficient than some of the other answers as the list is fully iterated over twice.</p>\n" }, { "answer_id": 7829692, "author": "MPelletier", "author_id": 210916, "author_profile": "https://Stackoverflow.com/users/210916", "pm_score": 0, "selected": false, "text": "<p>I discussed this interesting problem with a colleague and at first I thought JonSkeet's solution was great, but my colleague pointed out one problem, namely that if the function is an extension to <code>IEnumerable&lt;T&gt;</code>, then it can be used where a collection implements it.</p>\n\n<p>With an array, it's safe to say the order produced with <code>foreach</code> will be respected (i.e. <code>foreach</code> will iterate from first to last), but it would not necessarily be the case with other collections (List, Dictionary, etc), where <code>foreach</code> would not reflect <em>necessarily</em> \"order of entry\". Yet the function is there, and it can be misleading.</p>\n\n<p>In the end, I ended up with something similar to tvanfosson's answer, but as an extension method, for arrays:</p>\n\n<pre><code>public static int[] GetIndexes&lt;T&gt;(this T[]source, Func&lt;T, bool&gt; predicate)\n{\n List&lt;int&gt; matchingIndexes = new List&lt;int&gt;();\n\n for (int i = 0; i &lt; source.Length; ++i) \n {\n if (predicate(source[i]))\n {\n matchingIndexes.Add(i);\n }\n }\n return matchingIndexes.ToArray();\n}\n</code></pre>\n\n<p>Here's hoping <code>List.ToArray</code> will respect the order for the last operation...</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
Is there a better way to do this? ``` string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s .Select((a,i) => new {Value = a, Index = i}) .Where(b => b.Value.StartsWith("t")) .Select(c => c.Index); ``` i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.
You could easily add your own extension method: ``` public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate) { int index=0; foreach (T element in source) { if (predicate(element)) { yield return index; } index++; } } ``` Then use it with: ``` string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s.IndexesWhere(t => t.StartsWith("t")); ```
237,383
<p>Is possible to insert a line break where the cursor is in Vim without entering into insert mode? Here's an example (<code>[x]</code> means cursor is on <code>x</code>):</p> <pre><code>if (some_condition) {[ ]return; } </code></pre> <p>Occasionally, I might want to enter some more code. So I'd press <kbd>i</kbd> to get into insert mode, press <kbd>Enter</kbd> to insert the line break and then delete the extra space. Next, I'd enter normal mode and position the cursor before the closing brace and then do the same thing to get it on its own line.</p> <p>I've been doing this a while, but there's surely a better way to do it?</p>
[ { "answer_id": 237384, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "<p>For the example you've given, you could use <kbd>r</kbd><kbd>Enter</kbd> to replace a single character (the space) with Enter. Then, <kbd>f</kbd><kbd>space</kbd><kbd>.</kbd> to move forward to the next space and repeat the last command.</p>\n\n<p>Depending on your autoindent settings, the above may or may not indent the return statement properly. If not, then use <kbd>s</kbd><kbd>Enter</kbd><kbd>Tab</kbd><kbd>Esc</kbd> instead to replace the space with a newline, indent the line, and exit insert mode. You would have to replace the second space with a different command so you couldn't use '.' in this case.</p>\n" }, { "answer_id": 237436, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 4, "selected": false, "text": "<p>Here's how to create a macro that inserts a newline at the cursor whenever you press 'g' while <em>not</em> in insert mode:</p>\n\n<p>From within vim, type:</p>\n\n<pre><code>:map g i[Ctrl+V][Enter][Ctrl+V][Esc][Enter]\n</code></pre>\n\n<p>Where: </p>\n\n<ul>\n<li>[Ctrl+V] means <em>hold the Ctrl key and press 'v'</em></li>\n<li>[Enter] means <em>press the Enter key</em></li>\n<li>[Esc] means <em>press the Esc key</em></li>\n</ul>\n\n<p>You'll see the following at the bottom of your vim window until you press the final Enter:</p>\n\n<pre><code>:map g i^M^[\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<p>[Ctrl+V] means \"quote the following character\" -- it allows you to embed the newline and escape characters in the command.</p>\n\n<p>So you're mapping the 'g' key to the sequence: <pre>i [Enter] [Escape]</pre></p>\n\n<p>This is vim for <em>insert a newline before the cursor, then exit insert mode</em>.</p>\n\n<p><strong>Tweaks:</strong></p>\n\n<ul>\n<li>You can replace the 'g' with any character that's not already linked to a command you use.</li>\n<li>Add more to the command, <em>e.g.</em> <code>f}i^M^[O</code> -- This will <strong>f</strong>ind the <strong>}</strong> and <strong>i</strong>nsert another newline, then escape from insert mode and <strong>O</strong>pen an empty line for you to enter more code.</li>\n<li>You can add the command to your .vimrc or .exrc file to make it permanent. Just omit the colon from the beginning, so the command starts with \"map\"</li>\n</ul>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 237471, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 1, "selected": false, "text": "<p>Vim will automatically kill any whitespace to the right of the cursor if you break a line in two while <code>autoindent</code> (or any other indentation aid) is enabled.</p>\n\n<p>If you do not want to use any of those settings, use <code>s</code> instead of <code>i</code> in order to <b>s</b>ubstitute your new text for the blank rather than just inserting. (If there are multiple blanks, put the cursor on the leftmost and use <code>cw</code> instead.)</p>\n" }, { "answer_id": 237512, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": -1, "selected": false, "text": "<p>This mapping will break up any one-line function you have. Simply put your cursor on the line and hit 'g' in normal mode:</p>\n\n<pre><code>:map g ^f{malr&lt;CR&gt;`a%hr&lt;CR&gt;`a\n</code></pre>\n\n<p>This assumes that you have a space after the opening brace and a space before the closing brace. See if that works for you.</p>\n" }, { "answer_id": 237522, "author": "slothbear", "author_id": 2464, "author_profile": "https://Stackoverflow.com/users/2464", "pm_score": 3, "selected": false, "text": "<p>If you're usually expanding a one line block to three lines, try substitution. Change the opening bracket into bracket/return, and the closing bracket into return/bracket.</p>\n\n<p>The command for substituting bracket/return for bracket looks like this:</p>\n\n<pre><code>:s/{/{\\r/\n</code></pre>\n\n<p>Since you want to use this often, you could map the full sequence to an unused keystroke like this:</p>\n\n<pre><code>:map &lt;F7&gt; :s/{/{\\r/ ^M :s/}/\\r}/ ^M\n</code></pre>\n\n<p>Where you see <strong>^M</strong> in the sequence, type <strong>[Ctrl-V]</strong>, then press <strong>enter</strong>.</p>\n\n<p>Now with your cursor anywhere on your sample line, press the mapped key, and the carriage returns are added.</p>\n\n<p>Check <code>:help map-which-keys</code> for advice on selecting unused keystrokes to map.</p>\n" }, { "answer_id": 941991, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>A simple mapping to break the line at the cursor by pressing Ctrl+Enter:</p>\n\n<blockquote>\n <p><code>:nmap &lt;c-cr&gt; i&lt;cr&gt;&lt;Esc&gt;</code></p>\n</blockquote>\n\n<p>essentially enters 'insert' mode, inserts a line break and goes back to normal mode.</p>\n\n<p>put it in your .vimrc file for future use.</p>\n" }, { "answer_id": 6881163, "author": "Kiddo", "author_id": 804202, "author_profile": "https://Stackoverflow.com/users/804202", "pm_score": 0, "selected": false, "text": "<p>Set this key mapping in your vimrc</p>\n\n<pre><code>:map &lt;C-m&gt; i&lt;CR&gt;&lt;Esc&gt;h\n</code></pre>\n\n<p>Then press Ctrl+m if you want to use it in your vim.</p>\n" }, { "answer_id": 29820351, "author": "Hotschke", "author_id": 1057593, "author_profile": "https://Stackoverflow.com/users/1057593", "pm_score": 0, "selected": false, "text": "<p>IMHO, the built-in mapping <code>gs</code> is not a useful mapping (put vim to sleep), one could use this for splitting:</p>\n\n<pre><code>nmap gs i&lt;CR&gt;&lt;ESC&gt;\n</code></pre>\n" }, { "answer_id": 32127176, "author": "Janac Meena", "author_id": 1502439, "author_profile": "https://Stackoverflow.com/users/1502439", "pm_score": 0, "selected": false, "text": "<p>In <a href=\"http://vrapper.sourceforge.net/home/\" rel=\"nofollow\">Vrapper</a> you can use gql which will split a line without entering insert mode, but may not always maintain indentation. </p>\n" }, { "answer_id": 35784669, "author": "ctrl", "author_id": 3701295, "author_profile": "https://Stackoverflow.com/users/3701295", "pm_score": 1, "selected": false, "text": "<p>Basically, when you split a line you either want to just insert a carriage return, or in the case that you're on a space, replace that with a carriage return. Well, why settle for one or the other? Here's my mapping for K:</p>\n\n<pre><code>\"Have K split lines the way J joins lines\nnnoremap &lt;expr&gt;K getline('.')[col('.')-1]==' ' ? \"r&lt;CR&gt;\" : \"i&lt;CR&gt;&lt;Esc&gt;\"\n</code></pre>\n\n<p>I use the ternary operator to condense the two actions into one key map. Breaking it down, <code>&lt;expr&gt;</code> means the key map's output can dynamic and in this case hinges on the condition <code>getline('.')[col('.')-1]==' '</code> which is the long winded way to ask vim if the character under the cursor is a space. Finally, the familiar ternary operator <code>? :</code> either replaces the space with linebreak (<code>r&lt;CR&gt;</code>) or inserts a new one (<code>i&lt;CR&gt;&lt;Esc&gt;</code>)</p>\n\n<p>Now you have a lovely sister key map to the <code>J</code> command.</p>\n" }, { "answer_id": 40598115, "author": "mondaugen", "author_id": 1082233, "author_profile": "https://Stackoverflow.com/users/1082233", "pm_score": 2, "selected": false, "text": "<p>Assuming you're okay with mapping <code>K</code> to something else (choose a different key of your liking), and using marker <code>'</code> as a temporary marker is okay why not do this?</p>\n\n<pre><code>:nmap K m'a&lt;CR&gt;&lt;Esc&gt;`'\n</code></pre>\n\n<p>now pressing K in normal mode over the character after which you want the line break to occur will split the line and leave the cursor where it was.</p>\n" }, { "answer_id": 43011315, "author": "Nathan", "author_id": 7764790, "author_profile": "https://Stackoverflow.com/users/7764790", "pm_score": 1, "selected": false, "text": "<p>In fact you need the following combined operations:</p>\n\n<ol>\n<li>Press <kbd>v</kbd> to enter Visual Mode</li>\n<li>Select the line you want to split</li>\n<li>Press <code>:</code> to enter in Command Mode</li>\n<li><code>s/\\s/\\r/g</code> </li>\n<li>Done</li>\n</ol>\n" }, { "answer_id": 43712932, "author": "Yarden Akin", "author_id": 6422027, "author_profile": "https://Stackoverflow.com/users/6422027", "pm_score": 1, "selected": false, "text": "<p>If you have the input:</p>\n\n<pre><code>aaa bbb ccc ddd\n</code></pre>\n\n<p>and want to output</p>\n\n<pre><code>aaa\nbbb\nccc\nddd\n</code></pre>\n\n<p>You can use the command</p>\n\n<pre><code>f r&lt;ENTER&gt;;.;.\n</code></pre>\n" }, { "answer_id": 53782580, "author": "JaredMcAteer", "author_id": 577926, "author_profile": "https://Stackoverflow.com/users/577926", "pm_score": 0, "selected": false, "text": "<p>I found this to be the most faithful implementation of what I'd expect the opposite behaviour to <code>J</code></p>\n\n<pre><code>nnoremap S i&lt;cr&gt;&lt;esc&gt;^mwgk:silent! s/\\v +$//&lt;cr&gt;:noh&lt;cr&gt;`w\n</code></pre>\n\n<p>It does the simplistic new line at cursor, takes care of any trailing whitespace on the previous line if there are any present and then returns the cursor to the correct position.</p>\n\n<p><kbd>i</kbd> <kbd>&lt;cr&gt;</kbd> <kbd>&lt;esc&gt;</kbd> - this is one of the most common solutions suggested, it doesn't delete non-whitespace characters under your cursor but it also leaves you with trailing whitespace</p>\n\n<p><kbd>^mw</kbd> - goto start of new line and create a mark under <code>w</code></p>\n\n<p><kbd>gk</kbd> - go up one line</p>\n\n<p><kbd>:silent! s/\\v +$//</kbd><kbd>&lt;cr&gt;</kbd> - regex replace any whitespace at the end of the line</p>\n\n<p><kbd>:noh</kbd><kbd>&lt;cr&gt;</kbd> - Clear any search highlighting that the regex might have turned on</p>\n\n<p><kbd>&#x60;w</kbd> - return the the mark under <code>w</code></p>\n\n<p>Essentially combines the best of both <kbd>r</kbd><kbd>&lt;esc&gt;</kbd><kbd>&lt;cr&gt;</kbd> and <kbd>i</kbd><kbd>&lt;cr&gt;</kbd><kbd>&lt;esc&gt;</kbd></p>\n\n<p>Note: I have this bound to <kbd>S</kbd> which potentially overwrites a useful key but it is a synonym for <kbd>cc</kbd> and since I don't use it as often as I do splits I am okay with overwriting it.</p>\n" }, { "answer_id": 62144795, "author": "logbasex", "author_id": 10393067, "author_profile": "https://Stackoverflow.com/users/10393067", "pm_score": 1, "selected": false, "text": "<p><code>o</code> <code>ESC</code> command will do it for you.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103052/" ]
Is possible to insert a line break where the cursor is in Vim without entering into insert mode? Here's an example (`[x]` means cursor is on `x`): ``` if (some_condition) {[ ]return; } ``` Occasionally, I might want to enter some more code. So I'd press `i` to get into insert mode, press `Enter` to insert the line break and then delete the extra space. Next, I'd enter normal mode and position the cursor before the closing brace and then do the same thing to get it on its own line. I've been doing this a while, but there's surely a better way to do it?
For the example you've given, you could use `r``Enter` to replace a single character (the space) with Enter. Then, `f``space``.` to move forward to the next space and repeat the last command. Depending on your autoindent settings, the above may or may not indent the return statement properly. If not, then use `s``Enter``Tab``Esc` instead to replace the space with a newline, indent the line, and exit insert mode. You would have to replace the second space with a different command so you couldn't use '.' in this case.
237,405
<p>Can someone explain this in a practical way? Sample represents usage for one, low-traffic Rails site using Nginx and 3 Mongrel clusters. I ask because I am aiming to learn about page caching, wondering if these figures have significant meaning to that process. Thank you. Great site!</p> <pre><code>me@vps:~$ free -m total used free shared buffers cached Mem: 512 506 6 0 15 103 -/+ buffers/cache: 387 124 Swap: 1023 113 910 </code></pre>
[ { "answer_id": 237528, "author": "Cameron Booth", "author_id": 14873, "author_profile": "https://Stackoverflow.com/users/14873", "pm_score": 1, "selected": false, "text": "<p>by my reading of this, you have used almost all your memory, have 6 M free, and are going into about 10% of your swap. A more useful tools is to use top or perhaps ps to see how much each of your individual mongrels are using in RAM. Because you're going into swap, you're probably getting more slowdowns. you might find having only 2 mongrels rather than 3 might actually respond faster because it likely wouldn't go into swap memory.</p>\n\n<p>Page caching will for sure help a tonne on response time, so if your pages are cachable (eg, they don't have content that is unique to the individual user) I would say for sure check it out</p>\n" }, { "answer_id": 237848, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 2, "selected": false, "text": "<p>Physical memory is all used up. Why? Because it's there, the system should be using it.</p>\n\n<p>You'll note also that the system is using 113M of swap space. Bad? Good? It depends. </p>\n\n<p>See also that there's 103M of cached disk; this means that the system has decided that it's better to cache 103M of disk and swap out these 113M; maybe you have some processes using memory that are not being used and thus are paged out to disk.</p>\n\n<p>As the other poster said, you should be using other tools to see what's happening:</p>\n\n<ol>\n<li>Your perception: is the site running appropiately when you use it?</li>\n<li>Benchmarking: what response times are your clients seeing?</li>\n<li>More fine-grained diagnostics:\n\n<ol>\n<li>top: you can see live which processes are using memory and CPU</li>\n<li>vmstat: it produces this kind of output:</li>\n</ol></li>\n</ol>\n\n<pre>\n alex@armitage:~$ vmstat 1\nprocs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----\n r b swpd free buff cache si so bi bo in cs us sy id wa\n 2 1 71184 156520 92524 316488 1 5 12 23 362 250 13 6 80 1\n 0 0 71184 156340 92528 316508 0 0 0 1 291 608 10 1 89 0\n 0 0 71184 156364 92528 316508 0 0 0 0 308 674 9 2 89 0\n 0 0 71184 156364 92532 316504 0 0 0 72 295 723 9 0 91 0\n 1 0 71184 150892 92532 316508 0 0 0 0 370 722 38 0 62 0\n 0 0 71184 163060 92532 316508 0 0 0 0 303 611 17 2 81 0\n</pre>\n\n<p>which will show you whether swap is hurting you (high numbers on si, so) and a more easier to see performance-over-time statistic.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31347/" ]
Can someone explain this in a practical way? Sample represents usage for one, low-traffic Rails site using Nginx and 3 Mongrel clusters. I ask because I am aiming to learn about page caching, wondering if these figures have significant meaning to that process. Thank you. Great site! ``` me@vps:~$ free -m total used free shared buffers cached Mem: 512 506 6 0 15 103 -/+ buffers/cache: 387 124 Swap: 1023 113 910 ```
Physical memory is all used up. Why? Because it's there, the system should be using it. You'll note also that the system is using 113M of swap space. Bad? Good? It depends. See also that there's 103M of cached disk; this means that the system has decided that it's better to cache 103M of disk and swap out these 113M; maybe you have some processes using memory that are not being used and thus are paged out to disk. As the other poster said, you should be using other tools to see what's happening: 1. Your perception: is the site running appropiately when you use it? 2. Benchmarking: what response times are your clients seeing? 3. More fine-grained diagnostics: 1. top: you can see live which processes are using memory and CPU 2. vmstat: it produces this kind of output: ``` alex@armitage:~$ vmstat 1 procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu---- r b swpd free buff cache si so bi bo in cs us sy id wa 2 1 71184 156520 92524 316488 1 5 12 23 362 250 13 6 80 1 0 0 71184 156340 92528 316508 0 0 0 1 291 608 10 1 89 0 0 0 71184 156364 92528 316508 0 0 0 0 308 674 9 2 89 0 0 0 71184 156364 92532 316504 0 0 0 72 295 723 9 0 91 0 1 0 71184 150892 92532 316508 0 0 0 0 370 722 38 0 62 0 0 0 71184 163060 92532 316508 0 0 0 0 303 611 17 2 81 0 ``` which will show you whether swap is hurting you (high numbers on si, so) and a more easier to see performance-over-time statistic.
237,408
<p>I have a local Git repository I've been developing under for a few days: it has eighteen commits so far. Tonight, I created a private Github repository I was hoping to push it to; however, when I did so, it only ended up pushing eight of the eighteen commits to Github. I deleted the Github repo and retried, with the same result.</p> <p>Any thoughts on why this might be happening? I've done this procedure before without a few times successfully, so I'm a bit stumped.</p> <p><strong>Update</strong>: There is, and has always been, only the master branch in this repo. Just to address a few of the posted answers...</p>
[ { "answer_id": 237409, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>I suppose the first thing I would do would be to run <code>git fsck</code> on your local repository to make sure that it is all in good order.</p>\n\n<p>I've never seen this problem before, and I can't think of what might be wrong.</p>\n" }, { "answer_id": 237517, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "<p>Check if you are pushing the correct branches, and that the branches actually have what you think they have. In particular, check if you do not have a detached HEAD, which can be quite confusing if not done on purpose.</p>\n\n<p>The easiest way to check is to use <code>gitk --all</code>, which shows graphically all the branches, the HEAD, and more.</p>\n" }, { "answer_id": 238656, "author": "rpj", "author_id": 23498, "author_profile": "https://Stackoverflow.com/users/23498", "pm_score": 0, "selected": false, "text": "<p>So, it turns out that both: the commit hash in .git/refs/heads/master was incorrect and the information in .git/logs/refs/heads/master was incomplete; in that I mean it only went up to and included the commit hash specified in .git/refs/heads/master.</p>\n<p>Once I fixed these files (by hand), and pushed them back to Github, everything was gravy again. I still have <strong>no idea</strong> what happened to get things in this state, but I'm glad I've at least figured out the fix.</p>\n<p>In case anyone is wondering: to fix .git/refs/heads/master, I just replaced the content of that file with the latest commit hash (HEAD), and to fix .git/logs/refs/heads/master, I simply copied the contents of .git/logs/HEAD into .git/logs/refs/heads/master. Easy peasy... NOT.</p>\n" }, { "answer_id": 276409, "author": "farktronix", "author_id": 677, "author_profile": "https://Stackoverflow.com/users/677", "pm_score": 5, "selected": true, "text": "<p>I took a look at the repository in question and here's what was going on:</p>\n\n<ul>\n<li>At some point, rpj had performed <code>git checkout [commit id]</code>. This pointed HEAD at a loose commit rather than a recognized branch. I believe this is the \"dangling HEAD\" problem that CesarB is referring to.</li>\n<li>Not realizing this problem, he went on making changing and committing them, which bumped HEAD up every time. However, HEAD was just pointing at a dangling chain of commits, not at a recognized branch.</li>\n<li>When he went to push his changes, git pushed everything up to the top of master, which was only about halfway through the current tree he was on.</li>\n<li>Confusion ensued</li>\n</ul>\n\n<p>This diagram should make it more clear:</p>\n\n<pre><code> -- D -- E -- F\n / ^\n A -- B -- C - |\n ^ ^ HEAD\n | |\n remote master\n</code></pre>\n\n<p>When he tried to push his changes, only <code>A</code> through <code>C</code> were pushed and <code>remote</code> moved up to <code>C</code>. He couldn't get commits <code>D</code> through <code>F</code> to push because they aren't referenced by a known branch.</p>\n\n<p>Here's what you see when you're in this state:</p>\n\n<pre><code>$ git branch\n* (no branch)\nmaster\n</code></pre>\n\n<p>The solution is to move <code>master</code> up to <code>F</code> in the dangling chain of commits. Here's how I did it.</p>\n\n<ul>\n<li><p>Create a legitimate branch for the current state:</p>\n\n<p><code>git checkout -b tmp</code></p>\n\n<ul>\n<li>The <code>tmp</code> branch is now pointing at commit <code>F</code> in the diagram above</li>\n</ul></li>\n<li><p>Fast-forward <code>master</code> to <code>tmp</code></p>\n\n<p><code>git checkout master</code></p>\n\n<p><code>git merge tmp</code></p>\n\n<ul>\n<li><code>master</code> is now pointing at commit <code>F</code>. </li>\n</ul></li>\n<li><p>Throw away your temporary branch</p>\n\n<p><code>git branch -d tmp</code></p></li>\n<li><p>You can happily push to the remote repository and it should send all of your changes.</p></li>\n</ul>\n" }, { "answer_id": 276418, "author": "farktronix", "author_id": 677, "author_profile": "https://Stackoverflow.com/users/677", "pm_score": 1, "selected": false, "text": "<p>I don't have the reputation to comment directly on CesarB's earlier answer, but <code>gitk --all</code> doesn't work in this case because it only lists out known branches. </p>\n\n<p><code>gitk HEAD</code> shows this problem, but it's not entirely clear. The smoking gun is that <code>master</code> shows up down the commit tree rather than at the most recent commit.</p>\n" }, { "answer_id": 276495, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "<p>From Git 1.7.3 onwards, you can do this with one simple command:</p>\n\n<pre><code>git checkout -B master\n</code></pre>\n\n<p>The <code>-b</code> switch means “create branch here before checking it out” and <code>-B</code> is the unconditional version of that, “even if the branch already exists – in that case, move it here before checking it out”.</p>\n\n<hr>\n\n<p>A very simple approach for fixing this sort of problem is to just delete the <code>master</code> branch and recreate it. After all, branches in git are merely names for commits and the <code>master</code> branch is nothing special.</p>\n\n<p>So assuming that the current commit is the one you want <code>master</code> to be, you simply do</p>\n\n<pre><code>git branch -D master\n</code></pre>\n\n<p>to delete the existing <code>master</code> branch, then do</p>\n\n<pre><code>git checkout -b master\n</code></pre>\n\n<p>to a) create a new branch called <code>master</code> that points to the current commit and b) update <code>HEAD</code> to point to the <code>master</code> branch. After that, <code>HEAD</code> will be attached to <code>master</code> and therefore <code>master</code> will move forward whenever you commit.</p>\n" }, { "answer_id": 495945, "author": "Matthew Maravillas", "author_id": 2186, "author_profile": "https://Stackoverflow.com/users/2186", "pm_score": 0, "selected": false, "text": "<p>I've had this same problem twice, and finally figured out what I was doing that was causing it. In the process of editing an old commit with <code>git rebase -i</code>, instead of calling <code>git commit --amend</code>, I was calling <code>git commit -a</code> by force of habit, immediately followed by <code>git rebase --continue</code>, of course. Someone else might be able to explain what's going on behind the scenes, but it seems that the result is the detached HEAD problem.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23498/" ]
I have a local Git repository I've been developing under for a few days: it has eighteen commits so far. Tonight, I created a private Github repository I was hoping to push it to; however, when I did so, it only ended up pushing eight of the eighteen commits to Github. I deleted the Github repo and retried, with the same result. Any thoughts on why this might be happening? I've done this procedure before without a few times successfully, so I'm a bit stumped. **Update**: There is, and has always been, only the master branch in this repo. Just to address a few of the posted answers...
I took a look at the repository in question and here's what was going on: * At some point, rpj had performed `git checkout [commit id]`. This pointed HEAD at a loose commit rather than a recognized branch. I believe this is the "dangling HEAD" problem that CesarB is referring to. * Not realizing this problem, he went on making changing and committing them, which bumped HEAD up every time. However, HEAD was just pointing at a dangling chain of commits, not at a recognized branch. * When he went to push his changes, git pushed everything up to the top of master, which was only about halfway through the current tree he was on. * Confusion ensued This diagram should make it more clear: ``` -- D -- E -- F / ^ A -- B -- C - | ^ ^ HEAD | | remote master ``` When he tried to push his changes, only `A` through `C` were pushed and `remote` moved up to `C`. He couldn't get commits `D` through `F` to push because they aren't referenced by a known branch. Here's what you see when you're in this state: ``` $ git branch * (no branch) master ``` The solution is to move `master` up to `F` in the dangling chain of commits. Here's how I did it. * Create a legitimate branch for the current state: `git checkout -b tmp` + The `tmp` branch is now pointing at commit `F` in the diagram above * Fast-forward `master` to `tmp` `git checkout master` `git merge tmp` + `master` is now pointing at commit `F`. * Throw away your temporary branch `git branch -d tmp` * You can happily push to the remote repository and it should send all of your changes.
237,415
<p>I'm attempting to use LINQ to insert a record into a child table and I'm receiving a "Specified cast is not valid" error that has something to do w/ the keys involved. The stack trace is:</p> <blockquote> <p>Message: Specified cast is not valid.</p> <p>Type: System.InvalidCastException Source: System.Data.Linq TargetSite: Boolean TryCreateKeyFromValues(System.Object[], V ByRef) HelpLink: null Stack: at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager<code>2.TryCreateKeyFromValues(Object[] values, V&amp; v) at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache</code>2.Find(Object[] keyValues) at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues) at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) at System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges()</p> <p>(.....)</p> </blockquote> <p>This error is being thrown on the following code:</p> <pre><code> ResponseDataContext db = new ResponseDataContext(m_ConnectionString); CodebookVersion codebookVersion = db.CodebookVersions.Single(cv =&gt; cv.VersionTag == m_CodebookVersionTag); ResponseCode rc = new ResponseCode() { SurveyQuestionName = "Q11", Code = 3, Description = "Yet another code" }; codebookVersion.ResponseCodes.Add(rc); db.SubmitChanges(); //exception gets thrown here </code></pre> <p>The tables in question have a FK relationship between the two of them.<br> The parent table's column is called 'id', is the PK, and is of type: INT NOT NULL IDENTITY<br> The child table's column is called 'responseCodeTableId' and is of type: INT NOT NULL.</p> <p>codebookVersion (parent class) maps to table tblResponseCodeTable<br> responseCode (childClass) maps to table tblResponseCode</p> <p>If I execute SQL directly, it works. e.g. </p> <pre><code>INSERT INTO tblResponseCode (responseCodeTableId, surveyQuestionName, code, description) VALUES (13683, 'Q11', 3, 'Yet another code') </code></pre> <p>Updates to the same class work properly. e.g. </p> <pre><code>codebookVersion.ResponseCodes[0].Description = "BlahBlahBlah"; db.SubmitChanges(); //no exception - change is committed to db </code></pre> <p>I've examined the variable, rc, after the .Add() operation and it does, indeed, receive the proper responseCodeTableId, just as I would expect since I'm adding it to that collection.</p> <pre><code>tblResponseCodeTable's full definition: COLUMN_NAME TYPE_NAME id int identity responseCodeTableId int surveyQuestionName nvarchar code smallint description nvarchar dtCreate smalldatetime </code></pre> <p>dtCreate has a default value of GetDate().</p> <p>The only other bit of useful information that I can think of is that no SQL is ever tried against the database, so LINQ is blowing up before it ever tries (hence the error not being a SqlException). I've profiled and verified that no attempt is made to execute any statements on the database.</p> <p>I've read around and seen the problem when you have a relationship to a non PK field, but that doesn't fit my case.</p> <p>Can anyone shed any light on this situation for me? What incredibly obvious thing am I missing here? </p> <p>Many thanks.<br> Paul Prewett</p>
[ { "answer_id": 237426, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<pre><code>ResponseCode rc = new ResponseCode()\n {\n SurveyQuestionName = \"Q11\",\n Code = 3,\n Description = \"Yet another code\"\n };\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>INSERT INTO tblResponseCode \n(responseCodeTableId, surveyQuestionName, code, description)\nVALUES (13683, 'Q11', 3, 'Yet another code')\n</code></pre>\n\n<p>Are not the same, you are not passing in the foreign key reference. Now, I'm huge n00b at LINQ2SQL, but I'd wager that LINQ2SQL is not smart enough to do that for you, and it expects it as the first parameter of the anonymous dictionary, and is trying to cast a string to an integer.</p>\n\n<p>Just some ideas.</p>\n" }, { "answer_id": 237427, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>This block:</p>\n\n<pre><code>codebookVersion.ResponseCodes.Add(rc);\ndb.SubmitChanges(); //exception gets thrown here\n</code></pre>\n\n<p>Can you try <code>InsertOnSubmit</code> instead of <code>Add</code>? i.e.</p>\n\n<pre><code>codebookVersion.ResponseCodes.InsertOnSubmit(rc);\n</code></pre>\n\n<p>I think <code>Add</code> is not meant to be used to insert records if my memory serves me right. InsertOnSubmit is the one to use.</p>\n" }, { "answer_id": 237459, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>To try and narrow down the culprit.</p>\n\n<p>Have you tried replacing the anonymous dictionary with something like:</p>\n\n<pre><code>ResponseCode rc = new ResponseCode();\n\nrc.SurveyQuestName = \"Q11\";\nrc.Code = 3;\nrc.Description = \"Yet Another Code\";\n</code></pre>\n\n<p>I've yet to really work with .NET 3.5 yet (day job is still all 2.0), so I'm wondering if there is an issue with passing the data using the anonymous dictionary (The cases don't match the SQL Columns for one).</p>\n" }, { "answer_id": 237473, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Post up the schema of the parent table.</p>\n\n<p>if you look here, some other people have had your problem.\n<a href=\"http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3493504&amp;SiteID=1\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3493504&amp;SiteID=1</a></p>\n\n<p>It appears that Linq2SQL has trouble mapping some foreign keys to some primary keys. One guy had a resolution, but I think you are already mapping to an IDENTITY column.</p>\n" }, { "answer_id": 237484, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Yea, I've read that and other posts, but it always seems to involve someone linking up to a field that simply has a unique contraint. Or in this guy's case (which does sound exactly like mine), he didn't get a solution.</p>\n\n<p>Here's the parent table: </p>\n\n<pre><code>tblResponseTable definition (which maps to CodebookVersion)\nCOLUMN_NAME TYPE_NAME\nid int identity\nversionTag nvarchar\nresponseVersionTag nvarchar\n</code></pre>\n\n<p>versionTag does have a unique contraint on it, but that's not represented anywhere that I can see in the LINQ-to-SQL stuff - and since nothing ever goes to the database... still stuck.</p>\n" }, { "answer_id": 237568, "author": "Mike Two", "author_id": 23659, "author_profile": "https://Stackoverflow.com/users/23659", "pm_score": 1, "selected": false, "text": "<p>Since the database isn't being called I think you have to look at the mappings linq to sql is using. What does the Association look like? There should be an Association on both the parent and child classes.\nTake a look at the linq to sql Association between the two classes. The Association should have a ThisKey property. The cast that is failing is trying to cast the value of the property that ThisKey points to, I think.\nAs far as I can tell there can be a problem when there is more than one key and the type of the first key does not match the type that ThisKey points too. I'm not sure how linq would determine what the first key is.\nFrom the looks of it you only have one key and one foreign key so that shouldn't be the problem, but the designer, if you are using it, has been known to get creative.\nI'm pretty much guessing, but this looks like something I've seen before.</p>\n" }, { "answer_id": 238051, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Mike, I hear you. But no matter where I look, everything looks correct. I've checked and rechecked that the ResponseTableId is an int and that Id is an int. They're defined as such in the designer and when I go look at the generated code, everything again appears to be in order.</p>\n\n<p>I've examined the associations. Here they are:</p>\n\n<pre><code>[Table(Name=\"dbo.tblResponseCode\")]\npublic partial class ResponseCode : ...\n ...\n [Association(Name=\"CodebookVersion_tblResponseCode\", Storage=\"_CodebookVersion\", ThisKey=\"ResponseCodeTableId\", OtherKey=\"Id\", IsForeignKey=true)]\n public CodebookVersion CodebookVersion\n {\n ...\n }\n\n[Table(Name=\"dbo.tblResponseCodeTable\")]\n public partial class CodebookVersion : ...\n ...\n [Association(Name=\"CodebookVersion_tblResponseCode\", Storage=\"_ResponseCodes\", ThisKey=\"Id\", OtherKey=\"ResponseCodeTableId\")]\n public EntitySet&lt;ResponseCode&gt; ResponseCodes\n {\n ...\n }\n</code></pre>\n\n<p>And a screenshot of the association in case that will help:<br>\n<img src=\"https://test.cmiresearch.com/images/designer.gif\" alt=\"designer\"></p>\n\n<p>Any further thoughts?</p>\n" }, { "answer_id": 238121, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<pre><code>ResponseCode rc = new ResponseCode()\n{\n CodebookVersion = codebookVersion,\n SurveyQuestionName = \"Q11\",\n Code = 3,\n Description = \"Yet another code\"\n};\ndb.ResponseCodes.InsertOnSubmit(rc);\ndb.SubmitChanges();\n</code></pre>\n" }, { "answer_id": 259723, "author": "Toby Mills", "author_id": 12377, "author_profile": "https://Stackoverflow.com/users/12377", "pm_score": 0, "selected": false, "text": "<p>You may want to check to see that any fields in your database tables which are set by the db server when inserting a new record have that reflected in the Linq to SQL diagram. If you select a field on the Linq to SQL diagram and view its properties you will see a field called \"Auto Generated Value\" which if set to true will ensure all new records take on the default value specified in the database.</p>\n" }, { "answer_id": 259807, "author": "CAD bloke", "author_id": 492, "author_profile": "https://Stackoverflow.com/users/492", "pm_score": 0, "selected": false, "text": "<p>LINQ to SQL has been deprecated, FYI - <a href=\"http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx</a>.</p>\n" }, { "answer_id": 313104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I ran into a very similar problem. I'll link you over to my wordy post: <a href=\"http://forums.asp.net/p/1223080/2763049.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1223080/2763049.aspx</a></p>\n\n<p>And I'll also offer a solution, just a guess...</p>\n\n<pre><code> ResponseDataContext db = new ResponseDataContext(m_ConnectionString);\n CodebookVersion codebookVersion = db.CodebookVersions.Single(cv =&gt; cv.VersionTag == m_CodebookVersionTag); \n ResponseCode rc = new ResponseCode()\n { \n ResponseCodeTableId = codebookVersion.Id, \n SurveyQuestionName = \"Q11\", \n Code = 3, \n Description = \"Yet another code\"\n };\n db.ResponseCodes.InsertOnSubmit(rc);\n db.SubmitChanges();\n</code></pre>\n" }, { "answer_id": 562453, "author": "E Rolnicki", "author_id": 46449, "author_profile": "https://Stackoverflow.com/users/46449", "pm_score": 0, "selected": false, "text": "<p>Somewhere in your object graph there is a conversion error, the underlying data model (or the Linq To SQL model) has changed. This is typically something like NVARCHAR(1) -> CHAR when it should be STRING, or something similar. </p>\n\n<p>This error is not fun to hunt down, hopefully your object model is small.</p>\n" }, { "answer_id": 947926, "author": "Jim Counts", "author_id": 36737, "author_profile": "https://Stackoverflow.com/users/36737", "pm_score": 1, "selected": false, "text": "<p>Is this an example of this <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=351358\" rel=\"nofollow noreferrer\">bug</a>? If so, try running your code in .NET 4.0 now that the beta is out.</p>\n\n<p>If, like me, you aren't ready to start using the beta, you may be able to work around the problem. The issue seems to be that LINQ does not properly support relationships defined on non-primary key fields. However, the term \"primary key\" does not refer to the primary key defined on the SQL table, but the primary key defined in the LINQ designer. </p>\n\n<p>If you dragged your tables into the designer, then Visual Studio automatically inspects the primary key defined in the database and marks the corresponding class field(s) as \"primary keys\". However, these do not need to correspond to each other. You can remove the key Visual Studio chose for you, and pick another field (or group of fields). Of course, you need to make sure this is logical (you should have a unique constraint in the database on the field/fields you choose).</p>\n\n<p>So I had 2 tables/classes related to eachother using an alternative key. The parent table had 2 keys: a surrogate primary key defined as an int, and an alternative natural key defined as a string. In the LINQ designer, I had defined the association using the alternative key, and I experienced the InvalidCastException whenever trying to update that association field on the child object.\nTo work around this, I went into the LINQ designer, selected the int, and then changed the Primary Key property from True to False. Then I chose the string, and set it's Primary Key property to True. Recompiled, retested, and the InvalidCastException is gone.</p>\n\n<p>Looking at your screen shot it looks like you may be able to fix your issue by changing the LINQ primary key on ResponseCode from ResponseCode.ID to ResponseCode.ResponseCodeTableID</p>\n" }, { "answer_id": 1434526, "author": "Glen Little", "author_id": 32429, "author_profile": "https://Stackoverflow.com/users/32429", "pm_score": 0, "selected": false, "text": "<p>We had a similar problem, caused by using non-integer keys. Details and hotfix number are here: <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=351358\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=351358</a></p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm attempting to use LINQ to insert a record into a child table and I'm receiving a "Specified cast is not valid" error that has something to do w/ the keys involved. The stack trace is: > > Message: Specified cast is not valid. > > > Type: System.InvalidCastException > Source: System.Data.Linq TargetSite: > Boolean > TryCreateKeyFromValues(System.Object[], > V ByRef) HelpLink: null Stack: at > System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager`2.TryCreateKeyFromValues(Object[] > values, V& v) at > System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] > keyValues) at > System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType > type, Object[] keyValues) at > System.Data.Linq.CommonDataServices.GetCachedObject(MetaType > type, Object[] keyValues) at > System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation > assoc, Object instance) at > System.Data.Linq.ChangeProcessor.BuildEdgeMaps() > at > System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode > failureMode) at > System.Data.Linq.DataContext.SubmitChanges(ConflictMode > failureMode) at > System.Data.Linq.DataContext.SubmitChanges() > > > (.....) > > > This error is being thrown on the following code: ``` ResponseDataContext db = new ResponseDataContext(m_ConnectionString); CodebookVersion codebookVersion = db.CodebookVersions.Single(cv => cv.VersionTag == m_CodebookVersionTag); ResponseCode rc = new ResponseCode() { SurveyQuestionName = "Q11", Code = 3, Description = "Yet another code" }; codebookVersion.ResponseCodes.Add(rc); db.SubmitChanges(); //exception gets thrown here ``` The tables in question have a FK relationship between the two of them. The parent table's column is called 'id', is the PK, and is of type: INT NOT NULL IDENTITY The child table's column is called 'responseCodeTableId' and is of type: INT NOT NULL. codebookVersion (parent class) maps to table tblResponseCodeTable responseCode (childClass) maps to table tblResponseCode If I execute SQL directly, it works. e.g. ``` INSERT INTO tblResponseCode (responseCodeTableId, surveyQuestionName, code, description) VALUES (13683, 'Q11', 3, 'Yet another code') ``` Updates to the same class work properly. e.g. ``` codebookVersion.ResponseCodes[0].Description = "BlahBlahBlah"; db.SubmitChanges(); //no exception - change is committed to db ``` I've examined the variable, rc, after the .Add() operation and it does, indeed, receive the proper responseCodeTableId, just as I would expect since I'm adding it to that collection. ``` tblResponseCodeTable's full definition: COLUMN_NAME TYPE_NAME id int identity responseCodeTableId int surveyQuestionName nvarchar code smallint description nvarchar dtCreate smalldatetime ``` dtCreate has a default value of GetDate(). The only other bit of useful information that I can think of is that no SQL is ever tried against the database, so LINQ is blowing up before it ever tries (hence the error not being a SqlException). I've profiled and verified that no attempt is made to execute any statements on the database. I've read around and seen the problem when you have a relationship to a non PK field, but that doesn't fit my case. Can anyone shed any light on this situation for me? What incredibly obvious thing am I missing here? Many thanks. Paul Prewett
Post up the schema of the parent table. if you look here, some other people have had your problem. <http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3493504&SiteID=1> It appears that Linq2SQL has trouble mapping some foreign keys to some primary keys. One guy had a resolution, but I think you are already mapping to an IDENTITY column.
237,423
<p>I have written this generator code but it returns 'can't convert nil into String' when I call m.directory inside the manifest. Anyone know what had happened?</p> <pre><code>class AuthGenerator &lt; Rails::Generator::NamedBase attr_reader :user_class_name def initialize(runtime_args, runtime_options={}) @user_class_name="User" @controller_class_name="AccountController" @user_class_file_name="#{@user_class_name}.rb" @controller_class_file_name="#{@controller_class_name}.rb" end def manifest record do |m| m.class_collisions @controller_class_name, @user_class puts @user_class_name m.directory File.join('app/models', @user_class_name) end end </code></pre> <p>end</p>
[ { "answer_id": 238252, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 1, "selected": false, "text": "<p>Where is it choking? Please post the full error. You can see the source of the <code>directory</code> method <a href=\"http://api.rubyonrails.org/classes/Rails/Generator/Commands/Create.html#M001866\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Plus, you probably just want </p>\n\n<pre><code>m.directory File.join('app/models')\n</code></pre>\n\n<p>Having an app/models/user directory for your generated code is not standard -- unless you're intending namespacing, which it doesn't look like.</p>\n" }, { "answer_id": 958756, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Your initialize method needs a call to super.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16371/" ]
I have written this generator code but it returns 'can't convert nil into String' when I call m.directory inside the manifest. Anyone know what had happened? ``` class AuthGenerator < Rails::Generator::NamedBase attr_reader :user_class_name def initialize(runtime_args, runtime_options={}) @user_class_name="User" @controller_class_name="AccountController" @user_class_file_name="#{@user_class_name}.rb" @controller_class_file_name="#{@controller_class_name}.rb" end def manifest record do |m| m.class_collisions @controller_class_name, @user_class puts @user_class_name m.directory File.join('app/models', @user_class_name) end end ``` end
Where is it choking? Please post the full error. You can see the source of the `directory` method [here](http://api.rubyonrails.org/classes/Rails/Generator/Commands/Create.html#M001866). Plus, you probably just want ``` m.directory File.join('app/models') ``` Having an app/models/user directory for your generated code is not standard -- unless you're intending namespacing, which it doesn't look like.
237,432
<p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p> <pre><code>class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 </code></pre> <p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p> <pre><code>age = property(lambda self: self._get_age()) </code></pre> <p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
[ { "answer_id": 237445, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>I agree with your solution, which seems an on-the-fly template method. \n<a href=\"http://www.artima.com/forums/flat.jsp?forum=122&amp;thread=153649\" rel=\"nofollow noreferrer\">This article</a> deals with your problem and provides exactly your solution.</p>\n" }, { "answer_id": 237447, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 3, "selected": false, "text": "<p>Yes, this is the way to do it; the property declaration executes at the time the parent class' definition is executed, which means it can only \"see\" the versions of the methods which exist on the parent class. So when you redefine one or more of those methods on a child class, you need to re-declare the property using the child class' version of the method(s).</p>\n" }, { "answer_id": 237461, "author": "Kozyarchuk", "author_id": 52490, "author_profile": "https://Stackoverflow.com/users/52490", "pm_score": 2, "selected": false, "text": "<p>Something like this will work</p>\n\n<pre><code>class HackedProperty(object):\n def __init__(self, f):\n self.f = f\n def __get__(self, inst, owner): \n return getattr(inst, self.f.__name__)()\n\nclass Foo(object):\n def _get_age(self):\n return 11\n age = HackedProperty(_get_age)\n\nclass Bar(Foo):\n def _get_age(self):\n return 44\n\nprint Bar().age\nprint Foo().age\n</code></pre>\n" }, { "answer_id": 237858, "author": "piro", "author_id": 10138, "author_profile": "https://Stackoverflow.com/users/10138", "pm_score": 7, "selected": true, "text": "<p>I simply prefer to repeat the <code>property()</code> as well as you will repeat the <code>@classmethod</code> decorator when overriding a class method. </p>\n\n<p>While this seems very verbose, at least for Python standards, you may notice:</p>\n\n<p>1) for read only properties, <code>property</code> can be used as a decorator:</p>\n\n<pre><code>class Foo(object):\n @property\n def age(self):\n return 11\n\nclass Bar(Foo):\n @property\n def age(self):\n return 44\n</code></pre>\n\n<p>2) in Python 2.6, <a href=\"http://docs.python.org/library/functions.html#property\" rel=\"noreferrer\">properties grew a pair of methods</a> <code>setter</code> and <code>deleter</code> which can be used to apply to general properties the shortcut already available for read-only ones:</p>\n\n<pre><code>class C(object):\n @property\n def x(self):\n return self._x\n\n @x.setter\n def x(self, value):\n self._x = value\n</code></pre>\n" }, { "answer_id": 291707, "author": "Kamil Kisiel", "author_id": 15061, "author_profile": "https://Stackoverflow.com/users/15061", "pm_score": 4, "selected": false, "text": "<p>Another way to do it, without having to create any additional classes. I've added a set method to show what you do if you only override one of the two:</p>\n\n<pre><code>class Foo(object):\n def _get_age(self):\n return 11\n\n def _set_age(self, age):\n self._age = age\n\n age = property(_get_age, _set_age)\n\n\nclass Bar(Foo):\n def _get_age(self):\n return 44\n\n age = property(_get_age, Foo._set_age)\n</code></pre>\n\n<p>This is a pretty contrived example, but you should get the idea.</p>\n" }, { "answer_id": 14349742, "author": "Mr. B", "author_id": 712522, "author_profile": "https://Stackoverflow.com/users/712522", "pm_score": 4, "selected": false, "text": "<p>I don't agree that the chosen answer is the ideal way to allow for overriding the property methods. If you expect the getters and setters to be overridden, then you can use lambda to provide access to self, with something like <code>lambda self: self.&lt;property func&gt;</code>.</p>\n\n<p>This works (at least) for Python versions 2.4 to 3.6.</p>\n\n<p>If anyone knows a way to do this with by using property as a decorator instead of as a direct property() call, I'd like to hear it!</p>\n\n<p>Example:</p>\n\n<pre><code>class Foo(object):\n def _get_meow(self):\n return self._meow + ' from a Foo'\n def _set_meow(self, value):\n self._meow = value\n meow = property(fget=lambda self: self._get_meow(),\n fset=lambda self, value: self._set_meow(value))\n</code></pre>\n\n<p>This way, an override can be easily performed:</p>\n\n<pre><code>class Bar(Foo):\n def _get_meow(self):\n return super(Bar, self)._get_meow() + ', altered by a Bar'\n</code></pre>\n\n<p>so that:</p>\n\n<pre><code>&gt;&gt;&gt; foo = Foo()\n&gt;&gt;&gt; bar = Bar()\n&gt;&gt;&gt; foo.meow, bar.meow = \"meow\", \"meow\"\n&gt;&gt;&gt; foo.meow\n\"meow from a Foo\"\n&gt;&gt;&gt; bar.meow\n\"meow from a Foo, altered by a Bar\"\n</code></pre>\n\n<p>I discovered this on <a href=\"http://www.kylev.com/2004/10/13/fun-with-python-properties/\" rel=\"noreferrer\" title=\"omg it&#39;s ancient!\">geek at play</a>.</p>\n" }, { "answer_id": 30600839, "author": "andrew pate", "author_id": 2668869, "author_profile": "https://Stackoverflow.com/users/2668869", "pm_score": 0, "selected": false, "text": "<p>I ran into problems setting a property in a parent class from a child class. The following workround extends a property of a parent but does so by calling the _set_age method of the parent directly. Wrinkled should always be correct. It is a little javathonic though.</p>\n\n<pre><code>import threading\n\n\nclass Foo(object):\n def __init__(self):\n self._age = 0\n\n def _get_age(self):\n return self._age\n\n def _set_age(self, age):\n self._age = age\n\n age = property(_get_age, _set_age)\n\n\nclass ThreadsafeFoo(Foo):\n\n def __init__(self):\n super(ThreadsafeFoo, self).__init__()\n self.__lock = threading.Lock()\n self.wrinkled = False\n\n def _get_age(self):\n with self.__lock:\n return super(ThreadsafeFoo, self).age\n\n def _set_age(self, value):\n with self.__lock:\n self.wrinkled = True if value &gt; 40 else False\n super(ThreadsafeFoo, self)._set_age(value)\n\n age = property(_get_age, _set_age)\n</code></pre>\n" }, { "answer_id": 37355919, "author": "Nizam Mohamed", "author_id": 4522780, "author_profile": "https://Stackoverflow.com/users/4522780", "pm_score": 2, "selected": false, "text": "<p>Same as <a href=\"https://stackoverflow.com/a/14349742/4522780]\">@mr-b</a>'s but with decorator. </p>\n\n<pre><code>class Foo(object):\n def _get_meow(self):\n return self._meow + ' from a Foo'\n def _set_meow(self, value):\n self._meow = value\n @property\n def meow(self):\n return self._get_meow()\n @meow.setter\n def meow(self, value):\n self._set_meow(value)\n</code></pre>\n\n<p>This way, an override can be easily performed:</p>\n\n<pre><code>class Bar(Foo):\n def _get_meow(self):\n return super(Bar, self)._get_meow() + ', altered by a Bar'\n</code></pre>\n" }, { "answer_id": 57619695, "author": "Robin", "author_id": 9610758, "author_profile": "https://Stackoverflow.com/users/9610758", "pm_score": -1, "selected": false, "text": "<pre><code>class Foo:\n # Template method\n @property\n def age(self):\n return self.dothis()\n # Hook method of TM is accessor method of property at here\n def dothis(self):\n return 11\nclass Bar(Foo):\n def dothis(self):\n return 44\n</code></pre>\n\n<p>Same as Nizam Mohamed, just to mention that <a href=\"https://google.github.io/styleguide/pyguide.html?showone=Comments#Comments\" rel=\"nofollow noreferrer\">style guide</a> 2.13.4 using both template method and property</p>\n" }, { "answer_id": 59594225, "author": "Vladimir Zolotykh", "author_id": 4422949, "author_profile": "https://Stackoverflow.com/users/4422949", "pm_score": 2, "selected": false, "text": "<p>A possible workaround might look like:</p>\n\n<pre><code>class Foo:\n def __init__(self, age):\n self.age = age\n\n @property\n def age(self):\n print('Foo: getting age')\n return self._age\n\n @age.setter\n def age(self, value):\n print('Foo: setting age')\n self._age = value\n\n\nclass Bar(Foo):\n def __init__(self, age):\n self.age = age\n\n @property\n def age(self):\n return super().age\n\n @age.setter\n def age(self, value):\n super(Bar, Bar).age.__set__(self, value)\n\nif __name__ == '__main__':\n f = Foo(11)\n print(f.age)\n b = Bar(44)\n print(b.age)\n</code></pre>\n\n<p>It prints</p>\n\n<pre><code>Foo: setting age\nFoo: getting age\n11\nFoo: setting age\nFoo: getting age\n44\n</code></pre>\n\n<p>Got the idea from \"Python Cookbook\" by David Beazley &amp; Brian K. Jones. \nUsing Python 3.5.3 on Debian GNU/Linux 9.11 (stretch)</p>\n" }, { "answer_id": 67559102, "author": "Bastian Ebeling", "author_id": 617339, "author_profile": "https://Stackoverflow.com/users/617339", "pm_score": 0, "selected": false, "text": "<p>I think the <a href=\"https://stackoverflow.com/questions/237432/python-properties-and-inheritance#answer-59594225\">answer</a> from <a href=\"https://stackoverflow.com/users/4422949/vladimir-zolotykh\">Vladimir Zolotykh</a> is nearly optimal.<br />\nFor my unterstanding a slightly better variant might be calling the constructer of the superclass.<br />\nResulting in the following code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Foo:\n def __init__(self, age):\n self.age = age\n\n @property\n def age(self):\n print(&quot;Foo: getting age&quot;)\n return self._age\n\n @age.setter\n def age(self, value):\n print(&quot;Foo: setting age&quot;)\n self._age = value\n\n\nclass Bar(Foo):\n def __init__(self, age):\n super().__init__(age)\n\n\nif __name__ == &quot;__main__&quot;:\n a = Foo(11)\n print(a.age)\n b = Bar(44)\n print(b.age)\n</code></pre>\n<p>With this solution, there is no need to reeimplement the property for the subclass. Just tell the subclass, that it should behave like the superclass by using the constructor.</p>\n<p>The upper lines result in the following output</p>\n<pre><code>Foo: setting age\nFoo: getting age\n11\nFoo: setting age\nFoo: getting age\n44\n</code></pre>\n<p>with python3.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720/" ]
I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like: ``` class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 ``` This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works: ``` age = property(lambda self: self._get_age()) ``` So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?
I simply prefer to repeat the `property()` as well as you will repeat the `@classmethod` decorator when overriding a class method. While this seems very verbose, at least for Python standards, you may notice: 1) for read only properties, `property` can be used as a decorator: ``` class Foo(object): @property def age(self): return 11 class Bar(Foo): @property def age(self): return 44 ``` 2) in Python 2.6, [properties grew a pair of methods](http://docs.python.org/library/functions.html#property) `setter` and `deleter` which can be used to apply to general properties the shortcut already available for read-only ones: ``` class C(object): @property def x(self): return self._x @x.setter def x(self, value): self._x = value ```
237,440
<p>I have a problem whereby I want to display a view differently (a different master page), depending on where it came from, but don't know where to start...</p> <p>I have several routes which catch various different types of urls that contain different structures.</p> <p>In the code snippet below, I have a product route, and then I have a partner site route which could also go to a product page, but let's say that this partner is Pepsi, and they want their branding on the master page, rather than our own default styling. Lets say I go to <a href="http://mysite.com/products/cola.htm" rel="nofollow noreferrer">products/cola.htm</a>. This should go to the same url as <a href="http://mysite.com/partners/pepsi/products/cola.htm" rel="nofollow noreferrer">partners/pepsi/products/cola.htm</a>, and the PartnerRedirect would be able to handle the url based on the wildcard, by translating the url wildcard (in this case, "products/cola.htm") into a controller action, and forward the user on, (but simply change the master page in the view).</p> <pre><code>routes.MapRoute( "Product", "products/{product}.htm", new { controller = "Product", action = "ShowProduct" } ); routes.MapRoute( "ProductReview", "products/{product}/reviews.htm", new { controller = "Product", action = "ShowProductReview" } ); routes.MapRoute( "Partner", "partners/{partner}/{*wildcard}", new { controller = "Partners", action = "PartnerRedirect" } ); </code></pre> <p>Is this possible? And if so, how?</p> <p>Many thanks in advance.</p>
[ { "answer_id": 239021, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": true, "text": "<p>In your partners controller why don't you set a cookie that indicates which partner you want to show, and then redirects to the wildcard section of the route. That way you can show the same partner layout for all subsequent page views.</p>\n\n<p>I don't know if this is what you're looking for, but it might be an option.</p>\n" }, { "answer_id": 239363, "author": "jmcd", "author_id": 2285, "author_profile": "https://Stackoverflow.com/users/2285", "pm_score": 0, "selected": false, "text": "<p>It may be the devils work but you could put some code in the Partner View's codebehind to look at the URL and then set the master page programmatically in there?</p>\n" }, { "answer_id": 240017, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "<p>I'm not sure how you can programatically alter the master page, as I've never done that, but I'm sure it's possible (it's probably just a property on Page). </p>\n\n<p>That might be worth asking as another question.</p>\n" }, { "answer_id": 362423, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I had same issue</p>\n\n<pre><code>public class FriViewPage : ViewPage\n{\n public override string MasterPageFile\n {\n get\n {\n return \"~/Views/Shared/Site.Master\"; // base.MasterPageFile;\n }\n set\n {\n if (ViewData[\"agent\"].ToString() == \"steve\")\n base.MasterPageFile = \"~/Views/Shared/Site.Master\";\n else\n base.MasterPageFile = \"~/Views/Shared/Site2.Master\";\n }\n }\n}\n</code></pre>\n\n<p>Then just ensure all the views inherit from FriViewPage instead of ViewPage</p>\n" }, { "answer_id": 362427, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Acutally the MasterPageFile getter never appears to be called</p>\n" }, { "answer_id": 364718, "author": "Matthew", "author_id": 20162, "author_profile": "https://Stackoverflow.com/users/20162", "pm_score": 0, "selected": false, "text": "<p>You can change the MasterPage by modifying the ViewResult prior to rendering. For example, a controller action could do:</p>\n\n<pre><code>public ActionResult TestMP(int? id)\n{\n ViewData[\"Title\"] = \"MasterPage Test Page\";\n ViewData[\"Message\"] = \"Welcome to ASP.NET MVC!\";\n ViewResult result = View(\"Index\");\n if (id.HasValue)\n {\n result.MasterName = \"Site2\";\n }\n return result;\n}\n</code></pre>\n\n<p>You could accomplish the same thing with an action filter for a more generic solution.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31532/" ]
I have a problem whereby I want to display a view differently (a different master page), depending on where it came from, but don't know where to start... I have several routes which catch various different types of urls that contain different structures. In the code snippet below, I have a product route, and then I have a partner site route which could also go to a product page, but let's say that this partner is Pepsi, and they want their branding on the master page, rather than our own default styling. Lets say I go to [products/cola.htm](http://mysite.com/products/cola.htm). This should go to the same url as [partners/pepsi/products/cola.htm](http://mysite.com/partners/pepsi/products/cola.htm), and the PartnerRedirect would be able to handle the url based on the wildcard, by translating the url wildcard (in this case, "products/cola.htm") into a controller action, and forward the user on, (but simply change the master page in the view). ``` routes.MapRoute( "Product", "products/{product}.htm", new { controller = "Product", action = "ShowProduct" } ); routes.MapRoute( "ProductReview", "products/{product}/reviews.htm", new { controller = "Product", action = "ShowProductReview" } ); routes.MapRoute( "Partner", "partners/{partner}/{*wildcard}", new { controller = "Partners", action = "PartnerRedirect" } ); ``` Is this possible? And if so, how? Many thanks in advance.
In your partners controller why don't you set a cookie that indicates which partner you want to show, and then redirects to the wildcard section of the route. That way you can show the same partner layout for all subsequent page views. I don't know if this is what you're looking for, but it might be an option.
237,464
<p>Many languages have a facility to check to see if an Object is of a certain type (including parent subclasses), implemented with 'is' and used like this:</p> <pre><code>if(obj is MyType) </code></pre> <p>Or slightly more tediously you can in other languages check by using the 'as' keyword to do a soft typecast and seeing if the result null. </p> <p>I haven't used Java in years and I'm getting back up to speed on it but surely Java has a way to easily do this without delving deep into the Reflection APIs?</p> <p>Thanks in advance for answers. I have searched both here and other places but the keywords involved are so generic that even though I'm sure this has a simple answer, googling for it is hard.</p>
[ { "answer_id": 237467, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "<pre><code>if (objectReference instanceof type){\n //Your code goes here\n}\n</code></pre>\n\n<p>More info <a href=\"http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 237469, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 1, "selected": false, "text": "<p><code>obj instanceof TargetType</code> returns true just in case <code>TargetType</code> is in the type hierarchy that contains <code>obj</code>.</p>\n\n<p>See <a href=\"http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op2.html\" rel=\"nofollow noreferrer\">Sun's tutorial</a></p>\n" }, { "answer_id": 238007, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 3, "selected": false, "text": "<p>You can only use <code>instanceof</code> with a class literal: that is:</p>\n\n<pre><code>Class type = String.class;\n\nif (myObj instanceof String) // will compile\n\nif (myObj instanceof type) //will not compile\n</code></pre>\n\n<p>The alternative is to use the method <code>Class.isInstance</code></p>\n\n<pre><code>if (type.isInstance(myObj)) // will compile\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Many languages have a facility to check to see if an Object is of a certain type (including parent subclasses), implemented with 'is' and used like this: ``` if(obj is MyType) ``` Or slightly more tediously you can in other languages check by using the 'as' keyword to do a soft typecast and seeing if the result null. I haven't used Java in years and I'm getting back up to speed on it but surely Java has a way to easily do this without delving deep into the Reflection APIs? Thanks in advance for answers. I have searched both here and other places but the keywords involved are so generic that even though I'm sure this has a simple answer, googling for it is hard.
``` if (objectReference instanceof type){ //Your code goes here } ``` More info [here](http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm).
237,539
<p>My current setup binds the <code>Text</code> property of my <code>TextBox</code> to a certain <code>Uri</code> object. I'd love to use WPF's inbuilt validation to detect invalid URIs, and proceed from there. But this doesn't seem to be working?</p> <p>I would imagine that it would throw an exception if I entered, e.g., "aaaa" as a URI. Thus, triggering my current setup, which is supposed to detect exceptions like so:</p> <pre><code>&lt;TextBox Grid.Column="1" Name="txtHouseListFile" DockPanel.Dock="Right" Margin="3"&gt; &lt;TextBox.Text&gt; &lt;Binding Source="{StaticResource Settings}" Path="Default.HouseListFile" Mode="TwoWay"&gt; &lt;Binding.ValidationRules&gt; &lt;ExceptionValidationRule /&gt; &lt;/Binding.ValidationRules&gt; &lt;/Binding&gt; &lt;/TextBox.Text&gt; &lt;/TextBox&gt; </code></pre> <p>Then I would imagine I could check the various Validation properties, like so?</p> <pre><code>Validation.GetHasError(this.txtHouseListFile) </code></pre> <p>But, this appears to not work. Maybe it doesn't throw exceptions when trying to convert? Or maybe my setup's wrong? Corrections to either would be great.</p>
[ { "answer_id": 247937, "author": "decasteljau", "author_id": 12082, "author_profile": "https://Stackoverflow.com/users/12082", "pm_score": 1, "selected": false, "text": "<p>You can try create our own ValidationRule (inherit from ValidationRule). In this class, override Validate(...) and try create an URI object and catch the exceptions. In the catch, just set the e.Message to exception message.</p>\n\n<p>(I am not too sure what is your binding source. Is it a URI object or a string?)</p>\n" }, { "answer_id": 255385, "author": "decasteljau", "author_id": 12082, "author_profile": "https://Stackoverflow.com/users/12082", "pm_score": 0, "selected": false, "text": "<p>OK, I think I know what is going on. The binding doesn't know how to convert a string to a URI object (because the textbox <em>Text</em> property is a string). You need a converter to help him.</p>\n\n<p>Try this:\nCreate a converter class (inherit from IValueConverter) that:</p>\n\n<ul>\n<li>convert a string to a Uri using the Uri constructor</li>\n<li>convert a Uri to a string (using one of the multiple getters)</li>\n</ul>\n\n<p>Put your converter in the Binding. Then, the converver will throw an exception in the Uri constructor and your ExceptionValidationRule will catch it.</p>\n\n<p><a href=\"http://learnwpf.com/Posts/Post.aspx?postId=05229e33-fcd4-44d5-9982-a002f2250a64\" rel=\"nofollow noreferrer\">Look here</a> to know how to use a converter.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3191/" ]
My current setup binds the `Text` property of my `TextBox` to a certain `Uri` object. I'd love to use WPF's inbuilt validation to detect invalid URIs, and proceed from there. But this doesn't seem to be working? I would imagine that it would throw an exception if I entered, e.g., "aaaa" as a URI. Thus, triggering my current setup, which is supposed to detect exceptions like so: ``` <TextBox Grid.Column="1" Name="txtHouseListFile" DockPanel.Dock="Right" Margin="3"> <TextBox.Text> <Binding Source="{StaticResource Settings}" Path="Default.HouseListFile" Mode="TwoWay"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> ``` Then I would imagine I could check the various Validation properties, like so? ``` Validation.GetHasError(this.txtHouseListFile) ``` But, this appears to not work. Maybe it doesn't throw exceptions when trying to convert? Or maybe my setup's wrong? Corrections to either would be great.
You can try create our own ValidationRule (inherit from ValidationRule). In this class, override Validate(...) and try create an URI object and catch the exceptions. In the catch, just set the e.Message to exception message. (I am not too sure what is your binding source. Is it a URI object or a string?)
237,542
<p>I'm using GCC; __FILE__ returns the current source file's entire path and name: <code>/path/to/file.cpp</code>. Is there a way to get just the file's name <code>file.cpp</code> (without its path) at compile time? Is it possible to do this in a portable way? Can template meta programming be applied to strings?</p> <p>I am using this in an error logging macro. I really do not want my source's full path making its way into the executable.</p>
[ { "answer_id": 237556, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 2, "selected": false, "text": "<p>You might be able to do it with template metaprogramming, but there's no built-in way to do it.</p>\n\n<p>EDIT: Hm, correction. According to <a href=\"http://coding.derkeiler.com/Archive/C_CPP/comp.lang.c/2006-02/msg00698.html\" rel=\"nofollow noreferrer\">one page I just saw</a>, GCC uses the path that it's given for the file. If it's given the full name, it'll embed it; if it's only given a relative one, it'll only embed that. I haven't tried it myself though.</p>\n" }, { "answer_id": 237563, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": false, "text": "<p>I don't know of a direct way. You could use:</p>\n\n<pre><code>#line 1 \"filename.c\"\n</code></pre>\n\n<p>at the top of the source file to set the value of <code>__FILE__</code>, but I'm not sure that that's much better than hard coding it. or just using a #define to create your own macro.</p>\n\n<p>Another option might be to pass the name from your Makefile using -D and $(shell basename $&lt;)</p>\n\n<p>Edit: If you use a #define or the -D option, you should create your own new name and not try to redefine <code>__FILE__</code>.</p>\n" }, { "answer_id": 237633, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>What does your error logging macro do? I would presume at some point the macro eventually calls a function of some kind in order to do the logging, why not have the called function strip off the path component at runtime?</p>\n\n<pre><code>#define LOG(message) _log(__FILE__, message)\n\nvoid _log(file, message)\n{\n #ifndef DEBUG\n strippath(file); // in some suitable way\n #endif\n\n cerr &lt;&lt; \"Log: \" &lt;&lt; file &lt;&lt; \": \" &lt;&lt; message; // or whatever\n}\n</code></pre>\n" }, { "answer_id": 237635, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": true, "text": "<p>If you're using a <code>make</code> program, you should be able to munge the filename beforehand and pass it as a macro to <code>gcc</code> to be used in your program. For example, in your <code>makefile</code>, change the line:</p>\n<pre><code>file.o: file.c\n gcc -c -o file.o src/file.c\n</code></pre>\n<p>to:</p>\n<pre><code>file.o: src/file.c\n gcc &quot;-DMYFILE=\\&quot;`basename $&lt;`\\&quot;&quot; -c -o file.o src/file.c\n</code></pre>\n<p>This will allow you to use <code>MYFILE</code> in your code instead of <code>__FILE__</code>.</p>\n<p>The use of <code>basename</code> of the source file <code>$&lt;</code> means you can use it in generalized rules such as <code>.c.o</code>. The following code illustrates how it works. First, a <code>makefile</code>:</p>\n<pre><code>mainprog: main.o makefile\n gcc -o mainprog main.o\n\nmain.o: src/main.c makefile\n gcc &quot;-DMYFILE=\\&quot;`basename $&lt;`\\&quot;&quot; -c -o main.o src/main.c\n</code></pre>\n<p>Then a file in a subdirectory, <code>src/main.c</code>:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main (int argc, char *argv[]) {\n printf (&quot;file = %s\\n&quot;, MYFILE);\n return 0;\n}\n</code></pre>\n<p>Finally, a transcript showing it running:</p>\n<pre><code>pax:~$ mainprog\nfile = main.c\n</code></pre>\n<p>Note the <code>file =</code> line which contains <em>only</em> the base name of the file, not the directory name as well.</p>\n" }, { "answer_id": 238250, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 0, "selected": false, "text": "<p>You can take __FILE__ and the strip off the part of path you don't want (programatically). If basedir satisfies your needs, then fine. Otherwise, get source dir root from your build system, and the rest should be doable.</p>\n" }, { "answer_id": 238528, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>Consider this simple source code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main(void)\n{\n puts(__FILE__);\n return(0);\n}\n</code></pre>\n\n<p>On Solaris, with GCC 4.3.1, if I compile this using:</p>\n\n<pre><code>gcc -o x x.c &amp;&amp; ./x\n</code></pre>\n\n<p>the output is '<code>x.c</code>' If I compile it using:</p>\n\n<pre><code>gcc -o x $PWD/x.c &amp;&amp; ./x\n</code></pre>\n\n<p>then __FILE__ maps to the full path ('<code>/work1/jleffler/tmp/x.c</code>'). If I compile it using:</p>\n\n<pre><code>gcc -o x ../tmp/x.c &amp;&amp; ./x\n</code></pre>\n\n<p>then __FILE__ maps to '<code>../tmp/x.c</code>'.</p>\n\n<p>So, basically, __FILE__ is the pathname of the source file. If you build with the name you want to see in the object, all is well.</p>\n\n<p>If that is impossible (for whatever reason), then you will have to get into the fixes suggested by other people.</p>\n" }, { "answer_id": 238538, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>Taking the idea from Glomek, it can be automated like this:</p>\n\n<p>Source file x.c</p>\n\n<pre><code>#line 1 MY_FILE_NAME\n#include &lt;stdio.h&gt;\n\nint main(void)\n{\n puts(__FILE__);\n return(0);\n}\n</code></pre>\n\n<p>Compilation line (beware the single quotes outside the double quotes):</p>\n\n<pre><code>gcc -DMY_FILE_NAME='\"abcd.c\"' -o x x.c\n</code></pre>\n\n<p>The output is '<code>abcd.c</code>'.</p>\n" }, { "answer_id": 305927, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "<p>You can assign <code>__FILE__</code> to a string, and then call _splitpath() to rip the pieces out of it. This might be a Windows/MSVC-only solution, honestly I don't know. </p>\n\n<p>I know you were looking for a compile-time solution and this is a run-time solution, but I figured since you were using the filename to do (presumably run-time) error logging, this could be a simple straightforward way to get you what you need.</p>\n" }, { "answer_id": 2250739, "author": "tHeDoc", "author_id": 271711, "author_profile": "https://Stackoverflow.com/users/271711", "pm_score": 0, "selected": false, "text": "<p>Just got the same issue; found a different resolution, just thought I'd share it:</p>\n\n<p>In a header file included in all my other files:</p>\n\n<pre><code>static char * file_bname = NULL;\n#define __STRIPPED_FILE__ (file_bname ?: (file_bname = basename(__FILE__)))\n</code></pre>\n\n<p>Hope this is useful to someone else as well :)</p>\n" }, { "answer_id": 22161316, "author": "fenugrec", "author_id": 3377192, "author_profile": "https://Stackoverflow.com/users/3377192", "pm_score": 3, "selected": false, "text": "<p>Since you tagged CMake, here's a neat solution to add to your CMakeLists.txt:\n(copied from <a href=\"http://www.cmake.org/pipermail/cmake/2011-December/048281.html\" rel=\"noreferrer\">http://www.cmake.org/pipermail/cmake/2011-December/048281.html</a> ). (Note : some compilers don't support per-file COMPILE_DEFINITIONS ! but it works with gcc)</p>\n\n<pre><code>set(SRCS a/a.cpp b/b.cpp c/c.cpp d/d.cpp)\n\nforeach(f IN LISTS SRCS)\n get_filename_component(b ${f} NAME)\n set_source_files_properties(${f} PROPERTIES\n COMPILE_DEFINITIONS \"MYSRCNAME=${b}\")\nendforeach()\n\nadd_executable(foo ${SRCS})\n</code></pre>\n\n<p>Note : For my application I needed to escape the filename string like this: </p>\n\n<pre><code>COMPILE_DEFINITIONS \"MYSRCNAME=\\\"${b}\\\"\")\n</code></pre>\n" }, { "answer_id": 54377777, "author": "puchu", "author_id": 404949, "author_profile": "https://Stackoverflow.com/users/404949", "pm_score": 2, "selected": false, "text": "<p>It is easy with cmake.</p>\n\n<p><code>DefineRelativeFilePaths.cmake</code></p>\n\n<pre><code>function (cmake_define_relative_file_paths SOURCES)\n foreach (SOURCE IN LISTS SOURCES)\n file (\n RELATIVE_PATH RELATIVE_SOURCE_PATH\n ${PROJECT_SOURCE_DIR} ${SOURCE}\n )\n\n set_source_files_properties (\n ${SOURCE} PROPERTIES\n COMPILE_DEFINITIONS __RELATIVE_FILE_PATH__=\"${RELATIVE_SOURCE_PATH}\"\n )\n endforeach ()\nendfunction ()\n</code></pre>\n\n<p>Somewhere in <code>CMakeLists.txt</code></p>\n\n<pre><code>set (SOURCES ${SOURCES}\n \"${CMAKE_CURRENT_SOURCE_DIR}/common.c\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/main.c\"\n)\n\ninclude (DefineRelativeFilePaths)\ncmake_define_relative_file_paths (\"${SOURCES}\")\n</code></pre>\n\n<p><code>cmake .. &amp;&amp; make clean &amp;&amp; make VERBOSE=1</code></p>\n\n<pre><code>cc ... -D__RELATIVE_FILE_PATH__=\"src/main.c\" ... -c src/main.c\n</code></pre>\n\n<p>That's it. Now you can make pretty log messages.</p>\n\n<pre><code>#define ..._LOG_HEADER(target) \\\n fprintf(target, \"%s %s:%u - \", __func__, __RELATIVE_FILE_PATH__, __LINE__);\n</code></pre>\n\n<blockquote>\n <p>func src/main.c:22 - my error</p>\n</blockquote>\n\n<p>PS It is better to declear in <code>config.h.in</code> -> <code>config.h</code></p>\n\n<pre><code>#ifndef __RELATIVE_FILE_PATH__\n#define __RELATIVE_FILE_PATH__ __FILE__\n#endif\n</code></pre>\n\n<p>So your linter wan't provide rain of errors.</p>\n" }, { "answer_id": 64107772, "author": "Akira Cleber Nakandakare", "author_id": 1669975, "author_profile": "https://Stackoverflow.com/users/1669975", "pm_score": 2, "selected": false, "text": "<p>The question is already 12 years old and back in 2008 this solution wasn't available, but</p>\n<p>Starting with GCC 8 and CLANG 10, one can use the option <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html#index-fmacro-prefix-map\" rel=\"nofollow noreferrer\">-fmacro-prefix-map</a>.<br />\nAcording to GCC Manual:</p>\n<blockquote>\n<p>-fmacro-prefix-map=old=new<br />\nWhen preprocessing files residing in directory <em>‘old’</em>, expand the\n<code>__FILE__</code> and <code>__BASE_FILE__</code> macros as if the files resided in\ndirectory <em>‘new’</em> instead. This can be used to change an absolute path to\na relative path by using <em>‘.’</em> for <em>new</em> which can result in more\nreproducible builds that are location independent. This option also\naffects <code>__builtin_FILE()</code> during compilation. See also\n‘-ffile-prefix-map’.</p>\n</blockquote>\n<p>For instance, the makefile in my IDE (Eclipse) includes the following parameter for GCC for some files: <code>-fmacro-prefix-map=&quot;../Sources/&quot;=.</code><br />\nThus, my debug logs always show only the filenames, without the paths.</p>\n<p>Note: GCC 8.1 and Clang 10 were released in May 2018 and March 2020, respectively. So, currently, in September of 2020, only some of my environments support -fmacro-prefix-map.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
I'm using GCC; \_\_FILE\_\_ returns the current source file's entire path and name: `/path/to/file.cpp`. Is there a way to get just the file's name `file.cpp` (without its path) at compile time? Is it possible to do this in a portable way? Can template meta programming be applied to strings? I am using this in an error logging macro. I really do not want my source's full path making its way into the executable.
If you're using a `make` program, you should be able to munge the filename beforehand and pass it as a macro to `gcc` to be used in your program. For example, in your `makefile`, change the line: ``` file.o: file.c gcc -c -o file.o src/file.c ``` to: ``` file.o: src/file.c gcc "-DMYFILE=\"`basename $<`\"" -c -o file.o src/file.c ``` This will allow you to use `MYFILE` in your code instead of `__FILE__`. The use of `basename` of the source file `$<` means you can use it in generalized rules such as `.c.o`. The following code illustrates how it works. First, a `makefile`: ``` mainprog: main.o makefile gcc -o mainprog main.o main.o: src/main.c makefile gcc "-DMYFILE=\"`basename $<`\"" -c -o main.o src/main.c ``` Then a file in a subdirectory, `src/main.c`: ``` #include <stdio.h> int main (int argc, char *argv[]) { printf ("file = %s\n", MYFILE); return 0; } ``` Finally, a transcript showing it running: ``` pax:~$ mainprog file = main.c ``` Note the `file =` line which contains *only* the base name of the file, not the directory name as well.
237,553
<p>Google chrome doesn't behave the same as other browsers when encountering this nugget:</p> <pre><code>&lt;?php while (true) { echo "&lt;script type='text/javascript'&gt;\n"; echo "alert('hello');\n"; echo "&lt;/script&gt;"; flush(); sleep(5); } ?&gt; </code></pre> <p>It seems that it's waiting for the connection to terminate before doing anything.</p> <p>Other than polling how can I do a similar thing in Google Chrome?</p>
[ { "answer_id": 237616, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 1, "selected": false, "text": "<p>I wish I had access to Chrome at the moment to test out some ideas. Have you tried adding some HTML after <code>&lt;/script&gt;</code> and seeing if it renders incrementally? I imagine it would, and if so that'd be proof that Chrome doesn't want to run javascript in <code>&lt;script&gt;</code> elements while the page is loading. Of course, rendering the markup might trigger your scripts to run. If not, you could try including the javascript as external files and see if that affects execution time.</p>\n\n<p>I think browsers generally have some leeway according to the spec in when they begin executing javascript, especially as the page loads. It might not be possible to do this in a fully cross-browser way without polling.</p>\n" }, { "answer_id": 237736, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": true, "text": "<p>Some browsers require a certain number of bytes to be downloaded before rendering available data. I remember the last time I tried to do what you're doing I ended up having to dump something like 300 spaces to be sure the browser would bother with it.</p>\n" }, { "answer_id": 238246, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 0, "selected": false, "text": "<p><strong>Did you talk with Chrome developers? Did you open a bug about that?</strong> IMHO the best solution is make Chrome behave like other browsers do, rather than having a workaround for it. </p>\n\n<p>Okay, actually you probably will need a short-term workaround. But imagine a world in which each browser behaves differently in each aspect, say HTTP, HTML, CSS handling... it would not be a pleasant place!</p>\n" }, { "answer_id": 318060, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Stream is working. The answer from eyelidlessness is the solution.</p>\n\n<p>print \"2048 points[BR>\\n\";</p>\n\n<p>The [ = &lt;</p>\n\n<p>BTW look at the user-agent. Safari needs much bytes too. I think 1024. Firefox needs not so much bytes.</p>\n" }, { "answer_id": 796691, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php\n$i = 0;\nwhile (true) {\n if($i == 0) {\n echo \"&lt;html&gt;&lt;body&gt;\";\n }\n echo \"&lt;script type='text/javascript'&gt;\\n\";\n echo \"alert('hello');\\n\";\n echo \"&lt;/script&gt;\";\n if($i == 0 ) {\n $padstr = str_pad(\"\",2048,\"&amp;nbsp;\");\n echo $padstr;\n echo \"&lt;/body&gt;&lt;/html&gt;\";\n }\n flush();\n\n sleep(5);\n $i = $i + 1;\n}\n?&gt;\n</code></pre>\n\n<p>For fist time send at least 2048 bytes of data. then it will work fine. And make sure to keep script tag in a body tag. The strange thing is , in my case if I add 1024 bytes it worked. Hope this helps you</p>\n\n<p>The above program is working fine in google chrome.</p>\n" }, { "answer_id": 1469598, "author": "thomasrutter", "author_id": 53212, "author_profile": "https://Stackoverflow.com/users/53212", "pm_score": 2, "selected": false, "text": "<p>I had a similar issue to this, and solved it by adding an HTML tag (in my case &lt;br />) before each flush.</p>\n\n<p>My guess would be that Chrome waits for an element <em>which is being displayed</em> to close before triggering a re-render. That's only a guess though.</p>\n\n<p>It didn't seem to require 1024 bytes - I think I would have had just under 512 bytes when it worked.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
Google chrome doesn't behave the same as other browsers when encountering this nugget: ``` <?php while (true) { echo "<script type='text/javascript'>\n"; echo "alert('hello');\n"; echo "</script>"; flush(); sleep(5); } ?> ``` It seems that it's waiting for the connection to terminate before doing anything. Other than polling how can I do a similar thing in Google Chrome?
Some browsers require a certain number of bytes to be downloaded before rendering available data. I remember the last time I tried to do what you're doing I ended up having to dump something like 300 spaces to be sure the browser would bother with it.
237,561
<p>Edit: This code is fine. I found a logic bug somewhere that doesn't exist in my pseudo code. I was blaming it on my lack of Java experience.</p> <p>In the <strong>pseudo code</strong> below, I'm trying to parse the XML shown. A silly example maybe but my code was too large/specific for anyone to get any real value out of seeing it and learning from answers posted. So, this is more entertaining and hopefully others can learn from the answer as well as me.</p> <p>I'm new to Java but an experienced C++ programmer which makes me believe my problem lies in my understanding of the Java language.</p> <p>Problem: When the parser finishes, my Vector is full of uninitialized Cows. I create the Vector of Cows with a default capacity (which shouldn't effect it's "size" if it's anything like C++ STL Vector). When I print the contents of the Cow Vector out after the parse, it gives the right size of Vector but all the values appear never to have been set.</p> <p>Info: I have successfully done this with other parsers that don't have Vector <em>fields</em> but in this case, I'd like to use a Vector to accumulate Cow properties.</p> <p>MoreInfo: I can't use generics (Vector&lt; Cow >) so please don't point me there. :)</p> <p>Thanks in advance.</p> <pre><code>&lt;pluralcow&gt; &lt;cow&gt; &lt;color&gt;black&lt;/color&gt; &lt;age&gt;1&lt;/age&gt; &lt;/cow&gt; &lt;cow&gt; &lt;color&gt;brown&lt;/color&gt; &lt;age&gt;2&lt;/age&gt; &lt;/cow&gt; &lt;cow&gt; &lt;color&gt;blue&lt;/color&gt; &lt;age&gt;3&lt;/age&gt; &lt;/cow&gt; &lt;/pluralcow&gt; public class Handler extends DefaultHandler{ // vector to store all the cow knowledge private Vector m_CowVec; // temp variable to store cow knowledge until // we're ready to add it to the vector private Cow m_WorkingCow; // flags to indicate when to look at char data private boolean m_bColor; private boolean m_bAge; public void startElement(...tag...) { if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc // I happen to magically know how many cows there are here. m_CowVec = new Vector(numcows); }else if(tag == cow ){ // rule: multiple cow tags exist m_WorkingCow = new Cow(); }else if(tag == color){ // rule: single color within cow m_bColor = true; }else if(tag == age){ // rule: single age within cow m_bAge = true; } } public void characters(...chars...) { if(m_bColor){ m_WorkingCow.setColor(chars); }else if(m_bAge){ m_WorkingCow.setAge(chars); } } public void endElement(...tag...) { if(tag == pluralcow){ // that's all the cows }else if(tag == cow ){ m_CowVec.addElement(m_WorkingCow); }else if(tag == color){ m_bColor = false; }else if(tag == age){ m_bAge = false; } } } </code></pre>
[ { "answer_id": 237596, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": true, "text": "<p>The code looks fine to me. I say set breakpoints at the start of each function and watch it in the debugger or add some print statements. My gut tells me that either <code>characters()</code> is not being called or <code>setColor()</code> and <code>setAge()</code> don't work correctly, but that's just a guess.</p>\n" }, { "answer_id": 237605, "author": "Uri", "author_id": 23072, "author_profile": "https://Stackoverflow.com/users/23072", "pm_score": 0, "selected": false, "text": "<p>I have to say that I'm not a big fan of this design.\nHowever, are you sure that your characters is ever called ? (maybe a few system.outs would help). If it's never called, you would end up with an uninitialized cow.</p>\n\n<p>Also, I would not try to implement an XML parser myself like this since you need to be more robust against validation issues. </p>\n\n<p>You can use SAX or DOM4J, or even better, use Apache digester.</p>\n" }, { "answer_id": 237672, "author": "javelinBCD", "author_id": 3576, "author_profile": "https://Stackoverflow.com/users/3576", "pm_score": 0, "selected": false, "text": "<p>Also, if I have a schema I will use JaxB, or another code generator to speed up development of XML interface code. The code generators hide a lot of the complexity of working directly with SAX or DOM4J.</p>\n" }, { "answer_id": 237774, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 2, "selected": false, "text": "<p>When you say that the Cows are uninitialized, are the String properties initialized to null? Or empty Strings?</p>\n\n<p>I know you mentioned that this is pseudo-code, but I just wanted to point out a few potential problems:</p>\n\n<pre><code>public void startElement(...tag...)\n {\n if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc\n // I happen to magically know how many cows there are here. \n m_CowVec = new Vector(numcows);\n }else if(tag == cow ){ // rule: multiple cow tags exist\n m_WorkingCow = new Cow();\n }else if(tag == color){ // rule: single color within cow\n m_bColor = true;\n }else if(tag == age){ // rule: single age within cow\n m_bAge = true;\n }\n }\n</code></pre>\n\n<p>You really should be using tag.equals(...) instead of tag == ... here.</p>\n\n<pre><code>public void characters(...chars...)\n{\n if(m_bColor){\n m_WorkingCow.setColor(chars); \n }else if(m_bAge){\n m_WorkingCow.setAge(chars);\n }\n}\n</code></pre>\n\n<p>I'm assuming you're aware of this, but this methods is actually called with a character buffer with start and end indexes.</p>\n\n<p>Note also that characters(...) can be called multiple times for a single text block, returning small chunks in each call:\n<a href=\"http://java.sun.com/j2se/1.4.2/docs/api/org/xml/sax/ContentHandler.html#characters(char[],%20int,%20int)\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/api/org/xml/sax/ContentHandler.html#characters(char[],%20int,%20int)</a></p>\n\n<blockquote>\n <p>\"...SAX parsers may return all contiguous\n character data in a single chunk, or\n they may split it into several chunks...\"</p>\n</blockquote>\n\n<p>I doubt you'll run into that problem in the simple example you provided, but you also mentioned that this is a simplified version of a more complex problem. If in your original problem, your XML consists of large text blocks, this is something to consider.</p>\n\n<p>Finally, as others have mentioned, if you could, it's a good idea to consider an XML marshalling library (e.g., JAXB, Castor, JIBX, XMLBeans, XStream to name a few).</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22917/" ]
Edit: This code is fine. I found a logic bug somewhere that doesn't exist in my pseudo code. I was blaming it on my lack of Java experience. In the **pseudo code** below, I'm trying to parse the XML shown. A silly example maybe but my code was too large/specific for anyone to get any real value out of seeing it and learning from answers posted. So, this is more entertaining and hopefully others can learn from the answer as well as me. I'm new to Java but an experienced C++ programmer which makes me believe my problem lies in my understanding of the Java language. Problem: When the parser finishes, my Vector is full of uninitialized Cows. I create the Vector of Cows with a default capacity (which shouldn't effect it's "size" if it's anything like C++ STL Vector). When I print the contents of the Cow Vector out after the parse, it gives the right size of Vector but all the values appear never to have been set. Info: I have successfully done this with other parsers that don't have Vector *fields* but in this case, I'd like to use a Vector to accumulate Cow properties. MoreInfo: I can't use generics (Vector< Cow >) so please don't point me there. :) Thanks in advance. ``` <pluralcow> <cow> <color>black</color> <age>1</age> </cow> <cow> <color>brown</color> <age>2</age> </cow> <cow> <color>blue</color> <age>3</age> </cow> </pluralcow> public class Handler extends DefaultHandler{ // vector to store all the cow knowledge private Vector m_CowVec; // temp variable to store cow knowledge until // we're ready to add it to the vector private Cow m_WorkingCow; // flags to indicate when to look at char data private boolean m_bColor; private boolean m_bAge; public void startElement(...tag...) { if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc // I happen to magically know how many cows there are here. m_CowVec = new Vector(numcows); }else if(tag == cow ){ // rule: multiple cow tags exist m_WorkingCow = new Cow(); }else if(tag == color){ // rule: single color within cow m_bColor = true; }else if(tag == age){ // rule: single age within cow m_bAge = true; } } public void characters(...chars...) { if(m_bColor){ m_WorkingCow.setColor(chars); }else if(m_bAge){ m_WorkingCow.setAge(chars); } } public void endElement(...tag...) { if(tag == pluralcow){ // that's all the cows }else if(tag == cow ){ m_CowVec.addElement(m_WorkingCow); }else if(tag == color){ m_bColor = false; }else if(tag == age){ m_bAge = false; } } } ```
The code looks fine to me. I say set breakpoints at the start of each function and watch it in the debugger or add some print statements. My gut tells me that either `characters()` is not being called or `setColor()` and `setAge()` don't work correctly, but that's just a guess.
237,621
<p>I'm new with Objective-C, so there probably is a simple solution to this.</p> <p>I want a number to increment, but each iteration to be show on a label. (for example, it shows 1, 2, 3, 4, 5... displayed apart by an amount of time).</p> <p>I tried:</p> <pre><code>#import "testNums.h" @implementation testNums - (IBAction)start:(id)sender { int i; for(i = 0; i &lt; 10; ++i) { [outputNum setIntValue:i]; sleep(1); } } @end </code></pre> <p>and all it did was wait for 9 seconds (apparently frozen) and then displayed 9 in the text box.</p>
[ { "answer_id": 237629, "author": "jtbandes", "author_id": 23649, "author_profile": "https://Stackoverflow.com/users/23649", "pm_score": 2, "selected": false, "text": "<p>Yes, because that is what you told it to do. The graphics will not actually update until the main run loop is free to display them. You'll need to use <code>NSTimer</code> or some such method to do what you want.</p>\n\n<p>A better question might be why you want to do this?</p>\n" }, { "answer_id": 237683, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 4, "selected": true, "text": "<p>To allow the run loop to run between messages, use an <code>NSTimer</code> or delayed perform. Here's the latter:</p>\n\n<pre><code>- (IBAction) start:(id)sender {\n [self performSelector:@selector(updateTextFieldWithNumber:) withObject:[NSNumber numberWithInt:0] afterDelay:1.0];\n}\n\n- (void) updateTextFieldWithNumber:(NSNumber *)num {\n int i = [num intValue];\n [outputField setIntValue:i];\n if (i &lt; 10)\n [self performSelector:@selector(updateTextFieldWithNumber:) withObject:[NSNumber numberWithInt:++i] afterDelay:1.0];\n}\n</code></pre>\n\n<p>Here's one timer-based solution. You may find it easier to follow. You could set the text field's value from the text field:</p>\n\n<pre><code>@interface TestNums: NSObject\n{\n IBOutlet NSTextField *outputField;\n NSTimer *timer;\n int currentNumber;\n}\n\n@end\n\n@implementation TestNums\n\n- (IBAction) start:(id)sender {\n timer = [[NSTimer scheduledTimerWithTimeInterval:1.0\n target:self\n selector:@selector(updateTextField:)\n userInfo:nil\n repeats:YES] retain];\n\n //Set the field's value immediately to 0\n currentNumber = 0;\n [outputField setIntValue:currentNumber];\n}\n\n- (void) updateTextField:(NSTimer *)timer {\n [outputField setIntValue:++currentNumber];\n}\n\n@end\n</code></pre>\n\n<p>Here's an even better (cleaner) timer-based solution, using a property. You'll need to bind the text field to the property in Interface Builder (select the field, press ⌘4, choose your object, and enter <code>currentNumber</code> as the key to bind to).</p>\n\n<pre><code>@interface TestNums: NSObject\n{\n //NOTE: No outlet this time.\n NSTimer *timer;\n int currentNumber;\n}\n\n@property int currentNumber;\n\n@end\n\n@implementation TestNums\n\n@synthesize currentNumber;\n\n- (IBAction) start:(id)sender {\n timer = [[NSTimer scheduledTimerWithTimeInterval:1.0\n target:self\n selector:@selector(updateTextField:)\n userInfo:nil\n repeats:YES] retain];\n\n //Set the field's value immediately to 0\n self.currentNumber = 0;\n}\n\n- (void) updateTextField:(NSTimer *)timer {\n self.currentNumber = ++currentNumber;\n}\n\n@end\n</code></pre>\n\n<p>The property-based solution has at least two advantages:</p>\n\n<ol>\n<li>Your object doesn't need to know about the text field. (It is a model object, separate from the view object that is the text field.)</li>\n<li>To add more text fields, you simply create and bind them in IB. You don't have to add any code to the TestNums class.</li>\n</ol>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31549/" ]
I'm new with Objective-C, so there probably is a simple solution to this. I want a number to increment, but each iteration to be show on a label. (for example, it shows 1, 2, 3, 4, 5... displayed apart by an amount of time). I tried: ``` #import "testNums.h" @implementation testNums - (IBAction)start:(id)sender { int i; for(i = 0; i < 10; ++i) { [outputNum setIntValue:i]; sleep(1); } } @end ``` and all it did was wait for 9 seconds (apparently frozen) and then displayed 9 in the text box.
To allow the run loop to run between messages, use an `NSTimer` or delayed perform. Here's the latter: ``` - (IBAction) start:(id)sender { [self performSelector:@selector(updateTextFieldWithNumber:) withObject:[NSNumber numberWithInt:0] afterDelay:1.0]; } - (void) updateTextFieldWithNumber:(NSNumber *)num { int i = [num intValue]; [outputField setIntValue:i]; if (i < 10) [self performSelector:@selector(updateTextFieldWithNumber:) withObject:[NSNumber numberWithInt:++i] afterDelay:1.0]; } ``` Here's one timer-based solution. You may find it easier to follow. You could set the text field's value from the text field: ``` @interface TestNums: NSObject { IBOutlet NSTextField *outputField; NSTimer *timer; int currentNumber; } @end @implementation TestNums - (IBAction) start:(id)sender { timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTextField:) userInfo:nil repeats:YES] retain]; //Set the field's value immediately to 0 currentNumber = 0; [outputField setIntValue:currentNumber]; } - (void) updateTextField:(NSTimer *)timer { [outputField setIntValue:++currentNumber]; } @end ``` Here's an even better (cleaner) timer-based solution, using a property. You'll need to bind the text field to the property in Interface Builder (select the field, press ⌘4, choose your object, and enter `currentNumber` as the key to bind to). ``` @interface TestNums: NSObject { //NOTE: No outlet this time. NSTimer *timer; int currentNumber; } @property int currentNumber; @end @implementation TestNums @synthesize currentNumber; - (IBAction) start:(id)sender { timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTextField:) userInfo:nil repeats:YES] retain]; //Set the field's value immediately to 0 self.currentNumber = 0; } - (void) updateTextField:(NSTimer *)timer { self.currentNumber = ++currentNumber; } @end ``` The property-based solution has at least two advantages: 1. Your object doesn't need to know about the text field. (It is a model object, separate from the view object that is the text field.) 2. To add more text fields, you simply create and bind them in IB. You don't have to add any code to the TestNums class.
237,631
<p>I have two PHP files that I need to link. How can I link the files together using PHP? The effect I want is to have the user click a button, some information is proccessed on the page, and then the result is displayed in a different page, depending on the button the user clicked.Thanks</p>
[ { "answer_id": 237637, "author": "jtbandes", "author_id": 23649, "author_profile": "https://Stackoverflow.com/users/23649", "pm_score": 3, "selected": false, "text": "<p>It sounds like you might want an HTML form:</p>\n\n<pre><code>&lt;form method=\"post\" action=\"other_file.php\"&gt;\n &lt;input name=\"foo\" type=\"...\"... /&gt; ...\n&lt;/form&gt;\n</code></pre>\n\n<p>Then <code>$_POST[\"foo\"]</code> will contain the value of that input in other_file.php.</p>\n" }, { "answer_id": 237680, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 0, "selected": false, "text": "<p>In PHP's most basic setup, you can use two independent files: one generates the form, the second handles the response. You can also handle this with one file that checks to see if the form as been posted.</p>\n\n<pre><code> if (isset($_POST['foo'])) { ... }\n</code></pre>\n\n<p>or</p>\n\n<pre><code> if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }\n</code></pre>\n\n<p>Once you get beyond this level, there are must cleaner ways to build the scripts so that you keep your logic and your interfaces separate, but I'm guessing from the question that you're not there yet.</p>\n" }, { "answer_id": 237838, "author": "noob source", "author_id": 29838, "author_profile": "https://Stackoverflow.com/users/29838", "pm_score": 3, "selected": true, "text": "<p>I've interpreted your question differently to the others.</p>\n\n<p>It sounds to me like you want to create a page with two buttons on it and execute one of your two existing PHP files, depending on which button was pressed.</p>\n\n<p>If that's right, then here's a simple skeleton to achieve that. In this example, page_1.php and page_2.php are your two existing PHP files.</p>\n\n<p>Note if you're doing a lot of this stuff, you probably want to read up on the MVC (Model-View-Controller) pattern and/or try some of the popular PHP frameworks available. It's beyond the scope of this question, but basically both those things will give you a good foundation for structuring your code so that things stay managable and don't become a mess.</p>\n\n<pre><code>&lt;?php\n\nif ($_SERVER['REQUEST_METHOD'] == 'POST') {\n switch ($_POST['command']) {\n case 'show_file_1':\n include 'file_1.php';\n break;\n case 'show_file_2':\n include 'file_2.php';\n break;\n } \n exit;\n} \n\n?&gt;\n&lt;form method=\"POST\"&gt;\n &lt;button name=\"command\" value=\"show_file_1\"&gt;Show file 1&lt;/button&gt;\n &lt;button name=\"command\" value=\"show_file_2\"&gt;Show file 2&lt;/button&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Note: I've included only the relevant HTML and PHP to illustrate the point. Obviously you'd add <code>&lt;html&gt;</code>, <code>&lt;head&gt;</code> and <code>&lt;body&gt;</code> tags, and likely shuffle and modularize the PHP a bit, depending on what you're going to add.</p>\n\n<p>UPDATE: I should also add that if either of your existing PHP files contain forms that POST to themselves, you may want to change the <code>include</code> to a redirect. That is:</p>\n\n<pre><code>include 'file_1.php';\n</code></pre>\n\n<p>would become:</p>\n\n<pre><code>header('Location: http://mysite.com/file_1.php');\n</code></pre>\n\n<p>It's hard to know what to recommend without knowing the nature of your existing files.</p>\n\n<p>EDIT: I'm responding to the OP's second post this way because I don't have enough reputation to comment. Which line number do you get the unexpected <code>;</code> error? If I had to guess, I would say check that you're using a <code>:</code> (colon) and not <code>;</code> (semi-colon) at the end of the <code>case 'show_file_1'</code> and <code>case 'show_file_2'</code> lines.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24391/" ]
I have two PHP files that I need to link. How can I link the files together using PHP? The effect I want is to have the user click a button, some information is proccessed on the page, and then the result is displayed in a different page, depending on the button the user clicked.Thanks
I've interpreted your question differently to the others. It sounds to me like you want to create a page with two buttons on it and execute one of your two existing PHP files, depending on which button was pressed. If that's right, then here's a simple skeleton to achieve that. In this example, page\_1.php and page\_2.php are your two existing PHP files. Note if you're doing a lot of this stuff, you probably want to read up on the MVC (Model-View-Controller) pattern and/or try some of the popular PHP frameworks available. It's beyond the scope of this question, but basically both those things will give you a good foundation for structuring your code so that things stay managable and don't become a mess. ``` <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { switch ($_POST['command']) { case 'show_file_1': include 'file_1.php'; break; case 'show_file_2': include 'file_2.php'; break; } exit; } ?> <form method="POST"> <button name="command" value="show_file_1">Show file 1</button> <button name="command" value="show_file_2">Show file 2</button> </form> ``` Note: I've included only the relevant HTML and PHP to illustrate the point. Obviously you'd add `<html>`, `<head>` and `<body>` tags, and likely shuffle and modularize the PHP a bit, depending on what you're going to add. UPDATE: I should also add that if either of your existing PHP files contain forms that POST to themselves, you may want to change the `include` to a redirect. That is: ``` include 'file_1.php'; ``` would become: ``` header('Location: http://mysite.com/file_1.php'); ``` It's hard to know what to recommend without knowing the nature of your existing files. EDIT: I'm responding to the OP's second post this way because I don't have enough reputation to comment. Which line number do you get the unexpected `;` error? If I had to guess, I would say check that you're using a `:` (colon) and not `;` (semi-colon) at the end of the `case 'show_file_1'` and `case 'show_file_2'` lines.
237,675
<p>Here's what I am trying to do:</p> <p>Select text from a webpage I pulled up using my web browser control.After clicking a button while this text is still selected I would like a message box to pop-up displaying the text that was highlighted by the user. How do I get this functionality to work in my wpf application?</p> <p>I think I'm on the right track using mshtml but I get an error that says:</p> <blockquote> <p>Error HRESULT E_FAIL has been returned from a call to a COM component.</p> </blockquote> <p>This error will happen even when I try something small on the document like changing the title.</p> <p>The code is below:</p> <pre><code>IHTMLDocument2 doc = (IHTMLDocument2)this.webBookText.Document; doc.title = "l"; </code></pre>
[ { "answer_id": 237710, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Well, for starters it would be a lot simpler to use <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx\" rel=\"nofollow noreferrer\"><code>WebBrowser</code></a> than mshtml (note that you can still host <code>WebBrowser</code> in WPF) - this will certainly let you do simple things a lot easier:</p>\n\n<pre><code>webBook.Document.Title = \"foo\";\n</code></pre>\n\n<p>However, I can't see anything there that would let you work with selections very easily...</p>\n\n<p>You can get the selected <em>element</em> with <code>.Document.ActiveElement</code>, but this is the entire element - not the selected portion.</p>\n" }, { "answer_id": 238713, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Figured it out that error was because this wasn't in my form class</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here's what I am trying to do: Select text from a webpage I pulled up using my web browser control.After clicking a button while this text is still selected I would like a message box to pop-up displaying the text that was highlighted by the user. How do I get this functionality to work in my wpf application? I think I'm on the right track using mshtml but I get an error that says: > > Error HRESULT E\_FAIL has been returned from a call to a COM component. > > > This error will happen even when I try something small on the document like changing the title. The code is below: ``` IHTMLDocument2 doc = (IHTMLDocument2)this.webBookText.Document; doc.title = "l"; ```
Well, for starters it would be a lot simpler to use [`WebBrowser`](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx) than mshtml (note that you can still host `WebBrowser` in WPF) - this will certainly let you do simple things a lot easier: ``` webBook.Document.Title = "foo"; ``` However, I can't see anything there that would let you work with selections very easily... You can get the selected *element* with `.Document.ActiveElement`, but this is the entire element - not the selected portion.
237,691
<p>I been waiting for sometime now to bring my Asp.net Preview 4 project up to snuff, totally skipping Preview 5 just because I knew I would have some issues.</p> <p>Anyhow, here is the question and dilemma.</p> <p>I have a few areas on the site which I have an ajax update type panel that renders content from a view using this technique found here. <a href="http://www.singingeels.com/Articles/AJAX_Panels_with_ASPNET_MVC.aspx" rel="nofollow noreferrer">AJAX Panels with ASP.NET MVC</a></p> <p>This worked fine in preview 4 but now in the beta I keep getting this ..</p> <pre><code>Sys.ArgumentNullException: Value cannot be null Parameter name eventObject </code></pre> <p>It has been driving me nuts... </p> <p>My code looks like this</p> <pre><code>&lt;% using (this.Ajax.BeginForm("ReportOne", "Reports", null, new AjaxOptions { UpdateTargetId = "panel1" }, new { id = "panelOneForm" })) { } %&gt; &lt;div class="panel" id="panel1"&gt;&lt;img src="/Content/ajax-loader.gif" /&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; $get("panelOneForm").onsubmit(); &lt;/script&gt; </code></pre> <p>so basically what its doing is forcing the submit on the form, which updates panel1 with the contents from the view ReportOne.</p> <p>What am I missing? Why am I getting this error? Why did they go and change things? I love MVC but this is making me crazy.</p>
[ { "answer_id": 238855, "author": "Eilon", "author_id": 31668, "author_profile": "https://Stackoverflow.com/users/31668", "pm_score": 0, "selected": false, "text": "<p>I believe that calling someFormElement.onsubmit() simply invokes the event handlers registered for that event. To properly submit the form you should call someFormElement.submit() (without the \"on\" prefix).</p>\n\n<p>I don't think we changed anything in the AJAX helpers' behavior between ASP.NET MVC Preview 4 and ASP.NET MVC Beta.</p>\n\n<p>Thanks,\nEilon</p>\n" }, { "answer_id": 258943, "author": "Andrew Stanton-Nurse", "author_id": 29813, "author_profile": "https://Stackoverflow.com/users/29813", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, just calling submit() won't fire the onsubmit event so the MVC Ajax script won't run. When the <strong>browser</strong> calls onsubmit() for you (because the user clicked the submit button), it actually provides a parameter called <em>event</em> (which you can see if you look at the Html outputted by the Ajax helper). </p>\n\n<p>So, when you call onsubmit() manually, you need to provide this parameter (because the MVC Ajax code requires it). So, what you can do is create a \"fake\" event parameter, and pass it in to onsubmit:</p>\n\n<pre><code>&lt;% using (this.Ajax.BeginForm(\"ReportOne\", \"Reports\", null, new AjaxOptions { UpdateTargetId = \"panel1\" }, new { id = \"panelOneForm\" })) { } %&gt;\n&lt;div class=\"panel\" id=\"panel1\"&gt;&lt;img src=\"/Content/ajax-loader.gif\" /&gt;&lt;/div&gt;\n&lt;script type=\"text/javascript\"&gt;\n $get(\"panelOneForm\").onsubmit({ preventDefault: function() {} });\n&lt;/script&gt;\n</code></pre>\n\n<p>The important part is the <strong>{ preventDefault: function() {} }</strong> section, which creates a JSON object that has a method called \"preventDefault\" that does nothing. This is the only thing the MVC Ajax script does with the event object, so this should work just fine.</p>\n\n<p>Perhaps a longer term fix would be if the MVC Ajax code had a check that simply ignored a null event parameter (<em>wink</em> @Eilon :P)</p>\n" }, { "answer_id": 353344, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": true, "text": "<p>Having some irritating problems relating to this issue. Hope someone here can help me out.</p>\n\n<pre><code>\nvar event = new Object();\nfunction refreshInformation(){\ndocument.forms['MyForm'].onsubmit({preventDefault: function(){} });\n}\n</code></pre>\n\n<p>This is my current code, it works fine for updating the the form. Problem is the \"var event\" disrupts all other javascript events, if I have for example this:</p>\n\n<pre><code>\n&lt;img src=\"myimg.gif\" onmouseover=\"showmousepos(event)\" /&gt;\n</code></pre>\n\n<p>its not the mouse event that's sent to the function, instead it's my \"var event\" that I must declare to get the onsubmit to function properly.</p>\n\n<p>When using only <pre><code>onsubmit({preventDefault: function(){} }</code></pre> without the \"var event\" I get the <pre><code>Sys.ArgumentNullException: Value cannot be null Parameter name eventObject</code></pre></p>\n\n<p>I've also tried using <pre><code>submit()</code></pre> this does a full postback and totally ignores the ajaxform stuff...at least in my solution.</p>\n\n<p>Hmm...I realize this might be a little confusing, but if someone understands the problem, it would be great if you had a solution as well. =)\nIf you need more info regarding the problem please just ask and I'll try to elaborate som more.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22093/" ]
I been waiting for sometime now to bring my Asp.net Preview 4 project up to snuff, totally skipping Preview 5 just because I knew I would have some issues. Anyhow, here is the question and dilemma. I have a few areas on the site which I have an ajax update type panel that renders content from a view using this technique found here. [AJAX Panels with ASP.NET MVC](http://www.singingeels.com/Articles/AJAX_Panels_with_ASPNET_MVC.aspx) This worked fine in preview 4 but now in the beta I keep getting this .. ``` Sys.ArgumentNullException: Value cannot be null Parameter name eventObject ``` It has been driving me nuts... My code looks like this ``` <% using (this.Ajax.BeginForm("ReportOne", "Reports", null, new AjaxOptions { UpdateTargetId = "panel1" }, new { id = "panelOneForm" })) { } %> <div class="panel" id="panel1"><img src="/Content/ajax-loader.gif" /></div> <script type="text/javascript"> $get("panelOneForm").onsubmit(); </script> ``` so basically what its doing is forcing the submit on the form, which updates panel1 with the contents from the view ReportOne. What am I missing? Why am I getting this error? Why did they go and change things? I love MVC but this is making me crazy.
Having some irritating problems relating to this issue. Hope someone here can help me out. ``` var event = new Object(); function refreshInformation(){ document.forms['MyForm'].onsubmit({preventDefault: function(){} }); } ``` This is my current code, it works fine for updating the the form. Problem is the "var event" disrupts all other javascript events, if I have for example this: ``` <img src="myimg.gif" onmouseover="showmousepos(event)" /> ``` its not the mouse event that's sent to the function, instead it's my "var event" that I must declare to get the onsubmit to function properly. When using only ``` onsubmit({preventDefault: function(){} } ``` without the "var event" I get the ``` Sys.ArgumentNullException: Value cannot be null Parameter name eventObject ``` I've also tried using ``` submit() ``` this does a full postback and totally ignores the ajaxform stuff...at least in my solution. Hmm...I realize this might be a little confusing, but if someone understands the problem, it would be great if you had a solution as well. =) If you need more info regarding the problem please just ask and I'll try to elaborate som more.
237,703
<p>In cmd.exe, I can execute the command "copy c:\hello.txt c:\hello2.txt" and it worked fine. But in my C program, I ran this piece of code and got the following error:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { system("copy c:\hello.txt c:\hello2.txt"); system("pause"); return 0; } </code></pre> <p>Output: The system cannot find the file specified.</p> <p>Anybody know what is going on here?</p>
[ { "answer_id": 237706, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": true, "text": "<p>Inside C strings (and quite a few other languages that use the same escaping rules), <code>\\</code> should be <code>\\\\</code> since it's the escape character. It allows you to enter, in normal text, non-printable characters such as:</p>\n\n<ul>\n<li>the tab character <code>\\t</code>.</li>\n<li>the carriage-return character <code>\\r</code>.</li>\n<li>the newline character <code>\\n</code>.</li>\n<li>others which I won't cover in detail.</li>\n</ul>\n\n<p>Since <code>\\</code> is used as the escape character, we need a way to put an <em>actual</em> <code>'\\'</code> into a string. This is done with the sequence <code>\\\\</code>.</p>\n\n<p>Your line should therefore be: </p>\n\n<pre><code>system(\"copy c:\\\\hello.txt c:\\\\hello2.txt\");\n</code></pre>\n\n<p>This can sometimes lead to obscure errors with commands like:</p>\n\n<pre><code>FILE *fh = fopen (\"c:\\text.dat\", \"w\");\n</code></pre>\n\n<p>where the <code>\\t</code> is actually the <code>tab</code> character and the file that you're trying to open is:\n<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<kbd>c</kbd><kbd>:</kbd><kbd>TAB</kbd><kbd>e</kbd><kbd>x</kbd><kbd>t</kbd><kbd>.</kbd><kbd>d</kbd><kbd>a</kbd><kbd>t</kbd>.</p>\n" }, { "answer_id": 1809058, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>Alternatively, all the Windows functions support Unix style slashes</p>\n\n<pre><code>system(\"copy c:/hello.txt c:/hello2.txt\");\n</code></pre>\n\n<p>Some people prefer this since it's easier to spot an odd '\\'.<br>\nBut it might confuse Windows users if you display this path in a message.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In cmd.exe, I can execute the command "copy c:\hello.txt c:\hello2.txt" and it worked fine. But in my C program, I ran this piece of code and got the following error: ``` #include <iostream> using namespace std; int main() { system("copy c:\hello.txt c:\hello2.txt"); system("pause"); return 0; } ``` Output: The system cannot find the file specified. Anybody know what is going on here?
Inside C strings (and quite a few other languages that use the same escaping rules), `\` should be `\\` since it's the escape character. It allows you to enter, in normal text, non-printable characters such as: * the tab character `\t`. * the carriage-return character `\r`. * the newline character `\n`. * others which I won't cover in detail. Since `\` is used as the escape character, we need a way to put an *actual* `'\'` into a string. This is done with the sequence `\\`. Your line should therefore be: ``` system("copy c:\\hello.txt c:\\hello2.txt"); ``` This can sometimes lead to obscure errors with commands like: ``` FILE *fh = fopen ("c:\text.dat", "w"); ``` where the `\t` is actually the `tab` character and the file that you're trying to open is:             `c``:``TAB``e``x``t``.``d``a``t`.
237,716
<p>std::next_permutation (and std::prev_permutation) permute all values in the range <code>[first, last)</code> given for a total of n! permutations (assuming that all elements are unique).</p> <p>is it possible to write a function like this:</p> <pre><code>template&lt;class Iter&gt; bool next_permutation(Iter first, Iter last, Iter choice_last); </code></pre> <p>That permutes the elements in the range <code>[first, last)</code> but only chooses elements in the range <code>[first, choice_last)</code>. ie we have maybe 20 elements and want to iterate through all permutations of 10 choices of them, 20 P 10 options vs 20 P 20.</p> <ul> <li>Iter is a random access iterator for my purposes, but if it can be implemented as a bidirectional iterator, then great!</li> <li>The less amount of external memory needed the better, but for my purposes it doesn't matter.</li> <li>The chosen elements on each iteration are input to the first elements of the sequence.</li> </ul> <p><em>Is such a function possible to implement? Does anyone know of any existing implementations?</em></p> <p>Here is essentially what I am doing to hack around this. Suggestions on how to improve this are also welcome.</p> <ul> <li>Start with a vector <code>V</code> of <code>N</code> elements of which I want to visit each permutation of <code>R</code> elements chosen from it (<code>R &lt;= N</code>).</li> <li>Build a vector <code>I</code> of length <code>R</code> with values <code>{ 0, 1, 2, ... R - 1 }</code> to serve as an index to the elements of <code>V</code></li> <li>On each iteration, build a vector <code>C</code> of length <code>R</code> with values <code>{ V[I[0]], V[I[1]], ... V[I[R - 1]] }</code></li> <li>Do something with the values in <code>C</code>.</li> <li>Apply a function to permute the elements of <code>I</code> and iterate again if it was able to.</li> </ul> <p>That function looks like this:</p> <pre><code>bool NextPermutationIndices(std::vector&lt;int&gt; &amp;I, int N) { const int R = I.size(); for (int i = R - 1; ; --i) { if (I[i] &lt; N - R + i) { ++I[i]; return true; } if (i == 0) return false; if (I[i] &gt; I[i-1] + 1) { ++I[i-1]; for (int j = i; j &lt; R; ++j) I[j] = I[j-1] + 1; return true; } } } </code></pre> <p>That function is very complicated due to all the possible off-by-one errors, as well everything using it are more complicated than is probably necessary.</p> <hr> <p><strong><em>EDIT:</em></strong></p> <p>It turns out that it was <strong>significantly</strong> easier than I had even imagined. From <a href="http://photon.poly.edu/~hbr/boost/combinations.html" rel="nofollow noreferrer">here</a>, I was able to find exact implementations of many of the exact algorithms I needed (combinations, permutations, etc.).</p> <pre><code>template&lt;class BidirectionalIterator&gt; bool next_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { std::reverse(middle, last); return std::next_permutation(first, last); } </code></pre> <p>Plus there is a combination algorithm there that works in a similar way. The implementation of that is much more complication though.</p>
[ { "answer_id": 237743, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 1, "selected": false, "text": "<p>Source code for a Java combination generator is at <strong><a href=\"http://www.merriampark.com/comb.htm\" rel=\"nofollow noreferrer\">http://www.merriampark.com/comb.htm</a></strong>. Strip out the Java idioms, and it's almost exactly what you're looking for, implemented as a generator to keep a lid on your memory usage.</p>\n\n<hr>\n\n<p>This problem is from the mathematical field known as <strong>Combinatorics</strong>, which is part of <strong>Discrete mathematics</strong>. Discrete math is crucial to practitioners of computer science, as it includes nearly all of the math we use daily (like logic, algorithms, counting, relations, graph theory, etc.). I highly recommend <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201726343\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\"><em>Discrete and Combinatorial Mathematics: An applied introduction</em></a> or \n<a href=\"https://rads.stackoverflow.com/amzn/click/com/0071244743\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\"><em>Discrete Mathematics and Its Applications</em></a>, if you can afford it.</p>\n\n<p>(Note: this question is related to \"<a href=\"https://stackoverflow.com/questions/199677/algorithm-for-grouping\">Algorithm for Grouping</a>,\" but not quite a duplicate since this question asks to solve it in the general case.)</p>\n" }, { "answer_id": 237779, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 3, "selected": true, "text": "<p>To iterate over nPk permutations, I've used the <code>for_each_permutation()</code> algorithm presented in <a href=\"http://www.ddj.com/cpp/184401912\" rel=\"nofollow noreferrer\">this old CUJ article</a> before. It uses a nice algorithm from Knuth which rotates the elements in situ, leaving them in the original order at the end. Therefore, it meets your no external memory requirement. It also works for BidirectionalIterators. It doesn't meet your requirement of looking like <code>next_permutation()</code>. However, I think this is a win - I don't like stateful APIs. </p>\n" }, { "answer_id": 237802, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 0, "selected": false, "text": "<p>An algorithmic simplification would be to split this into two separate steps.</p>\n\n<ul>\n<li>Generate a list of all possible selections of R elements out of the original data.</li>\n<li>For each of those selections, create all possible permutations of the selected elements.</li>\n</ul>\n\n<p>By interleaving those operations, you can avoid allocating the intermediate lists.</p>\n\n<p>Selection can be implemented on a bidirectional iterator by skipping over non-selected items. Generate all selections, e.g. by permuting a sequence of <code>R</code> ones and <code>(N-R)</code> zeroes. This will need O(N) additional memory, but enables you to permute the original sequence in place. </p>\n" }, { "answer_id": 238692, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 0, "selected": false, "text": "<p>For what its worth, here is an implementation that sort of works.</p>\n\n<p>It requires that the elements above choice start in sorted order. It only works if there are no duplicate elements in the sequence (if there are, it misses some permutations, and doesn't end in the correct perumtation). It also might be missing some edge cases as I didn't really test it thoroughly as I have no plans on actually using it.</p>\n\n<p>One benefit of this way over <a href=\"https://stackoverflow.com/questions/237716/is-it-possible-to-write-a-function-like-nextpermutation-but-that-only-permutes#237779\">this answer's</a>, is that way doesn't visit permutations in lexicographical order, which may (but probably not) be important. It also is kind of a pain to use boost::bind sometimes to create a functor to pass to for_each.</p>\n\n<pre><code>template&lt;class Iter&gt;\nbool next_choice_permutation(Iter first, Iter choice, Iter last)\n{\n if (first == choice)\n return false;\n\n Iter i = choice;\n --i;\n if (*i &lt; *choice) {\n std::rotate(i, choice, last);\n return true;\n }\n\n while (i != first) {\n Iter j = i;\n ++j;\n std::rotate(i, j, last);\n --i;\n --j;\n for (; j != last; ++j) {\n if (*i &lt; *j)\n break;\n }\n if (j != last) {\n std::iter_swap(i, j);\n return true;\n }\n }\n std::rotate(first, ++Iter(first), last);\n return false;\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
std::next\_permutation (and std::prev\_permutation) permute all values in the range `[first, last)` given for a total of n! permutations (assuming that all elements are unique). is it possible to write a function like this: ``` template<class Iter> bool next_permutation(Iter first, Iter last, Iter choice_last); ``` That permutes the elements in the range `[first, last)` but only chooses elements in the range `[first, choice_last)`. ie we have maybe 20 elements and want to iterate through all permutations of 10 choices of them, 20 P 10 options vs 20 P 20. * Iter is a random access iterator for my purposes, but if it can be implemented as a bidirectional iterator, then great! * The less amount of external memory needed the better, but for my purposes it doesn't matter. * The chosen elements on each iteration are input to the first elements of the sequence. *Is such a function possible to implement? Does anyone know of any existing implementations?* Here is essentially what I am doing to hack around this. Suggestions on how to improve this are also welcome. * Start with a vector `V` of `N` elements of which I want to visit each permutation of `R` elements chosen from it (`R <= N`). * Build a vector `I` of length `R` with values `{ 0, 1, 2, ... R - 1 }` to serve as an index to the elements of `V` * On each iteration, build a vector `C` of length `R` with values `{ V[I[0]], V[I[1]], ... V[I[R - 1]] }` * Do something with the values in `C`. * Apply a function to permute the elements of `I` and iterate again if it was able to. That function looks like this: ``` bool NextPermutationIndices(std::vector<int> &I, int N) { const int R = I.size(); for (int i = R - 1; ; --i) { if (I[i] < N - R + i) { ++I[i]; return true; } if (i == 0) return false; if (I[i] > I[i-1] + 1) { ++I[i-1]; for (int j = i; j < R; ++j) I[j] = I[j-1] + 1; return true; } } } ``` That function is very complicated due to all the possible off-by-one errors, as well everything using it are more complicated than is probably necessary. --- ***EDIT:*** It turns out that it was **significantly** easier than I had even imagined. From [here](http://photon.poly.edu/~hbr/boost/combinations.html), I was able to find exact implementations of many of the exact algorithms I needed (combinations, permutations, etc.). ``` template<class BidirectionalIterator> bool next_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { std::reverse(middle, last); return std::next_permutation(first, last); } ``` Plus there is a combination algorithm there that works in a similar way. The implementation of that is much more complication though.
To iterate over nPk permutations, I've used the `for_each_permutation()` algorithm presented in [this old CUJ article](http://www.ddj.com/cpp/184401912) before. It uses a nice algorithm from Knuth which rotates the elements in situ, leaving them in the original order at the end. Therefore, it meets your no external memory requirement. It also works for BidirectionalIterators. It doesn't meet your requirement of looking like `next_permutation()`. However, I think this is a win - I don't like stateful APIs.
237,733
<p>I've been a bad programmer because I am doing a copy and paste. An example is that everytime i connect to a database and retrieve a recordset, I will copy the previous code and edit, copy the code that sets the datagridview and edit. I am aware of the phrase code reuse, but I have not actually used it. How can i utilize code reuse so that I don't have to copy and paste the database code and the datagridview code.,</p>
[ { "answer_id": 237738, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>Put the code into a routine and call the routine whenever you want that code to be executed.</p>\n" }, { "answer_id": 237739, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>At first, create a library with reusable functions. They can be linked with different applications. It saves a lot of time and encourages reuse.</p>\n\n<p>Also be sure the library is unit tested and documented. So it is very easy to find the right class/function/variable/constant.</p>\n" }, { "answer_id": 237742, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>For the example you give, the appropriate solution is to write a function that takes as parameters whatever it is that you edit whenever you paste the block, then call that function with the appropriate data as parameters.</p>\n" }, { "answer_id": 237754, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 0, "selected": false, "text": "<p>It depends somewhat on what programming language you're using. In most languages you can</p>\n\n<ol>\n<li>Write a function, parameterize it to allow variations</li>\n<li>Write a function object, with members to hold the varying data</li>\n<li>Develop a hierarchy of (function object?) classes that implement even more complicated variations</li>\n<li>In C++ you could also develop templates to generate the various functions or classes at compile time</li>\n</ol>\n" }, { "answer_id": 237756, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "<p>Try and get into the habit of using other people's functions and libraries.</p>\n\n<p>You'll usually find that your particular problem has a well-tested, elegant solution. </p>\n\n<p>Even if the solutions you find aren't a perfect fit, you'll probably gain a lot of insight into the problem by seeing how other people have tackled it.</p>\n" }, { "answer_id": 237759, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 2, "selected": false, "text": "<p>Check out Martin Fowler's <a href=\"http://martinfowler.com/books.html#refactoring\" rel=\"nofollow noreferrer\">book</a> on <a href=\"http://en.wikipedia.org/wiki/Refactoring\" rel=\"nofollow noreferrer\">refactoring</a>, or some of the numerous refactoring related internet resources (also on stackoverflow), to find out how you could improve code that has smells of duplication.</p>\n" }, { "answer_id": 237773, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 3, "selected": false, "text": "<p>The essence of code reuse is to take a common operation and parameterize it so it can accept a variety of inputs.</p>\n\n<p>Take humble <code>printf</code>, for example. Imagine if you did not have <code>printf</code>, and only had <code>write</code>, or something similar:</p>\n\n<pre><code>//convert theInt to a string and write it out.\nchar c[24];\nitoa(theInt, c, 10);\nputs(c);\n</code></pre>\n\n<p>Now this sucks to have to write every time, and is actually kind of buggy. So some smart programmer decided he was tired of this and wrote a better function, that in one fell swoop print stuff to stdout.</p>\n\n<pre><code>printf(\"%d\", theInt);\n</code></pre>\n\n<p>You don't need to get as fancy as <code>printf</code> with it's variadic arguments and format string. Even just a simple routine such as:</p>\n\n<pre><code>void print_int(int theInt)\n{\n char c[24];\n itoa(theInt, c, 10);\n puts(c);\n}\n</code></pre>\n\n<p>would do the trick nickely. This way, if you want to change <code>print_int</code> to always print to stderr you could update it to be:</p>\n\n<pre><code>void print_int(int theInt)\n{\n fprintf(stderr, \"%d\", theInt);\n}\n</code></pre>\n\n<p>and all your integers would now magically be printed to standard error.</p>\n\n<p>You could even then bundle that function and others you write up into a library, which is just a collection of code you can load in to your program.</p>\n\n<p>Following the practice of code reuse is why you even have a database to connect to: someone created some code to store records on disk, reworked it until it was usable by others, and decided to call it a database.</p>\n\n<p>Libraries do not magically appear. They are created by programmers to make their lives easier and to allow them to work faster.</p>\n" }, { "answer_id": 237782, "author": "Ather", "author_id": 1065163, "author_profile": "https://Stackoverflow.com/users/1065163", "pm_score": 0, "selected": false, "text": "<p>I'll do this at two levels. First within a class or namespace, put that code piece that is reused in that scope in a separate method and make sure it is being called. </p>\n\n<p>Second is something similar to the case that you are describing. That is a good candidate to be put in a library or a helper/utility class that can be reused more broadly. </p>\n\n<p>It is important to evaluate everything that you are doing with an perspective whether it can be made available to others for reuse. This should be a fundamental approach to programming that most of us dont realize. </p>\n\n<p>Note that anything that is to be reused needs to be documented in more detail. Its naming convention be distinct, all the parameters, return results and any constraints/limitations/pre-requisites that are needed should be clearly documented (in code or help files).</p>\n" }, { "answer_id": 237951, "author": "Aristotle Ucab", "author_id": 31445, "author_profile": "https://Stackoverflow.com/users/31445", "pm_score": 1, "selected": false, "text": "<p>I think the best way to answer your problem is that create a separate assembly for your important functions.. in this way you can create extension methods or modify the helper assemble itself.. think of this function..</p>\n\n<p>ExportToExcel(List date, string filename)</p>\n\n<p>this method can be use for your future excel export functions so why don't store it in your own helper assembly.. i this way you just add reference to these assemblies.</p>\n" }, { "answer_id": 237957, "author": "zvrba", "author_id": 2583, "author_profile": "https://Stackoverflow.com/users/2583", "pm_score": 0, "selected": false, "text": "<p>Easy: whenever you catch yourself copy-pasting code, take it out <em>immediately</em> (i.e., don't do it after you've already CP'd code several times) into a new function.</p>\n" }, { "answer_id": 237967, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": true, "text": "<p>Depending on the size of the project can change the answer.</p>\n\n<p>For a <strong>smaller</strong> project I would recommend setting up a DatabaseHelper class that does all your DB access. It would just be a wrapper around opening/closing connections and execution of the DB code. Then at a higher level you can just write the DBCommands that will be executed.</p>\n\n<p>A similar technique <em>could</em> be used for a larger project, but would need some additional work, interfaces need to be added, DI, as well as abstracting out what you need to know about the database.</p>\n\n<p>You might also try looking into ORM, DAAB, or over to the <a href=\"http://msdn.microsoft.com/en-us/practices/bb190351.aspx#RR\" rel=\"nofollow noreferrer\">Patterns and Practices Group</a></p>\n\n<p>As far as how to prevent the ole C&amp;P? - Well as you write your code, you need to periodically review it, if you have similar blocks of code, that only vary by a parameter or two, that is always a good candidate for refactoring into its own method.</p>\n\n<p>Now for my pseudo code example:</p>\n\n<pre><code>Function GetCustomer(ID) as Customer\n Dim CMD as New DBCmd(\"SQL or Stored Proc\")\n CMD.Paramaters.Add(\"CustID\",DBType,Length).Value = ID\n Dim DHelper as New DatabaseHelper\n DR = DHelper.GetReader(CMD)\n Dim RtnCust as New Customer(Dx)\n Return RtnCust\nEnd Function\n\nClass DataHelper\n Public Function GetDataTable(cmd) as DataTable\n Write the DB access code stuff here.\n GetConnectionString\n OpenConnection\n Do DB Operation\n Close Connection\n End Function\n Public Function GetDataReader(cmd) as DataReader\n Public Function GetDataSet(cmd) as DataSet\n ... And So on ...\nEnd Class\n</code></pre>\n" }, { "answer_id": 238038, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Good rule of thumb is if you use same piece three times, and it's obviously possible to generalize it, than make it a procedure/function/library.</p>\n\n<p>However, as I am getting older, and also more experienced as a professional developer, I am more inclined to see code reuse as not always the best idea, for two reasons:</p>\n\n<ol>\n<li><p>It's difficult to anticipate future needs, so it's very hard to define APIs so you would really use them next time. It can cost you twice as much time - once you make it more general just so that second time you are going to rewrite it anyway. It seems to me that especially Java projects of late are prone to this, they seem to be always rewritten in the framework du jour, just to be more \"easier to integrate\" or whatever in the future.</p></li>\n<li><p>In a larger organization (I am a member of one), if you have to rely on some external team (either in-house or 3rd party), you can have a problem. Your future then depends on their funding and their resources. So it can be a big burden to use foreign code or library. In a similar fashion, if you share a piece of code to some other team, they can then expect that you will maintain it.</p></li>\n</ol>\n\n<p>Note however, these are more like business reasons, so in open source, it's almost invariably a good thing to be reusable.</p>\n" }, { "answer_id": 239343, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 2, "selected": false, "text": "<p>to get code reuse you need to become a master of...</p>\n\n<ol>\n<li>Giving things names that capture their essence. This is really really important</li>\n<li>Making sure that it only does one thing. This is really comes back to the first point, if you can't name it by its essence, then often its doing too much.</li>\n<li>Locating the thing somewhere logical. Again this comes back to being able to name things well and capturing its essence...</li>\n<li>Grouping it with things that build on a central concept. Same as above, but said differntly :-)</li>\n</ol>\n" }, { "answer_id": 7440396, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p>The first thing to note is that by using copy-and-paste, you are reusing code - albeit not in the most efficient way.\nYou have recognised a situation where you have come up with a solution previously.</p>\n\n<p>There are two main scopes that you need to be aware of when thinking about code reuse. Firstly, code reuse within a project and, secondly, code reuse between projects.</p>\n\n<p>The fact that you have a piece of code that you can copy and paste within a project should be a cue that the piece of code that you're looking at is useful elsewhere. That is the time to make it into a function, and make it available within the project.\nIdeally you should replace all occurrances of that code with your new function, so that it (a) reduces redundant code and (b) ensures that any bugs in that chunk of code only need to be fixed in one function instead of many.</p>\n\n<p>The second scope, code reuse across projects, requires some more organisation to get the maximum benefit. This issue has been addressed in a couple of other SO questions eg. <a href=\"https://stackoverflow.com/questions/237946/how-do-i-index-and-make-available-reusable-code\">here</a> and <a href=\"https://stackoverflow.com/questions/145720/what-techniques-do-you-use-to-maximise-code-reuse\">here</a>.</p>\n\n<p>A good start is to organise code that is likely to be reused across projects into source files that are as self-contained as possible. Minimise the amount of supporting, project specific, code that is required as this will make it easier to reuse entire files in a new project. This means minimising the use of project specific data-types, minimising the use project specific global variables, etc.</p>\n\n<p>This may mean creating utility files that contain functions that you know are going to be useful in your environment. eg. Common database functions if you often develop projects that depend on databases.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26087/" ]
I've been a bad programmer because I am doing a copy and paste. An example is that everytime i connect to a database and retrieve a recordset, I will copy the previous code and edit, copy the code that sets the datagridview and edit. I am aware of the phrase code reuse, but I have not actually used it. How can i utilize code reuse so that I don't have to copy and paste the database code and the datagridview code.,
Depending on the size of the project can change the answer. For a **smaller** project I would recommend setting up a DatabaseHelper class that does all your DB access. It would just be a wrapper around opening/closing connections and execution of the DB code. Then at a higher level you can just write the DBCommands that will be executed. A similar technique *could* be used for a larger project, but would need some additional work, interfaces need to be added, DI, as well as abstracting out what you need to know about the database. You might also try looking into ORM, DAAB, or over to the [Patterns and Practices Group](http://msdn.microsoft.com/en-us/practices/bb190351.aspx#RR) As far as how to prevent the ole C&P? - Well as you write your code, you need to periodically review it, if you have similar blocks of code, that only vary by a parameter or two, that is always a good candidate for refactoring into its own method. Now for my pseudo code example: ``` Function GetCustomer(ID) as Customer Dim CMD as New DBCmd("SQL or Stored Proc") CMD.Paramaters.Add("CustID",DBType,Length).Value = ID Dim DHelper as New DatabaseHelper DR = DHelper.GetReader(CMD) Dim RtnCust as New Customer(Dx) Return RtnCust End Function Class DataHelper Public Function GetDataTable(cmd) as DataTable Write the DB access code stuff here. GetConnectionString OpenConnection Do DB Operation Close Connection End Function Public Function GetDataReader(cmd) as DataReader Public Function GetDataSet(cmd) as DataSet ... And So on ... End Class ```
237,745
<p>Does any one know of some kind of Comparator factory in Java, with a </p> <pre><code>public Comparator getComparatorForClass(Class clazz) {} </code></pre> <p>It would return Comparators for stuff like String, Double, Integer but would have a</p> <pre><code>public void addComparatorForClass(Class clazz, Comparator comparator) {} </code></pre> <p>For arbitrary types.</p>
[ { "answer_id": 237752, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 4, "selected": false, "text": "<p>Instead of:</p>\n\n<pre><code>factory.getComparatorForClass(x.getClass()).compare(x, y)\n</code></pre>\n\n<p>you could simply implement <code>Comparable</code> and write:</p>\n\n<pre><code>x.compareTo(y)\n</code></pre>\n\n<p>String, the primitive wrappers, and standard collections already implement <code>Comparable</code>.</p>\n" }, { "answer_id": 237753, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 2, "selected": false, "text": "<p>I'm not aware of anything like that off the top of my head. If you really need something like this, it shouldn't be too difficult to implement one yourself.</p>\n\n<p>However, could you elaborate on why you need something like this? There typically should not be a \"default\" comparator for classes. If the class has some sort of natural ordering, you really ought to have it implement <code>java.lang.Comparable</code>, and implement <code>Comparable#compareTo(Object) : int</code> instead.</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html</a></p>\n" }, { "answer_id": 237755, "author": "IAdapter", "author_id": 30453, "author_profile": "https://Stackoverflow.com/users/30453", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/builder/CompareToBuilder.html\" rel=\"noreferrer\"><code>CompareToBuilder</code></a> from Commons Lang.</p>\n<blockquote>\n<p>Assists in implementing Comparable.compareTo(Object) methods.</p>\n<p>To use this class write code as follows:</p>\n<pre><code>public class MyClass {\n String field1;\n int field2;\n boolean field3;\n\n ...\n\n public int compareTo(Object o) {\n MyClass myClass = (MyClass) o;\n return new CompareToBuilder()\n .appendSuper(super.compareTo(o)\n .append(this.field1, myClass.field1)\n .append(this.field2, myClass.field2)\n .append(this.field3, myClass.field3)\n .toComparison();\n }\n}\n</code></pre>\n</blockquote>\n" }, { "answer_id": 237954, "author": "Aristotle Ucab", "author_id": 31445, "author_profile": "https://Stackoverflow.com/users/31445", "pm_score": 1, "selected": false, "text": "<p>Comparator are need to be extend.. this is based on the reusable code implementation.. in these method you can have a custom comparison of data.. the implementation is just simple.. just implement the Comparator interface.. override its compareto method and place the comparison code.. and return which you think is greater in terms of values..</p>\n" }, { "answer_id": 5439379, "author": "Aetherus", "author_id": 677605, "author_profile": "https://Stackoverflow.com/users/677605", "pm_score": 0, "selected": false, "text": "<p>Default comparator is not exist in Java. However, if you are coding with, for example, a customized searcher, which intends to use comparator rather than the compareTo() method of derived type of Comparable class, you may write a static inner comparator class as the default comparator, simply implementing the compare() method by calling the compareTo().</p>\n\n<p>Example:</p>\n\n<p>class Searcher> {\n private Comparator comparator;</p>\n\n<pre><code>Searcher(Comparator&lt;T&gt; comparator) {\n this.comparator = comparator;\n}\n\nSearcher() {\n this(new DefaultComparator&lt;T&gt;());\n}\n\nint search(...) {\n ...\n}\n\nprivate static class DefaultComparator&lt;E extends Comparable&lt;E&gt;&gt; \n implements Comparator&lt;E&gt; {\n public int compare(E o1, E o2) {\n return o1.compareTo(o2);\n }\n}\n</code></pre>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does any one know of some kind of Comparator factory in Java, with a ``` public Comparator getComparatorForClass(Class clazz) {} ``` It would return Comparators for stuff like String, Double, Integer but would have a ``` public void addComparatorForClass(Class clazz, Comparator comparator) {} ``` For arbitrary types.
Instead of: ``` factory.getComparatorForClass(x.getClass()).compare(x, y) ``` you could simply implement `Comparable` and write: ``` x.compareTo(y) ``` String, the primitive wrappers, and standard collections already implement `Comparable`.
237,757
<p>I have a php script that is executing an executable that writes to a serial port. However, everytime it runs <pre>system("c:\Untitled1.exe")</pre> it just opens up a cmd window and freezes.</p> <p>Anybody know how to fix this? Or if there is an easier way to get PHP to write to the serial port directly? (I've already tried these two: <a href="http://blogs.vinuthomas.com/2007/04/09/php-and-serial-ports/" rel="nofollow noreferrer">http://blogs.vinuthomas.com/2007/04/09/php-and-serial-ports/</a> and they don't work for me)</p> <p>P.S. I am on Windows XP</p>
[ { "answer_id": 237797, "author": "lacop", "author_id": 894, "author_profile": "https://Stackoverflow.com/users/894", "pm_score": 0, "selected": false, "text": "<p>AFAIK <code>system()</code> call blocks the execution until the program finishes. Maybe using <code>popen()</code>, <code>fread()</code> and <code>pclose()</code> could solve this.</p>\n\n<p>See <a href=\"http://php.net/manual/en/function.popen.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.popen.php</a> for more info.</p>\n" }, { "answer_id": 237827, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 1, "selected": false, "text": "<p>What happens when you run \"Untitled1.exe\" - does it work outside of the php environment?</p>\n\n<p>I would advise persevering with the loaded extension method - it's a much better way of implementing this.</p>\n\n<p>If both methods aren't working then maybe the problem is somewhere else - related to permissions or configuration.</p>\n" }, { "answer_id": 238261, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 0, "selected": false, "text": "<p>I believe the trick under win32 is to run start.exe /B from php to execute and forget. :)\nGive it a shot!</p>\n\n<p>You can get the help for start.exe by running it through cmd : start /?</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a php script that is executing an executable that writes to a serial port. However, everytime it runs ``` system("c:\Untitled1.exe") ``` it just opens up a cmd window and freezes. Anybody know how to fix this? Or if there is an easier way to get PHP to write to the serial port directly? (I've already tried these two: <http://blogs.vinuthomas.com/2007/04/09/php-and-serial-ports/> and they don't work for me) P.S. I am on Windows XP
What happens when you run "Untitled1.exe" - does it work outside of the php environment? I would advise persevering with the loaded extension method - it's a much better way of implementing this. If both methods aren't working then maybe the problem is somewhere else - related to permissions or configuration.
237,763
<p>I have a CSV file that has a column that contains strings that look like integers. That is they should be dealt with as strings, but since they are numbers they appear to be imported as integers (dropping off the leading zeroes).</p> <p>Example Data:</p> <ul> <li>0000000000079</li> <li>0000999000012</li> <li>0001002000005 </li> <li>0004100000007</li> </ul> <p>The problem I'm seeing is that the last example data point comes through as DBNull.Value. I'm assuming this is because OleDB is treating that column as an integer (the data points come through without their leading zeroes also) and that 0004100000007 is greater than the largest integer value.</p> <p>Is there some way to say "column [0] is a string, don't read it as an integer"? When reading the data?</p> <p>The code I am currently using is:</p> <pre><code>OleDbConnection dbConn = new OleDbConnection(SourceConnectionString); OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM test.csv", dbConn); dbConn.Open(); OleDbDataReader dbReader = dbCommand.ExecuteReader(); while (dbReader.Read()) { if (dbReader[0] != DBNull.Value) { // do some work } } </code></pre>
[ { "answer_id": 237771, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>Have you tried using this <a href=\"http://www.codeproject.com/KB/database/CsvReader.aspx\" rel=\"nofollow noreferrer\">CSV reader</a>? It is generally very respected. Perhaps give it a go...</p>\n" }, { "answer_id": 237823, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 2, "selected": false, "text": "<p>Try to use GetString() method in the reader when you need to read the column as string:</p>\n\n<pre><code>string myStringValue = reader.GetString(0);\n</code></pre>\n" }, { "answer_id": 264844, "author": "Michael Prewecki", "author_id": 4403, "author_profile": "https://Stackoverflow.com/users/4403", "pm_score": 1, "selected": false, "text": "<p>Do you have control of the export process? If so can data be exported to CSV with quotes around the string items? </p>\n\n<p>If this is a one of job then just import the file into a predfined SQL table using Integration Services, but I suspect this will be a recurring task.</p>\n" }, { "answer_id": 577539, "author": "JoelHess", "author_id": 14509, "author_profile": "https://Stackoverflow.com/users/14509", "pm_score": 1, "selected": false, "text": "<p>There's a Schema.ini file that needs to be used to specify the info about the file. It includes field types and lengths, whether there are column headers and what the field delimiter is.</p>\n\n<p>Here's the MSDN Info on it.<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms709353.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms709353.aspx</a></p>\n" }, { "answer_id": 5695216, "author": "user310291", "author_id": 310291, "author_profile": "https://Stackoverflow.com/users/310291", "pm_score": 0, "selected": false, "text": "<p>I'm no expert but do you cope with fixed file format ?\n<a href=\"http://csharptutorial.com/blog/exclusive-how-to-export-a-datatable-to-a-fixed-file-format-the-easy-way-using-odbc-or-jet-engine/\" rel=\"nofollow\">http://csharptutorial.com/blog/exclusive-how-to-export-a-datatable-to-a-fixed-file-format-the-easy-way-using-odbc-or-jet-engine/</a></p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25719/" ]
I have a CSV file that has a column that contains strings that look like integers. That is they should be dealt with as strings, but since they are numbers they appear to be imported as integers (dropping off the leading zeroes). Example Data: * 0000000000079 * 0000999000012 * 0001002000005 * 0004100000007 The problem I'm seeing is that the last example data point comes through as DBNull.Value. I'm assuming this is because OleDB is treating that column as an integer (the data points come through without their leading zeroes also) and that 0004100000007 is greater than the largest integer value. Is there some way to say "column [0] is a string, don't read it as an integer"? When reading the data? The code I am currently using is: ``` OleDbConnection dbConn = new OleDbConnection(SourceConnectionString); OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM test.csv", dbConn); dbConn.Open(); OleDbDataReader dbReader = dbCommand.ExecuteReader(); while (dbReader.Read()) { if (dbReader[0] != DBNull.Value) { // do some work } } ```
Try to use GetString() method in the reader when you need to read the column as string: ``` string myStringValue = reader.GetString(0); ```
237,804
<p><a href="http://en.wikipedia.org/wiki/C%2B%2B11" rel="noreferrer">C++11</a> introduces <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2378.pdf" rel="noreferrer">user-defined literals</a> which will allow the introduction of new literal syntax based on existing literals (<code>int</code>, <code>hex</code>, <code>string</code>, <code>float</code>) so that any type will be able to have a literal presentation.</p> <p><strong>Examples:</strong></p> <pre><code>// imaginary numbers std::complex&lt;long double&gt; operator "" _i(long double d) // cooked form { return std::complex&lt;long double&gt;(0, d); } auto val = 3.14_i; // val = complex&lt;long double&gt;(0, 3.14) // binary values int operator "" _B(const char*); // raw form int answer = 101010_B; // answer = 42 // std::string std::string operator "" _s(const char* str, size_t /*length*/) { return std::string(str); } auto hi = "hello"_s + " world"; // + works, "hello"_s is a string not a pointer // units assert(1_kg == 2.2_lb); // give or take 0.00462262 pounds </code></pre> <p>At first glance this looks very cool but I'm wondering how applicable it really is, when I tried to think of having the suffixes <code>_AD</code> and <code>_BC</code> create dates I found that it's problematic due to operator order. <code>1974/01/06_AD</code> would first evaluate <code>1974/01</code> (as plain <code>int</code>s) and only later the <code>06_AD</code> (to say nothing of August and September having to be written without the <code>0</code> for octal reasons). This can be worked around by having the syntax be <code>1974-1/6_AD</code> so that the operator evaluation order works but it's clunky. </p> <p>So what my question boils down to is this, do you feel this feature will justify itself? What other literals would you like to define that will make your C++ code more readable?</p> <hr> <p>Updated syntax to fit the final draft on June 2011</p>
[ { "answer_id": 237812, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 2, "selected": false, "text": "<p>I have never needed or wanted this feature (but this could be the <a href=\"http://www.paulgraham.com/avg.html\" rel=\"nofollow noreferrer\">Blub</a> effect). My knee jerk reaction is that it's lame, and likely to appeal to the same people who think that it's cool to overload operator+ for any operation which could remotely be construed as adding. </p>\n" }, { "answer_id": 237821, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 5, "selected": false, "text": "<p>It's very nice for mathematical code. Out of my mind I can see the use for the following operators:</p>\n\n<p>deg for degrees. That makes writing absolute angles much more intuitive.</p>\n\n<pre><code>double operator \"\"_deg(long double d)\n{ \n // returns radians\n return d*M_PI/180; \n}\n</code></pre>\n\n<p>It can also be used for various fixed point representations (which are still in use in the field of DSP and graphics).</p>\n\n<pre><code>int operator \"\"_fix(long double d)\n{ \n // returns d as a 1.15.16 fixed point number\n return (int)(d*65536.0f); \n}\n</code></pre>\n\n<p>These look like nice examples how to use it. They help to make constants in code more readable. It's another tool to make code unreadable as well, but we already have so much tools abuse that one more does not hurt much.</p>\n" }, { "answer_id": 237837, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 3, "selected": false, "text": "<p>Hmm... I have not thought about this feature yet. Your sample was well thought out and is certainly interesting. C++ is very powerful as it is now, but unfortunately the syntax used in pieces of code you read is at times overly complex. Readability is, if not all, then at least much. And such a feature would be geared for more readability. If I take your last example</p>\n\n<pre><code>assert(1_kg == 2.2_lb); // give or take 0.00462262 pounds\n</code></pre>\n\n<p>... I wonder how you'd express that today. You'd have a KG and a LB class and you'd compare implicit objects:</p>\n\n<pre><code>assert(KG(1.0f) == LB(2.2f));\n</code></pre>\n\n<p>And that would do as well. With types that have longer names or types that you have no hopes of having such a nice constructor for sans writing an adapter, it might be a nice addition for on-the-fly implicit object creation and initialization. On the other hand, you can already create and initialize objects using methods, too.</p>\n\n<p>But I agree with Nils on mathematics. C and C++ trigonometry functions for example require input in radians. I think in degrees though, so a very short implicit conversion like Nils posted is very nice.</p>\n\n<p>Ultimately, it's going to be syntactic sugar however, but it will have a slight effect on readability. And it will probably be easier to write some expressions too (sin(180.0deg) is easier to write than sin(deg(180.0)). And then there will be people who abuse the concept. But then, language-abusive people should use very restrictive languages rather than something as expressive as C++.</p>\n\n<p>Ah, my post says basically nothing except: it's going to be okay, the impact won't be too big. Let's not worry. :-)</p>\n" }, { "answer_id": 237885, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": -1, "selected": false, "text": "<p>Line noise in that thing is huge. Also it's horrible to read.</p>\n\n<p>Let me know, did they reason that new syntax addition with any kind of examples? For instance, do they have couple of programs that already use C++0x?</p>\n\n<p>For me, this part:</p>\n\n<pre><code>auto val = 3.14_i\n</code></pre>\n\n<p><strong>Does not justify this part:</strong></p>\n\n<pre><code>std::complex&lt;double&gt; operator \"\"_i(long double d) // cooked form\n{ \n return std::complex(0, d);\n}\n</code></pre>\n\n<p>Not even if you'd use the i-syntax in 1000 other lines as well. If you write, you probably write 10000 lines of something else along that as well. Especially when you will still probably write mostly everywhere this:</p>\n\n<pre><code>std::complex&lt;double&gt; val = 3.14i\n</code></pre>\n\n<p>'auto' -keyword may be justified though, only perhaps. But lets take just C++, because it's better than C++0x in this aspect.</p>\n\n<pre><code>std::complex&lt;double&gt; val = std::complex(0, 3.14);\n</code></pre>\n\n<p>It's like.. that simple. Even thought all the std and pointy brackets are just lame if you use it about everywhere. I don't start guessing what syntax there's in C++0x for turning std::complex under complex.</p>\n\n<pre><code>complex = std::complex&lt;double&gt;;\n</code></pre>\n\n<p>That's perhaps something straightforward, but I don't believe it's that simple in C++0x.</p>\n\n<pre><code>typedef std::complex&lt;double&gt; complex;\n\ncomplex val = std::complex(0, 3.14);\n</code></pre>\n\n<p>Perhaps? >:) </p>\n\n<p>Anyway, the point is: writing 3.14i instead of std::complex(0, 3.14); does not save you much time in overall except in few super special cases.</p>\n" }, { "answer_id": 238057, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 8, "selected": false, "text": "<p>At first sight, it seems to be simple syntactic sugar.</p>\n<p>But when looking deeper, we see it's more than syntactic sugar, as <strong>it extends the C++ user's options to create user-defined types that behave exactly like distinct built-in types.</strong> In this, this little &quot;bonus&quot; is a very interesting C++11 addition to C++.</p>\n<h2>Do we really need it in C++?</h2>\n<p>I see few uses in the code I wrote in the past years, but just because I didn't use it in C++ doesn't mean it's not interesting for <em>another C++ developer</em>.</p>\n<p>We had used in C++ (and in C, I guess), compiler-defined literals, to type integer numbers as short or long integers, real numbers as float or double (or even long double), and character strings as normal or wide chars.</p>\n<p><strong>In C++, we had the possibility to create our own types</strong> (i.e. classes), with potentially no overhead (inlining, etc.). We had the possibility to add operators to their types, to have them behave like similar built-in types, which enables C++ developers to use matrices and complex numbers as naturally as they would have if these have been added to the language itself. We can even add cast operators (which is usually a bad idea, but sometimes, it's just the right solution).</p>\n<p><strong>We still missed one thing to have user-types behave as built-in types: user-defined literals.</strong></p>\n<p>So, I guess it's a natural evolution for the language, but to be as complete as possible: &quot;<em>If you want to create a type, and you want it to behave as much possible as a built-in types, here are the tools...</em>&quot;</p>\n<p>I'd guess it's very similar to .NET's decision to make every primitive a struct, including booleans, integers, etc., and have all structs derive from Object. This decision alone puts .NET far beyond Java's reach when working with primitives, no matter how much boxing/unboxing hacks Java will add to its specification.</p>\n<h2>Do YOU really need it in C++?</h2>\n<p>This question is for <strong>YOU</strong> to answer. Not Bjarne Stroustrup. Not Herb Sutter. Not whatever member of C++ standard committee. This is why <strong>you have the choice in C++</strong>, and they won't restrict a useful notation to built-in types alone.</p>\n<p>If <strong>you</strong> need it, then it is a welcome addition. If <strong>you</strong> don't, well... Don't use it. It will cost you nothing.</p>\n<p>Welcome to C++, the language where features are optional.</p>\n<h2>Bloated??? Show me your complexes!!!</h2>\n<p>There is a difference between bloated and complex (pun intended).</p>\n<p>Like shown by Niels at <a href=\"https://stackoverflow.com/questions/237804/user-defined-literals-in-c0x-a-much-needed-addition-or-making-c-even-more-bloat#237821\">What new capabilities do user-defined literals add to C++?</a>, being able to write a complex number is one of the two features added &quot;recently&quot; to C and C++:</p>\n<pre><code>// C89:\nMyComplex z1 = { 1, 2 } ;\n\n// C99: You'll note I is a macro, which can lead\n// to very interesting situations...\ndouble complex z1 = 1 + 2*I;\n\n// C++:\nstd::complex&lt;double&gt; z1(1, 2) ;\n\n// C++11: You'll note that &quot;i&quot; won't ever bother\n// you elsewhere\nstd::complex&lt;double&gt; z1 = 1 + 2_i ;\n</code></pre>\n<p>Now, both C99 &quot;double complex&quot; type and C++ &quot;std::complex&quot; type are able to be multiplied, added, subtracted, etc., using operator overloading.</p>\n<p>But in C99, they just added another type as a built-in type, and built-in operator overloading support. And they added another built-in literal feature.</p>\n<p>In C++, they just used existing features of the language, saw that the literal feature was a natural evolution of the language, and thus added it.</p>\n<p>In C, if you need the same notation enhancement for another type, you're out of luck until your lobbying to add your quantum wave functions (or 3D points, or whatever basic type you're using in your field of work) to the C standard as a built-in type succeeds.</p>\n<p>In C++11, you just can do it yourself:</p>\n<pre><code>Point p = 25_x + 13_y + 3_z ; // 3D point\n</code></pre>\n<p><strong>Is it bloated? No</strong>, the need is there, as shown by how both C and C++ complexes need a way to represent their literal complex values.</p>\n<p><strong>Is it wrongly designed? No</strong>, it's designed as every other C++ feature, with extensibility in mind.</p>\n<p><strong>Is it for notation purposes only? No</strong>, as it can even add type safety to your code.</p>\n<p>For example, let's imagine a CSS oriented code:</p>\n<pre><code>css::Font::Size p0 = 12_pt ; // Ok\ncss::Font::Size p1 = 50_percent ; // Ok\ncss::Font::Size p2 = 15_px ; // Ok\ncss::Font::Size p3 = 10_em ; // Ok\ncss::Font::Size p4 = 15 ; // ERROR : Won't compile !\n</code></pre>\n<p>It is then very easy to enforce a strong typing to the assignment of values.</p>\n<h2>Is is dangerous?</h2>\n<p>Good question. Can these functions be namespaced? If yes, then Jackpot!</p>\n<p>Anyway, <strong>like everything, you can kill yourself if a tool is used improperly</strong>. C is powerful, and you can shoot your head off if you misuse the C gun. C++ has the C gun, but also the scalpel, the taser, and whatever other tool you'll find in the toolkit. You can misuse the scalpel and bleed yourself to death. Or you can build very elegant and robust code.</p>\n<p>So, like every C++ feature, do you really need it? It is the question you must answer before using it in C++. If you don't, it will cost you nothing. But if you do really need it, at least, the language won't let you down.</p>\n<h2>The date example?</h2>\n<p>Your error, it seems to me, is that you are mixing operators:</p>\n<pre><code>1974/01/06AD\n ^ ^ ^\n</code></pre>\n<p>This can't be avoided, because / being an operator, the compiler must interpret it. And, AFAIK, it is a good thing.</p>\n<p>To find a solution for your problem, I would write the literal in some other way. For example:</p>\n<pre><code>&quot;1974-01-06&quot;_AD ; // ISO-like notation\n&quot;06/01/1974&quot;_AD ; // french-date-like notation\n&quot;jan 06 1974&quot;_AD ; // US-date-like notation\n19740106_AD ; // integer-date-like notation\n</code></pre>\n<p>Personally, I would choose the integer and the ISO dates, but it depends on YOUR needs. Which is the whole point of letting the user define its own literal names.</p>\n" }, { "answer_id": 238399, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": false, "text": "<p>UDLs are namespaced (and can be imported by using declarations/directives, but you cannot explicitly namespace a literal like <code>3.14std::i</code>), which means there (hopefully) won't be a ton of clashes.</p>\n\n<p>The fact that they can actually be templated (and constexpr'd) means that you can do some pretty powerful stuff with UDLs. Bigint authors will be really happy, as they can finally have arbitrarily large constants, calculated at compile time (via constexpr or templates).</p>\n\n<p>I'm just sad that we won't see a couple useful literals in the standard (from the looks of it), like <code>s</code> for <code>std::string</code> and <code>i</code> for the imaginary unit.</p>\n\n<p>The amount of coding time that will be saved by UDLs is actually not that high, but the readability will be vastly increased and more and more calculations can be shifted to compile-time for faster execution.</p>\n" }, { "answer_id": 238506, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 2, "selected": false, "text": "<p>C++ is usually very strict about the syntax used - barring the preprocessor there is not much you can use to define a custom syntax/grammar. E.g. we can overload existing operatos, but we cannot define new ones - IMO this is very much in tune with the spirit of C++. </p>\n\n<p>I don't mind some ways for more customized source code - but the point chosen seems very isolated to me, which confuses me most. </p>\n\n<p>Even intended use may make it much harder to read source code: an single letter may have vast-reaching side effects that in no way can be identified from the context. With symmetry to u, l and f, most developers will choose single letters.</p>\n\n<p>This may also turn scoping into a problem, using single letters in global namespace will probably be considered bad practice, and the tools that are supposed mixing libraries easier (namespaces and descriptive identifiers) will probably defeat its purpose.</p>\n\n<p>I see some merit in combination with \"auto\", also in combination with a unit library like <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/boost_units.html\" rel=\"nofollow noreferrer\">boost units</a>, but not enough to merit this adition. </p>\n\n<p>I wonder, however, what clever ideas we come up with.</p>\n" }, { "answer_id": 4051289, "author": "Diego Sevilla", "author_id": 62365, "author_profile": "https://Stackoverflow.com/users/62365", "pm_score": 4, "selected": false, "text": "<p>Let me add a little bit of context. For our work, user defined literals is much needed. We work on MDE (Model-Driven Engineering). We want to define models and metamodels in C++. We actually implemented a mapping from Ecore to C++ (<a href=\"http://WWW.Catedrasaes.org/trac/wiki/EMF4CPP\" rel=\"noreferrer\">EMF4CPP</a>).</p>\n\n<p>The problem comes when being able to define model elements as classes in C++. We are taking the approach of transforming the metamodel (Ecore) to templates with arguments. Arguments of the template are the structural characteristics of types and classes. For example, a class with two int attributes would be something like:</p>\n\n<pre><code>typedef ::ecore::Class&lt; Attribute&lt;int&gt;, Attribute&lt;int&gt; &gt; MyClass;\n</code></pre>\n\n<p>Hoever, it turns out that every element in a model or metamodel, usually has a name. We would like to write:</p>\n\n<pre><code>typedef ::ecore::Class&lt; \"MyClass\", Attribute&lt; \"x\", int&gt;, Attribute&lt;\"y\", int&gt; &gt; MyClass;\n</code></pre>\n\n<p>BUT, C++, nor C++0x don't allow this, as strings are prohibited as arguments to templates. You can write the name char by char, but this is admitedly a mess. With proper user-defined literals, we could write something similar. Say we use \"_n\" to identify model element names (I don't use the exact syntax, just to make an idea):</p>\n\n<pre><code>typedef ::ecore::Class&lt; MyClass_n, Attribute&lt; x_n, int&gt;, Attribute&lt;y_n, int&gt; &gt; MyClass;\n</code></pre>\n\n<p>Finally, having those definitions as templates helps us a lot to design algorithms for traversing the model elements, model transformations, etc. that are really efficient, because type information, identification, transformations, etc. are determined by the compiler at compile time.</p>\n" }, { "answer_id": 7906630, "author": "emsr", "author_id": 680359, "author_profile": "https://Stackoverflow.com/users/680359", "pm_score": 7, "selected": true, "text": "<p>Here's a case where there is an advantage to using user-defined literals instead of a constructor call:</p>\n\n<pre><code>#include &lt;bitset&gt;\n#include &lt;iostream&gt;\n\ntemplate&lt;char... Bits&gt;\n struct checkbits\n {\n static const bool valid = false;\n };\n\ntemplate&lt;char High, char... Bits&gt;\n struct checkbits&lt;High, Bits...&gt;\n {\n static const bool valid = (High == '0' || High == '1')\n &amp;&amp; checkbits&lt;Bits...&gt;::valid;\n };\n\ntemplate&lt;char High&gt;\n struct checkbits&lt;High&gt;\n {\n static const bool valid = (High == '0' || High == '1');\n };\n\ntemplate&lt;char... Bits&gt;\n inline constexpr std::bitset&lt;sizeof...(Bits)&gt;\n operator\"\" _bits() noexcept\n {\n static_assert(checkbits&lt;Bits...&gt;::valid, \"invalid digit in binary string\");\n return std::bitset&lt;sizeof...(Bits)&gt;((char []){Bits..., '\\0'});\n }\n\nint\nmain()\n{\n auto bits = 0101010101010101010101010101010101010101010101010101010101010101_bits;\n std::cout &lt;&lt; bits &lt;&lt; std::endl;\n std::cout &lt;&lt; \"size = \" &lt;&lt; bits.size() &lt;&lt; std::endl;\n std::cout &lt;&lt; \"count = \" &lt;&lt; bits.count() &lt;&lt; std::endl;\n std::cout &lt;&lt; \"value = \" &lt;&lt; bits.to_ullong() &lt;&lt; std::endl;\n\n // This triggers the static_assert at compile time.\n auto badbits = 2101010101010101010101010101010101010101010101010101010101010101_bits;\n\n // This throws at run time.\n std::bitset&lt;64&gt; badbits2(\"2101010101010101010101010101010101010101010101010101010101010101_bits\");\n}\n</code></pre>\n\n<p>The advantage is that a run-time exception is converted to a compile-time error.\nYou couldn't add the static assert to the bitset ctor taking a string (at least not without string template arguments).</p>\n" }, { "answer_id": 18689923, "author": "masonk", "author_id": 86432, "author_profile": "https://Stackoverflow.com/users/86432", "pm_score": 4, "selected": false, "text": "<p>Bjarne Stroustrup talks about UDL's in this <a href=\"http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style?format=smooth\">C++11 talk</a>, in the first section on type-rich interfaces, around 20 minute mark.</p>\n\n<p>His basic argument for UDLs takes the form of a syllogism: </p>\n\n<ol>\n<li><p>\"Trivial\" types, i.e., built-in primitive types, can only catch trivial type errors. Interfaces with richer types allow the type system to catch more kinds of errors.</p></li>\n<li><p>The kinds of type errors that richly typed code can catch have impact on real code. (He gives the example of the Mars Climate Orbiter, which infamously failed due to a dimensions error in an important constant).</p></li>\n<li><p>In real code, units are rarely used. People don't use them, because incurring runtime compute or memory overhead to create rich types is too costly, and using pre-existing C++ templated unit code is so notationally ugly that no one uses it. (Empirically, no one uses it, even though the libraries have been around for a decade).</p></li>\n<li><p>Therefore, in order to get engineers to use units in real code, we needed a device that (1) incurs no runtime overhead and (2) is notationally acceptable.</p></li>\n</ol>\n" }, { "answer_id": 32250622, "author": "rr-", "author_id": 2016221, "author_profile": "https://Stackoverflow.com/users/2016221", "pm_score": 2, "selected": false, "text": "<p>I used user literals for binary strings like this:</p>\n\n<pre><code> \"asd\\0\\0\\0\\1\"_b\n</code></pre>\n\n<p>using <code>std::string(str, n)</code> constructor so that <code>\\0</code> wouldn't cut the string in half. (The project does a lot of work with various file formats.)</p>\n\n<p>This was helpful also when I ditched <code>std::string</code> in favor of a wrapper for <code>std::vector</code>.</p>\n" }, { "answer_id": 38163546, "author": "Martin Moene", "author_id": 437272, "author_profile": "https://Stackoverflow.com/users/437272", "pm_score": 3, "selected": false, "text": "<p>Supporting compile-time dimension checking is the only justification required. </p>\n\n<pre><code>auto force = 2_N; \nauto dx = 2_m; \nauto energy = force * dx; \n\nassert(energy == 4_J); \n</code></pre>\n\n<p>See for example <a href=\"https://github.com/martinmoene/PhysUnits-CT-Cpp11\">PhysUnits-CT-Cpp11</a>, a small C++11, C++14 header-only library for compile-time dimensional analysis and unit/quantity manipulation and conversion. Simpler than <a href=\"http://www.boost.org/doc/libs/1_61_0/doc/html/boost_units.html\">Boost.Units</a>, does support <a href=\"https://en.wikipedia.org/wiki/International_System_of_Units#Units_and_prefixes\">unit symbol</a> literals such as m, g, s, <a href=\"http://en.wikipedia.org/wiki/Metric_prefix\">metric prefixes</a> such as m, k, M, only depends on standard C++ library, SI-only, integral powers of dimensions.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
[C++11](http://en.wikipedia.org/wiki/C%2B%2B11) introduces [user-defined literals](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2378.pdf) which will allow the introduction of new literal syntax based on existing literals (`int`, `hex`, `string`, `float`) so that any type will be able to have a literal presentation. **Examples:** ``` // imaginary numbers std::complex<long double> operator "" _i(long double d) // cooked form { return std::complex<long double>(0, d); } auto val = 3.14_i; // val = complex<long double>(0, 3.14) // binary values int operator "" _B(const char*); // raw form int answer = 101010_B; // answer = 42 // std::string std::string operator "" _s(const char* str, size_t /*length*/) { return std::string(str); } auto hi = "hello"_s + " world"; // + works, "hello"_s is a string not a pointer // units assert(1_kg == 2.2_lb); // give or take 0.00462262 pounds ``` At first glance this looks very cool but I'm wondering how applicable it really is, when I tried to think of having the suffixes `_AD` and `_BC` create dates I found that it's problematic due to operator order. `1974/01/06_AD` would first evaluate `1974/01` (as plain `int`s) and only later the `06_AD` (to say nothing of August and September having to be written without the `0` for octal reasons). This can be worked around by having the syntax be `1974-1/6_AD` so that the operator evaluation order works but it's clunky. So what my question boils down to is this, do you feel this feature will justify itself? What other literals would you like to define that will make your C++ code more readable? --- Updated syntax to fit the final draft on June 2011
Here's a case where there is an advantage to using user-defined literals instead of a constructor call: ``` #include <bitset> #include <iostream> template<char... Bits> struct checkbits { static const bool valid = false; }; template<char High, char... Bits> struct checkbits<High, Bits...> { static const bool valid = (High == '0' || High == '1') && checkbits<Bits...>::valid; }; template<char High> struct checkbits<High> { static const bool valid = (High == '0' || High == '1'); }; template<char... Bits> inline constexpr std::bitset<sizeof...(Bits)> operator"" _bits() noexcept { static_assert(checkbits<Bits...>::valid, "invalid digit in binary string"); return std::bitset<sizeof...(Bits)>((char []){Bits..., '\0'}); } int main() { auto bits = 0101010101010101010101010101010101010101010101010101010101010101_bits; std::cout << bits << std::endl; std::cout << "size = " << bits.size() << std::endl; std::cout << "count = " << bits.count() << std::endl; std::cout << "value = " << bits.to_ullong() << std::endl; // This triggers the static_assert at compile time. auto badbits = 2101010101010101010101010101010101010101010101010101010101010101_bits; // This throws at run time. std::bitset<64> badbits2("2101010101010101010101010101010101010101010101010101010101010101_bits"); } ``` The advantage is that a run-time exception is converted to a compile-time error. You couldn't add the static assert to the bitset ctor taking a string (at least not without string template arguments).
237,807
<p>.NET's <code>SslStream</code> class does not send the <code>close_notify</code> alert before closing the connection.</p> <p>How can I send the <code>close_notify</code> alert manually?</p>
[ { "answer_id": 238144, "author": "Shachar", "author_id": 13897, "author_profile": "https://Stackoverflow.com/users/13897", "pm_score": 2, "selected": false, "text": "<p>It's a bug in .NET's usage of the underlying security API. Note another question by me about being unable to select a specific cypher suite - they really botched up this API wrapper...</p>\n" }, { "answer_id": 737531, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>For the record, SslStream at least in .NET 2.0 also doesn't appear to response to a close_notify from the other side. This means that calling OpenSSL's SSL_Shutdown() properly, i.e. twice - once to initiate the shutdown and again to wait for the response - will hang on the second call.</p>\n" }, { "answer_id": 22626756, "author": "Neco", "author_id": 1655991, "author_profile": "https://Stackoverflow.com/users/1655991", "pm_score": 5, "selected": false, "text": "<p>Thanks for this question. It pointed me into the right direction, that there is a bug in .Net, which I do not very often think about.</p>\n\n<p>I bumped into this problem during writing of my implementation of FTPS server and Filezilla (or GnuTLS probably) client was complaining \"GnuTLS error -110 in gnutls_record_recv: The TLS connection was non-properly terminated\". I think it is a quite significant drawback in SslStream implementation.</p>\n\n<p>So I ended up with writing a wrapper which sends this alert before closing the stream:</p>\n\n<pre><code>public class FixedSslStream : SslStream {\n public FixedSslStream(Stream innerStream)\n : base(innerStream) {\n }\n public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen)\n : base(innerStream, leaveInnerStreamOpen) {\n }\n public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)\n : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback) {\n }\n public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback)\n : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback) {\n }\n public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy)\n : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, encryptionPolicy) {\n }\n public override void Close() {\n try {\n SslDirectCall.CloseNotify(this);\n } finally {\n base.Close();\n }\n }\n}\n</code></pre>\n\n<p>And the following code is to make it working (this code requires assembly to be 'unsafe'):</p>\n\n<pre><code>public unsafe static class SslDirectCall {\n public static void CloseNotify(SslStream sslStream) {\n if (sslStream.IsAuthenticated) {\n bool isServer = sslStream.IsServer;\n\n byte[] result;\n int resultSz;\n var asmbSystem = typeof(System.Net.Authorization).Assembly;\n\n int SCHANNEL_SHUTDOWN = 1;\n var workArray = BitConverter.GetBytes(SCHANNEL_SHUTDOWN);\n\n var sslstate = ReflectUtil.GetField(sslStream, \"_SslState\");\n var context = ReflectUtil.GetProperty(sslstate, \"Context\");\n\n var securityContext = ReflectUtil.GetField(context, \"m_SecurityContext\");\n var securityContextHandleOriginal = ReflectUtil.GetField(securityContext, \"_handle\");\n NativeApi.SSPIHandle securityContextHandle = default(NativeApi.SSPIHandle);\n securityContextHandle.HandleHi = (IntPtr)ReflectUtil.GetField(securityContextHandleOriginal, \"HandleHi\");\n securityContextHandle.HandleLo = (IntPtr)ReflectUtil.GetField(securityContextHandleOriginal, \"HandleLo\");\n\n var credentialsHandle = ReflectUtil.GetField(context, \"m_CredentialsHandle\");\n var credentialsHandleHandleOriginal = ReflectUtil.GetField(credentialsHandle, \"_handle\");\n NativeApi.SSPIHandle credentialsHandleHandle = default(NativeApi.SSPIHandle);\n credentialsHandleHandle.HandleHi = (IntPtr)ReflectUtil.GetField(credentialsHandleHandleOriginal, \"HandleHi\");\n credentialsHandleHandle.HandleLo = (IntPtr)ReflectUtil.GetField(credentialsHandleHandleOriginal, \"HandleLo\");\n\n int bufferSize = 1;\n NativeApi.SecurityBufferDescriptor securityBufferDescriptor = new NativeApi.SecurityBufferDescriptor(bufferSize);\n NativeApi.SecurityBufferStruct[] unmanagedBuffer = new NativeApi.SecurityBufferStruct[bufferSize];\n\n fixed (NativeApi.SecurityBufferStruct* ptr = unmanagedBuffer)\n fixed (void* workArrayPtr = workArray) {\n securityBufferDescriptor.UnmanagedPointer = (void*)ptr;\n\n unmanagedBuffer[0].token = (IntPtr)workArrayPtr;\n unmanagedBuffer[0].count = workArray.Length;\n unmanagedBuffer[0].type = NativeApi.BufferType.Token;\n\n NativeApi.SecurityStatus status;\n status = (NativeApi.SecurityStatus)NativeApi.ApplyControlToken(ref securityContextHandle, securityBufferDescriptor);\n if (status == NativeApi.SecurityStatus.OK) {\n unmanagedBuffer[0].token = IntPtr.Zero;\n unmanagedBuffer[0].count = 0;\n unmanagedBuffer[0].type = NativeApi.BufferType.Token;\n\n NativeApi.SSPIHandle contextHandleOut = default(NativeApi.SSPIHandle);\n NativeApi.ContextFlags outflags = NativeApi.ContextFlags.Zero;\n long ts = 0;\n\n var inflags = NativeApi.ContextFlags.SequenceDetect |\n NativeApi.ContextFlags.ReplayDetect |\n NativeApi.ContextFlags.Confidentiality |\n NativeApi.ContextFlags.AcceptExtendedError |\n NativeApi.ContextFlags.AllocateMemory |\n NativeApi.ContextFlags.InitStream;\n\n if (isServer) {\n status = (NativeApi.SecurityStatus)NativeApi.AcceptSecurityContext(ref credentialsHandleHandle, ref securityContextHandle, null,\n inflags, NativeApi.Endianness.Native, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts);\n } else {\n status = (NativeApi.SecurityStatus)NativeApi.InitializeSecurityContextW(ref credentialsHandleHandle, ref securityContextHandle, null,\n inflags, 0, NativeApi.Endianness.Native, null, 0, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts);\n }\n if (status == NativeApi.SecurityStatus.OK) {\n byte[] resultArr = new byte[unmanagedBuffer[0].count];\n Marshal.Copy(unmanagedBuffer[0].token, resultArr, 0, resultArr.Length);\n Marshal.FreeCoTaskMem(unmanagedBuffer[0].token);\n result = resultArr;\n resultSz = resultArr.Length;\n } else {\n throw new InvalidOperationException(string.Format(\"AcceptSecurityContext/InitializeSecurityContextW returned [{0}] during CloseNotify.\", status));\n }\n } else {\n throw new InvalidOperationException(string.Format(\"ApplyControlToken returned [{0}] during CloseNotify.\", status));\n }\n }\n\n var innerStream = (Stream)ReflectUtil.GetProperty(sslstate, \"InnerStream\");\n innerStream.Write(result, 0, resultSz);\n }\n }\n}\n</code></pre>\n\n<p>Windows API used:</p>\n\n<pre><code>public unsafe static class NativeApi {\n internal enum BufferType {\n Empty,\n Data,\n Token,\n Parameters,\n Missing,\n Extra,\n Trailer,\n Header,\n Padding = 9,\n Stream,\n ChannelBindings = 14,\n TargetHost = 16,\n ReadOnlyFlag = -2147483648,\n ReadOnlyWithChecksum = 268435456\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n internal struct SSPIHandle {\n public IntPtr HandleHi;\n public IntPtr HandleLo;\n public bool IsZero {\n get {\n return this.HandleHi == IntPtr.Zero &amp;&amp; this.HandleLo == IntPtr.Zero;\n }\n }\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]\n internal void SetToInvalid() {\n this.HandleHi = IntPtr.Zero;\n this.HandleLo = IntPtr.Zero;\n }\n public override string ToString() {\n return this.HandleHi.ToString(\"x\") + \":\" + this.HandleLo.ToString(\"x\");\n }\n }\n [StructLayout(LayoutKind.Sequential)]\n internal class SecurityBufferDescriptor {\n public readonly int Version;\n public readonly int Count;\n public unsafe void* UnmanagedPointer;\n public SecurityBufferDescriptor(int count) {\n this.Version = 0;\n this.Count = count;\n this.UnmanagedPointer = null;\n }\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct SecurityBufferStruct {\n public int count;\n public BufferType type;\n public IntPtr token;\n public static readonly int Size = sizeof(SecurityBufferStruct);\n }\n\n internal enum SecurityStatus {\n OK,\n ContinueNeeded = 590610,\n CompleteNeeded,\n CompAndContinue,\n ContextExpired = 590615,\n CredentialsNeeded = 590624,\n Renegotiate,\n OutOfMemory = -2146893056,\n InvalidHandle,\n Unsupported,\n TargetUnknown,\n InternalError,\n PackageNotFound,\n NotOwner,\n CannotInstall,\n InvalidToken,\n CannotPack,\n QopNotSupported,\n NoImpersonation,\n LogonDenied,\n UnknownCredentials,\n NoCredentials,\n MessageAltered,\n OutOfSequence,\n NoAuthenticatingAuthority,\n IncompleteMessage = -2146893032,\n IncompleteCredentials = -2146893024,\n BufferNotEnough,\n WrongPrincipal,\n TimeSkew = -2146893020,\n UntrustedRoot,\n IllegalMessage,\n CertUnknown,\n CertExpired,\n AlgorithmMismatch = -2146893007,\n SecurityQosFailed,\n SmartcardLogonRequired = -2146892994,\n UnsupportedPreauth = -2146892989,\n BadBinding = -2146892986\n }\n [Flags]\n internal enum ContextFlags {\n Zero = 0,\n Delegate = 1,\n MutualAuth = 2,\n ReplayDetect = 4,\n SequenceDetect = 8,\n Confidentiality = 16,\n UseSessionKey = 32,\n AllocateMemory = 256,\n Connection = 2048,\n InitExtendedError = 16384,\n AcceptExtendedError = 32768,\n InitStream = 32768,\n AcceptStream = 65536,\n InitIntegrity = 65536,\n AcceptIntegrity = 131072,\n InitManualCredValidation = 524288,\n InitUseSuppliedCreds = 128,\n InitIdentify = 131072,\n AcceptIdentify = 524288,\n ProxyBindings = 67108864,\n AllowMissingBindings = 268435456,\n UnverifiedTargetName = 536870912\n }\n internal enum Endianness {\n Network,\n Native = 16\n }\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]\n [DllImport(\"secur32.dll\", ExactSpelling = true, SetLastError = true)]\n internal static extern int ApplyControlToken(ref SSPIHandle contextHandle, [In] [Out] SecurityBufferDescriptor outputBuffer);\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]\n [DllImport(\"secur32.dll\", ExactSpelling = true, SetLastError = true)]\n internal unsafe static extern int AcceptSecurityContext(ref SSPIHandle credentialHandle, ref SSPIHandle contextHandle, [In] SecurityBufferDescriptor inputBuffer, [In] ContextFlags inFlags, [In] Endianness endianness, ref SSPIHandle outContextPtr, [In] [Out] SecurityBufferDescriptor outputBuffer, [In] [Out] ref ContextFlags attributes, out long timeStamp);\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]\n [DllImport(\"secur32.dll\", ExactSpelling = true, SetLastError = true)]\n internal unsafe static extern int InitializeSecurityContextW(ref SSPIHandle credentialHandle, ref SSPIHandle contextHandle, [In] byte* targetName, [In] ContextFlags inFlags, [In] int reservedI, [In] Endianness endianness, [In] SecurityBufferDescriptor inputBuffer, [In] int reservedII, ref SSPIHandle outContextPtr, [In] [Out] SecurityBufferDescriptor outputBuffer, [In] [Out] ref ContextFlags attributes, out long timeStamp);\n}\n</code></pre>\n\n<p>Reflection utilities:</p>\n\n<pre><code>public static class ReflectUtil {\n public static object GetField(object obj, string fieldName) {\n var tp = obj.GetType();\n var info = GetAllFields(tp)\n .Where(f =&gt; f.Name == fieldName).Single();\n return info.GetValue(obj);\n }\n public static void SetField(object obj, string fieldName, object value) {\n var tp = obj.GetType();\n var info = GetAllFields(tp)\n .Where(f =&gt; f.Name == fieldName).Single();\n info.SetValue(obj, value);\n }\n public static object GetStaticField(Assembly assembly, string typeName, string fieldName) {\n var tp = assembly.GetType(typeName);\n var info = GetAllFields(tp)\n .Where(f =&gt; f.IsStatic)\n .Where(f =&gt; f.Name == fieldName).Single();\n return info.GetValue(null);\n }\n\n public static object GetProperty(object obj, string propertyName) {\n var tp = obj.GetType();\n var info = GetAllProperties(tp)\n .Where(f =&gt; f.Name == propertyName).Single();\n return info.GetValue(obj, null);\n }\n public static object CallMethod(object obj, string methodName, params object[] prm) {\n var tp = obj.GetType();\n var info = GetAllMethods(tp)\n .Where(f =&gt; f.Name == methodName &amp;&amp; f.GetParameters().Length == prm.Length).Single();\n object rez = info.Invoke(obj, prm);\n return rez;\n }\n public static object NewInstance(Assembly assembly, string typeName, params object[] prm) {\n var tp = assembly.GetType(typeName);\n var info = tp.GetConstructors()\n .Where(f =&gt; f.GetParameters().Length == prm.Length).Single();\n object rez = info.Invoke(prm);\n return rez;\n }\n public static object InvokeStaticMethod(Assembly assembly, string typeName, string methodName, params object[] prm) {\n var tp = assembly.GetType(typeName);\n var info = GetAllMethods(tp)\n .Where(f =&gt; f.IsStatic)\n .Where(f =&gt; f.Name == methodName &amp;&amp; f.GetParameters().Length == prm.Length).Single();\n object rez = info.Invoke(null, prm);\n return rez;\n }\n public static object GetEnumValue(Assembly assembly, string typeName, int value) {\n var tp = assembly.GetType(typeName);\n object rez = Enum.ToObject(tp, value);\n return rez;\n }\n\n private static IEnumerable&lt;FieldInfo&gt; GetAllFields(Type t) {\n if (t == null)\n return Enumerable.Empty&lt;FieldInfo&gt;();\n\n BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |\n BindingFlags.Static | BindingFlags.Instance |\n BindingFlags.DeclaredOnly;\n return t.GetFields(flags).Concat(GetAllFields(t.BaseType));\n }\n private static IEnumerable&lt;PropertyInfo&gt; GetAllProperties(Type t) {\n if (t == null)\n return Enumerable.Empty&lt;PropertyInfo&gt;();\n\n BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |\n BindingFlags.Static | BindingFlags.Instance |\n BindingFlags.DeclaredOnly;\n return t.GetProperties(flags).Concat(GetAllProperties(t.BaseType));\n }\n private static IEnumerable&lt;MethodInfo&gt; GetAllMethods(Type t) {\n if (t == null)\n return Enumerable.Empty&lt;MethodInfo&gt;();\n\n BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |\n BindingFlags.Static | BindingFlags.Instance |\n BindingFlags.DeclaredOnly;\n return t.GetMethods(flags).Concat(GetAllMethods(t.BaseType));\n }\n}\n</code></pre>\n\n<p>I am not experienced in writing reliable interaction with unmanaged environment, so I hope somebody can have a look and fix issues (and maybe make it 'safe').</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
.NET's `SslStream` class does not send the `close_notify` alert before closing the connection. How can I send the `close_notify` alert manually?
Thanks for this question. It pointed me into the right direction, that there is a bug in .Net, which I do not very often think about. I bumped into this problem during writing of my implementation of FTPS server and Filezilla (or GnuTLS probably) client was complaining "GnuTLS error -110 in gnutls\_record\_recv: The TLS connection was non-properly terminated". I think it is a quite significant drawback in SslStream implementation. So I ended up with writing a wrapper which sends this alert before closing the stream: ``` public class FixedSslStream : SslStream { public FixedSslStream(Stream innerStream) : base(innerStream) { } public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen) { } public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback) { } public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback) { } public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, encryptionPolicy) { } public override void Close() { try { SslDirectCall.CloseNotify(this); } finally { base.Close(); } } } ``` And the following code is to make it working (this code requires assembly to be 'unsafe'): ``` public unsafe static class SslDirectCall { public static void CloseNotify(SslStream sslStream) { if (sslStream.IsAuthenticated) { bool isServer = sslStream.IsServer; byte[] result; int resultSz; var asmbSystem = typeof(System.Net.Authorization).Assembly; int SCHANNEL_SHUTDOWN = 1; var workArray = BitConverter.GetBytes(SCHANNEL_SHUTDOWN); var sslstate = ReflectUtil.GetField(sslStream, "_SslState"); var context = ReflectUtil.GetProperty(sslstate, "Context"); var securityContext = ReflectUtil.GetField(context, "m_SecurityContext"); var securityContextHandleOriginal = ReflectUtil.GetField(securityContext, "_handle"); NativeApi.SSPIHandle securityContextHandle = default(NativeApi.SSPIHandle); securityContextHandle.HandleHi = (IntPtr)ReflectUtil.GetField(securityContextHandleOriginal, "HandleHi"); securityContextHandle.HandleLo = (IntPtr)ReflectUtil.GetField(securityContextHandleOriginal, "HandleLo"); var credentialsHandle = ReflectUtil.GetField(context, "m_CredentialsHandle"); var credentialsHandleHandleOriginal = ReflectUtil.GetField(credentialsHandle, "_handle"); NativeApi.SSPIHandle credentialsHandleHandle = default(NativeApi.SSPIHandle); credentialsHandleHandle.HandleHi = (IntPtr)ReflectUtil.GetField(credentialsHandleHandleOriginal, "HandleHi"); credentialsHandleHandle.HandleLo = (IntPtr)ReflectUtil.GetField(credentialsHandleHandleOriginal, "HandleLo"); int bufferSize = 1; NativeApi.SecurityBufferDescriptor securityBufferDescriptor = new NativeApi.SecurityBufferDescriptor(bufferSize); NativeApi.SecurityBufferStruct[] unmanagedBuffer = new NativeApi.SecurityBufferStruct[bufferSize]; fixed (NativeApi.SecurityBufferStruct* ptr = unmanagedBuffer) fixed (void* workArrayPtr = workArray) { securityBufferDescriptor.UnmanagedPointer = (void*)ptr; unmanagedBuffer[0].token = (IntPtr)workArrayPtr; unmanagedBuffer[0].count = workArray.Length; unmanagedBuffer[0].type = NativeApi.BufferType.Token; NativeApi.SecurityStatus status; status = (NativeApi.SecurityStatus)NativeApi.ApplyControlToken(ref securityContextHandle, securityBufferDescriptor); if (status == NativeApi.SecurityStatus.OK) { unmanagedBuffer[0].token = IntPtr.Zero; unmanagedBuffer[0].count = 0; unmanagedBuffer[0].type = NativeApi.BufferType.Token; NativeApi.SSPIHandle contextHandleOut = default(NativeApi.SSPIHandle); NativeApi.ContextFlags outflags = NativeApi.ContextFlags.Zero; long ts = 0; var inflags = NativeApi.ContextFlags.SequenceDetect | NativeApi.ContextFlags.ReplayDetect | NativeApi.ContextFlags.Confidentiality | NativeApi.ContextFlags.AcceptExtendedError | NativeApi.ContextFlags.AllocateMemory | NativeApi.ContextFlags.InitStream; if (isServer) { status = (NativeApi.SecurityStatus)NativeApi.AcceptSecurityContext(ref credentialsHandleHandle, ref securityContextHandle, null, inflags, NativeApi.Endianness.Native, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts); } else { status = (NativeApi.SecurityStatus)NativeApi.InitializeSecurityContextW(ref credentialsHandleHandle, ref securityContextHandle, null, inflags, 0, NativeApi.Endianness.Native, null, 0, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts); } if (status == NativeApi.SecurityStatus.OK) { byte[] resultArr = new byte[unmanagedBuffer[0].count]; Marshal.Copy(unmanagedBuffer[0].token, resultArr, 0, resultArr.Length); Marshal.FreeCoTaskMem(unmanagedBuffer[0].token); result = resultArr; resultSz = resultArr.Length; } else { throw new InvalidOperationException(string.Format("AcceptSecurityContext/InitializeSecurityContextW returned [{0}] during CloseNotify.", status)); } } else { throw new InvalidOperationException(string.Format("ApplyControlToken returned [{0}] during CloseNotify.", status)); } } var innerStream = (Stream)ReflectUtil.GetProperty(sslstate, "InnerStream"); innerStream.Write(result, 0, resultSz); } } } ``` Windows API used: ``` public unsafe static class NativeApi { internal enum BufferType { Empty, Data, Token, Parameters, Missing, Extra, Trailer, Header, Padding = 9, Stream, ChannelBindings = 14, TargetHost = 16, ReadOnlyFlag = -2147483648, ReadOnlyWithChecksum = 268435456 } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct SSPIHandle { public IntPtr HandleHi; public IntPtr HandleLo; public bool IsZero { get { return this.HandleHi == IntPtr.Zero && this.HandleLo == IntPtr.Zero; } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal void SetToInvalid() { this.HandleHi = IntPtr.Zero; this.HandleLo = IntPtr.Zero; } public override string ToString() { return this.HandleHi.ToString("x") + ":" + this.HandleLo.ToString("x"); } } [StructLayout(LayoutKind.Sequential)] internal class SecurityBufferDescriptor { public readonly int Version; public readonly int Count; public unsafe void* UnmanagedPointer; public SecurityBufferDescriptor(int count) { this.Version = 0; this.Count = count; this.UnmanagedPointer = null; } } [StructLayout(LayoutKind.Sequential)] internal struct SecurityBufferStruct { public int count; public BufferType type; public IntPtr token; public static readonly int Size = sizeof(SecurityBufferStruct); } internal enum SecurityStatus { OK, ContinueNeeded = 590610, CompleteNeeded, CompAndContinue, ContextExpired = 590615, CredentialsNeeded = 590624, Renegotiate, OutOfMemory = -2146893056, InvalidHandle, Unsupported, TargetUnknown, InternalError, PackageNotFound, NotOwner, CannotInstall, InvalidToken, CannotPack, QopNotSupported, NoImpersonation, LogonDenied, UnknownCredentials, NoCredentials, MessageAltered, OutOfSequence, NoAuthenticatingAuthority, IncompleteMessage = -2146893032, IncompleteCredentials = -2146893024, BufferNotEnough, WrongPrincipal, TimeSkew = -2146893020, UntrustedRoot, IllegalMessage, CertUnknown, CertExpired, AlgorithmMismatch = -2146893007, SecurityQosFailed, SmartcardLogonRequired = -2146892994, UnsupportedPreauth = -2146892989, BadBinding = -2146892986 } [Flags] internal enum ContextFlags { Zero = 0, Delegate = 1, MutualAuth = 2, ReplayDetect = 4, SequenceDetect = 8, Confidentiality = 16, UseSessionKey = 32, AllocateMemory = 256, Connection = 2048, InitExtendedError = 16384, AcceptExtendedError = 32768, InitStream = 32768, AcceptStream = 65536, InitIntegrity = 65536, AcceptIntegrity = 131072, InitManualCredValidation = 524288, InitUseSuppliedCreds = 128, InitIdentify = 131072, AcceptIdentify = 524288, ProxyBindings = 67108864, AllowMissingBindings = 268435456, UnverifiedTargetName = 536870912 } internal enum Endianness { Network, Native = 16 } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport("secur32.dll", ExactSpelling = true, SetLastError = true)] internal static extern int ApplyControlToken(ref SSPIHandle contextHandle, [In] [Out] SecurityBufferDescriptor outputBuffer); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport("secur32.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int AcceptSecurityContext(ref SSPIHandle credentialHandle, ref SSPIHandle contextHandle, [In] SecurityBufferDescriptor inputBuffer, [In] ContextFlags inFlags, [In] Endianness endianness, ref SSPIHandle outContextPtr, [In] [Out] SecurityBufferDescriptor outputBuffer, [In] [Out] ref ContextFlags attributes, out long timeStamp); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport("secur32.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int InitializeSecurityContextW(ref SSPIHandle credentialHandle, ref SSPIHandle contextHandle, [In] byte* targetName, [In] ContextFlags inFlags, [In] int reservedI, [In] Endianness endianness, [In] SecurityBufferDescriptor inputBuffer, [In] int reservedII, ref SSPIHandle outContextPtr, [In] [Out] SecurityBufferDescriptor outputBuffer, [In] [Out] ref ContextFlags attributes, out long timeStamp); } ``` Reflection utilities: ``` public static class ReflectUtil { public static object GetField(object obj, string fieldName) { var tp = obj.GetType(); var info = GetAllFields(tp) .Where(f => f.Name == fieldName).Single(); return info.GetValue(obj); } public static void SetField(object obj, string fieldName, object value) { var tp = obj.GetType(); var info = GetAllFields(tp) .Where(f => f.Name == fieldName).Single(); info.SetValue(obj, value); } public static object GetStaticField(Assembly assembly, string typeName, string fieldName) { var tp = assembly.GetType(typeName); var info = GetAllFields(tp) .Where(f => f.IsStatic) .Where(f => f.Name == fieldName).Single(); return info.GetValue(null); } public static object GetProperty(object obj, string propertyName) { var tp = obj.GetType(); var info = GetAllProperties(tp) .Where(f => f.Name == propertyName).Single(); return info.GetValue(obj, null); } public static object CallMethod(object obj, string methodName, params object[] prm) { var tp = obj.GetType(); var info = GetAllMethods(tp) .Where(f => f.Name == methodName && f.GetParameters().Length == prm.Length).Single(); object rez = info.Invoke(obj, prm); return rez; } public static object NewInstance(Assembly assembly, string typeName, params object[] prm) { var tp = assembly.GetType(typeName); var info = tp.GetConstructors() .Where(f => f.GetParameters().Length == prm.Length).Single(); object rez = info.Invoke(prm); return rez; } public static object InvokeStaticMethod(Assembly assembly, string typeName, string methodName, params object[] prm) { var tp = assembly.GetType(typeName); var info = GetAllMethods(tp) .Where(f => f.IsStatic) .Where(f => f.Name == methodName && f.GetParameters().Length == prm.Length).Single(); object rez = info.Invoke(null, prm); return rez; } public static object GetEnumValue(Assembly assembly, string typeName, int value) { var tp = assembly.GetType(typeName); object rez = Enum.ToObject(tp, value); return rez; } private static IEnumerable<FieldInfo> GetAllFields(Type t) { if (t == null) return Enumerable.Empty<FieldInfo>(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; return t.GetFields(flags).Concat(GetAllFields(t.BaseType)); } private static IEnumerable<PropertyInfo> GetAllProperties(Type t) { if (t == null) return Enumerable.Empty<PropertyInfo>(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; return t.GetProperties(flags).Concat(GetAllProperties(t.BaseType)); } private static IEnumerable<MethodInfo> GetAllMethods(Type t) { if (t == null) return Enumerable.Empty<MethodInfo>(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; return t.GetMethods(flags).Concat(GetAllMethods(t.BaseType)); } } ``` I am not experienced in writing reliable interaction with unmanaged environment, so I hope somebody can have a look and fix issues (and maybe make it 'safe').
237,816
<p>Say each row in a table has data pertaining to one particular user. The user has a password to access the system.</p> <p>How do I encrypt a column of data using InnoDB so that no one other than the user who's data it is can read the data ? I was thinking of something like using one of the MySQL encryption functions (say AES) with a key based on a hash calculated from the user's password.</p> <p>Does any one have any pointers to how I could do this ? Am I on the right track ?</p> <p>One of the answers below</p> <blockquote> <p>The issue of modifying user's password involves re-encrypting the user key by means of the new password which is much more straight forward than re-encrypting the whole bunch of user's data that can be arbitrarily large. The user key remains the same accross the life of the user data in the system.</p> </blockquote> <p>How does this help ? Say the password is pass1. And there are a bunch of records encrypted with a key generated from this. If the user now resets the password to pass2, I have no way of decrypting the data that was encrypted using pass1. In the case of a user forgetting the password entirely, all his encrypted data will be lost.</p>
[ { "answer_id": 237839, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 3, "selected": false, "text": "<p>I don't know if there is much sense in encrypting data with user's password hash, <em>especially</em> if you keep hash itself in the database. In that case anyone who can access the encrypted data can also access the password hash and decrypt the data.</p>\n\n<p>Another approach would be to encrypt the data with the application-specific key salted with some user-specific data. However, then you face another problem: how to securely store the application key. To that question I do not know an easy answer, but keeping it in your source code is probably good enough if you fear that your database data can be compromised, but not the source code itself, e.g. if your database is stored off-site (think Amazon S3).</p>\n\n<p>Salting the app key with the user's password helps if you keep only password's hash in the database, but can introduce another security flaw: you have to keep user's password in clear text in the applications session.</p>\n\n<p>As for technical solution, it is quite simple and <a href=\"http://dev.mysql.com/doc/refman/5.0/en/encryption-functions.html#function_aes-encrypt\" rel=\"noreferrer\">sample code is available</a>. You could modify it as follows to encrypt the data with the application password salted with password hash:</p>\n\n<pre><code>INSERT INTO secure_table VALUES (\n 1,\n AES_ENCRYPT(\n 'plain text data',\n CONCAT(@application_password, @user_password))\n);\n</code></pre>\n\n<p>In any case you would have to store your application password somewhere so I don't think that there is an easy approach that provides perfect security.</p>\n\n<p>Another approach I can think of is to ask user for a short PIN which you could use as an encryption key. The PIN would not be stored in the database, <em>but</em> you would need to ask user for it every time you access their data.</p>\n\n<p>And of course your have to think of is the feasibility of the encryption. You won't be able to index or to search it without decryption. It is probably required for a limited set of data (e.g. credit card number), but I wouldn't go to far with it.</p>\n" }, { "answer_id": 237857, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 0, "selected": false, "text": "<p>I don't think that's the best approach, unless you're enforcing that users can never change their password, or you have a way to re-encrypt everything each time a user changes his/her password.</p>\n" }, { "answer_id": 237880, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 0, "selected": false, "text": "<p>You could store another key to encrypt/decrypt user specific data which could be generated when a new user is created. Let's call this new key user key. This user key should also be encrypted in database and the most direct approach would be to encrypt it by means of the user's password or any other data which cointained the password (such as the password and creation/modification time, etc.).</p>\n\n<p>I would keep in user's session the decrypted user key to access user's data at any desired time within session.</p>\n\n<p>The issue of modifying user's password involves re-encrypting the user key by means of the new password which is much more straight forward than re-encrypting the whole bunch of user's data that can be arbitrarily large. The user key remains the same accross the life of the user data in the system.</p>\n\n<p>Of course this method can only be used if authentication is carried out by sending the actual user password to the server at logon, since database only desirably contains the hash of the password.</p>\n" }, { "answer_id": 238836, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Say the password is pass1. And there are a bunch of records encrypted with a key generated from this. If the user now resets the password to pass2, I have no way of decrypting the data that was encrypted using pass1</p>\n</blockquote>\n\n<p>The key would need to be encrypted in a reversable manner, so that it could be decrypted\nusing pass1 and re-encrypted using pass2.</p>\n\n<p>To summarize:</p>\n\n<p>Stored in the database is: the one-way encrypted password (for password checking), \nthe encryption key for other data, reversibly encrypted using the clear password (or at any rate, the password encrypted in some different manner than the way it is stored in the database), and the other data, reversibly encrypted using the clear encryption key.</p>\n\n<p>Whenever you need the other data, you must have the clear (or differently encrypted than as stored in the database) password, read the encryption key, decrypt it with the password, and use that to decrypt the other data.</p>\n\n<p>When a password is changed, the encryption key is decrypted using the old password, encrypted using the new password, and stored.</p>\n" }, { "answer_id": 240976, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 2, "selected": false, "text": "<p>To clarify one of the answers mentioned in the question: \"user/app key\" is a randomly generated private key, which is used to encrypt the data. The private key never changes (unless it's compromised). You encrypt and store the private key with a password. Since the private key is much smaller than the data, it's much cheaper to change the password: you simply decrypt the private key with the old password and re-encrypt it with the new password.</p>\n" }, { "answer_id": 796570, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you need to access the data without user interaction (for database migration for example), you won't have the key to decrypt.</p>\n" }, { "answer_id": 17015513, "author": "sagunms", "author_id": 1297184, "author_profile": "https://Stackoverflow.com/users/1297184", "pm_score": 1, "selected": false, "text": "<p>For data that is not user-specific (global), you could maybe use a combination of symmetric and asymmetric cipher. You could have an <code>extra password</code> field that all users are required to enter so that even if one user changes one's password, the global data will still be usable to other users with different passwords.</p>\n\n<p>The <code>extra password</code> can be bitwise xor'ed with another <code>salt-like string</code> inside the source code. Together, it can form the symmetric passkey to decrypt a <code>private key</code> stored in the database (which will never change). After <code>private key</code> is decrypted using the <code>extra password</code>, the private key can decrypt and <code>read</code> all the data in the db. Private key can be stored as session variable.</p>\n\n<p>The <code>public key</code>, as the name suggests, can reside as plain text string in the db. When you need to <code>write</code> to db, use public key to encrypt the data.</p>\n\n<p>You can routinely provide the users with a new <code>extra password</code> and re-encrypt the static <code>private key</code>, followed by an xor'ing with <code>salt-like string</code>.</p>\n\n<p>If the data is user-specific data and not meant for other users, you could use the user's password without the extra-password field to encrypt the private key. The administrator could have another copy of the private keys for specific users, which can be decrypted using his password.</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31574/" ]
Say each row in a table has data pertaining to one particular user. The user has a password to access the system. How do I encrypt a column of data using InnoDB so that no one other than the user who's data it is can read the data ? I was thinking of something like using one of the MySQL encryption functions (say AES) with a key based on a hash calculated from the user's password. Does any one have any pointers to how I could do this ? Am I on the right track ? One of the answers below > > The issue of modifying user's password involves re-encrypting the user key by means of the new password which is much more straight forward than re-encrypting the whole bunch of user's data that can be arbitrarily large. The user key remains the same accross the life of the user data in the system. > > > How does this help ? Say the password is pass1. And there are a bunch of records encrypted with a key generated from this. If the user now resets the password to pass2, I have no way of decrypting the data that was encrypted using pass1. In the case of a user forgetting the password entirely, all his encrypted data will be lost.
I don't know if there is much sense in encrypting data with user's password hash, *especially* if you keep hash itself in the database. In that case anyone who can access the encrypted data can also access the password hash and decrypt the data. Another approach would be to encrypt the data with the application-specific key salted with some user-specific data. However, then you face another problem: how to securely store the application key. To that question I do not know an easy answer, but keeping it in your source code is probably good enough if you fear that your database data can be compromised, but not the source code itself, e.g. if your database is stored off-site (think Amazon S3). Salting the app key with the user's password helps if you keep only password's hash in the database, but can introduce another security flaw: you have to keep user's password in clear text in the applications session. As for technical solution, it is quite simple and [sample code is available](http://dev.mysql.com/doc/refman/5.0/en/encryption-functions.html#function_aes-encrypt). You could modify it as follows to encrypt the data with the application password salted with password hash: ``` INSERT INTO secure_table VALUES ( 1, AES_ENCRYPT( 'plain text data', CONCAT(@application_password, @user_password)) ); ``` In any case you would have to store your application password somewhere so I don't think that there is an easy approach that provides perfect security. Another approach I can think of is to ask user for a short PIN which you could use as an encryption key. The PIN would not be stored in the database, *but* you would need to ask user for it every time you access their data. And of course your have to think of is the feasibility of the encryption. You won't be able to index or to search it without decryption. It is probably required for a limited set of data (e.g. credit card number), but I wouldn't go to far with it.
237,832
<p>I'm seeing a very strange issue with a .NET webservice being consumed by Flex.</p> <p>I have a very simple class with nothing other than properties with [XmlAttribute('xxx')] attributes.</p> <pre><code>public class OrderAddress { public OrderAddress() {} [XmlAttribute("firstName")] public string FirstName { get; set; } [XmlAttribute("lastName")] public string LastName { get; set; } [XmlAttribute("company")] public string Company { get; set; } [XmlAttribute("address1")] public string Address1 { get; set; } ... (more properties) } </code></pre> <p>The problem is that in Flex when this object is deserialized EVERY SINGLE fields is null in the debugger. The instance of the OrderAddress class is not null, just all the fields. I an 100% sure my web service proxy layer is up to date and there is 100% definitely data going across the wire as shown by <a href="http://fiddlertool.com" rel="nofollow noreferrer">Fiddler</a>. </p> <p>The very very wierd thing is that if I change one of these properties to serialize as an element (as opposed to XmlAttribute) and recompile ONLY my C# webservice then the data instantly can be recognized by Flex. If I add a completely unused field - like <code>public string Foo = "foo";</code> then that also suddenly works.</p> <p>I kind of remember seeing something like this before but don't remeber if I successfully fixed it or not.</p> <p>Its 3:30am for me and I need to postpone my hardcore troubleshooting, but throwing this out here in case its obvious to anyone reading. The code is in a module, which I know can sometimes cause some wierdness - but this seems to be very wierd.</p>
[ { "answer_id": 237868, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 0, "selected": false, "text": "<p>Elements centric XML is more interoperable format in XML serialization. \nThis is the reason that the new WCF DataContract serializer serializes every property as elements instead of attribute. Attribute to me is descriptor to the element rather than data for the element.</p>\n" }, { "answer_id": 2600681, "author": "NewFlexer", "author_id": 311989, "author_profile": "https://Stackoverflow.com/users/311989", "pm_score": 2, "selected": true, "text": "<p>After three days' struggling, finally I figured out this XML attribute was the cause of my problem. Slightly different from yours, my class has an array of objects in addition to the XML attribute. Flex was able to generate proxies, and even got attribute correctly (it was treated as a property), but it failed to deserialize the XML elements (returned from web serive) to array of objects. Once I delete that attribute, everything worked fine...so yes, this is \"element centric XML serialization\". But, is there any way to work around it?</p>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
I'm seeing a very strange issue with a .NET webservice being consumed by Flex. I have a very simple class with nothing other than properties with [XmlAttribute('xxx')] attributes. ``` public class OrderAddress { public OrderAddress() {} [XmlAttribute("firstName")] public string FirstName { get; set; } [XmlAttribute("lastName")] public string LastName { get; set; } [XmlAttribute("company")] public string Company { get; set; } [XmlAttribute("address1")] public string Address1 { get; set; } ... (more properties) } ``` The problem is that in Flex when this object is deserialized EVERY SINGLE fields is null in the debugger. The instance of the OrderAddress class is not null, just all the fields. I an 100% sure my web service proxy layer is up to date and there is 100% definitely data going across the wire as shown by [Fiddler](http://fiddlertool.com). The very very wierd thing is that if I change one of these properties to serialize as an element (as opposed to XmlAttribute) and recompile ONLY my C# webservice then the data instantly can be recognized by Flex. If I add a completely unused field - like `public string Foo = "foo";` then that also suddenly works. I kind of remember seeing something like this before but don't remeber if I successfully fixed it or not. Its 3:30am for me and I need to postpone my hardcore troubleshooting, but throwing this out here in case its obvious to anyone reading. The code is in a module, which I know can sometimes cause some wierdness - but this seems to be very wierd.
After three days' struggling, finally I figured out this XML attribute was the cause of my problem. Slightly different from yours, my class has an array of objects in addition to the XML attribute. Flex was able to generate proxies, and even got attribute correctly (it was treated as a property), but it failed to deserialize the XML elements (returned from web serive) to array of objects. Once I delete that attribute, everything worked fine...so yes, this is "element centric XML serialization". But, is there any way to work around it?