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
202,547
<p>I am writing a command-line tool for Windows that uses libcurl to download files from the internet.</p> <p>Obviously, the downloading doesn't work when the user is behind a proxy server, because the proxy needs to be configured. I want to keep my tool as simple as possible however, and not have to burden the user with having to configure the proxy. My tool doesn't even have a config file, so the user would otherwise have to pass in the proxy settings on every command, or set an environment variable or somesuch -- way too much hassle.</p> <p>So I thought, everyone's browser will usually already be set up properly, proxy configured and everything. This will be true for even the most basic user because otherwise "their internet wouldn't work".</p> <p>So I figure that I can find out whether to use a proxy by looking at IE's proxy settings.</p> <p>How do I go about this? More specifically:</p> <ul> <li>Is there one set of "proxy settings" in Windows, used by all browsers (probably IE's), or would I have to write different routines for IE, Firefox, Opera, etc?</li> <li>I know that I can probably read the values directly out of the appropriate registry locations if they are configured manually, but does this also work with "automatically detect proxy server?" Do I even have to bother with that option, or is it (almost) never used?</li> </ul> <p>Before people start suggesting alternatives: I'm using C, so I'm limited to the Win32 API, and I really really want to keep using C and libcurl.</p>
[ { "answer_id": 202608, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 1, "selected": false, "text": "<p>There are registry keys for these values that you could get to directly of course. You could also do this in .NET without much hassle at all. I believe the WebClient object negotiates the proxy settings for you based on the current settings. This would look like this in C#:</p>\n\n<pre><code>using System.Net;\n\nstring url = \"http://www.example.com\";\nWebClient client = new WebClient();\nbyte[] fileBuffer = client.DownloadFile(url);\n</code></pre>\n\n<p>Or something close to that.</p>\n" }, { "answer_id": 203008, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 6, "selected": true, "text": "<p>The function you're looking for is WinHttpGetIEProxyConfigForCurrentUser(), which is documented at <a href=\"http://msdn.microsoft.com/en-us/library/aa384096(VS.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa384096(VS.85).aspx</a>. This function is used by Firefox and Opera to get their proxy settings by default, although you can override them per-browser. Don't do that, though. The right thing to do (which is what everybody else does) is to just get the IE settings and assume that they're correct, since they almost always are.</p>\n\n<p>Here's a sample of the relevant logic, which you should adapt for your needs:</p>\n\n<pre><code>if( WinHttpGetIEProxyConfigForCurrentUser( &amp;ieProxyConfig ) )\n{\n if( ieProxyConfig.fAutoDetect )\n {\n fAutoProxy = TRUE;\n }\n\n if( ieProxyConfig.lpszAutoConfigUrl != NULL )\n {\n fAutoProxy = TRUE;\n autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl;\n }\n}\nelse\n{\n // use autoproxy\n fAutoProxy = TRUE;\n}\n\nif( fAutoProxy )\n{\n if ( autoProxyOptions.lpszAutoConfigUrl != NULL )\n {\n autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;\n }\n else\n {\n autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;\n autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;\n }\n\n // basic flags you almost always want\n autoProxyOptions.fAutoLogonIfChallenged = TRUE;\n\n // here we reset fAutoProxy in case an auto-proxy isn't actually\n // configured for this url\n fAutoProxy = WinHttpGetProxyForUrl( hiOpen, pwszUrl, &amp;autoProxyOptions, &amp;autoProxyInfo );\n}\n\nif ( fAutoProxy )\n{\n // set proxy options for libcurl based on autoProxyInfo\n}\nelse\n{\n if( ieProxyConfig.lpszProxy != NULL )\n {\n // IE has an explicit proxy. set proxy options for libcurl here\n // based on ieProxyConfig\n //\n // note that sometimes IE gives just a single or double colon\n // for proxy or bypass list, which means \"no proxy\"\n }\n else\n {\n // there is no auto proxy and no manually configured proxy\n }\n}\n</code></pre>\n" }, { "answer_id": 228668, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 0, "selected": false, "text": "<p>For Firefox/Seamonkey, the problem is a bit more tricky because of the existence of many profiles.</p>\n\n<p>If you want to assume there is only one profile then you just need to find prefs.js. You parse the network.proxy.type, and then use it to decide, which related values to read.</p>\n\n<p>I'm working on some documents for mozilla, so put your followup questions in here (checked wiki box), and I'll try to give you the info you need.</p>\n" }, { "answer_id": 11750887, "author": "Maksym Kozlenko", "author_id": 171847, "author_profile": "https://Stackoverflow.com/users/171847", "pm_score": 2, "selected": false, "text": "<p>Here is a complete code sample how to call <code>WinHttpGetIEProxyConfigForCurrentUser</code> method from <code>winhttp.dll</code> library in C# </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>[TestClass]\npublic class UnitTest1\n{\n [StructLayout(LayoutKind.Sequential)]\n public struct WinhttpCurrentUserIeProxyConfig\n {\n [MarshalAs(UnmanagedType.Bool)]\n public bool AutoDetect;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string AutoConfigUrl;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string Proxy;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string ProxyBypass;\n\n }\n\n [DllImport(\"winhttp.dll\", SetLastError = true)]\n static extern bool WinHttpGetIEProxyConfigForCurrentUser(ref WinhttpCurrentUserIeProxyConfig pProxyConfig);\n\n [TestMethod]\n public void TestMethod1()\n {\n var config = new WinhttpCurrentUserIeProxyConfig();\n\n WinHttpGetIEProxyConfigForCurrentUser(ref config);\n\n Console.WriteLine(config.Proxy);\n Console.WriteLine(config.AutoConfigUrl);\n Console.WriteLine(config.AutoDetect);\n Console.WriteLine(config.ProxyBypass);\n }\n}\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2474/" ]
I am writing a command-line tool for Windows that uses libcurl to download files from the internet. Obviously, the downloading doesn't work when the user is behind a proxy server, because the proxy needs to be configured. I want to keep my tool as simple as possible however, and not have to burden the user with having to configure the proxy. My tool doesn't even have a config file, so the user would otherwise have to pass in the proxy settings on every command, or set an environment variable or somesuch -- way too much hassle. So I thought, everyone's browser will usually already be set up properly, proxy configured and everything. This will be true for even the most basic user because otherwise "their internet wouldn't work". So I figure that I can find out whether to use a proxy by looking at IE's proxy settings. How do I go about this? More specifically: * Is there one set of "proxy settings" in Windows, used by all browsers (probably IE's), or would I have to write different routines for IE, Firefox, Opera, etc? * I know that I can probably read the values directly out of the appropriate registry locations if they are configured manually, but does this also work with "automatically detect proxy server?" Do I even have to bother with that option, or is it (almost) never used? Before people start suggesting alternatives: I'm using C, so I'm limited to the Win32 API, and I really really want to keep using C and libcurl.
The function you're looking for is WinHttpGetIEProxyConfigForCurrentUser(), which is documented at <http://msdn.microsoft.com/en-us/library/aa384096(VS.85).aspx>. This function is used by Firefox and Opera to get their proxy settings by default, although you can override them per-browser. Don't do that, though. The right thing to do (which is what everybody else does) is to just get the IE settings and assume that they're correct, since they almost always are. Here's a sample of the relevant logic, which you should adapt for your needs: ``` if( WinHttpGetIEProxyConfigForCurrentUser( &ieProxyConfig ) ) { if( ieProxyConfig.fAutoDetect ) { fAutoProxy = TRUE; } if( ieProxyConfig.lpszAutoConfigUrl != NULL ) { fAutoProxy = TRUE; autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl; } } else { // use autoproxy fAutoProxy = TRUE; } if( fAutoProxy ) { if ( autoProxyOptions.lpszAutoConfigUrl != NULL ) { autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; } else { autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; } // basic flags you almost always want autoProxyOptions.fAutoLogonIfChallenged = TRUE; // here we reset fAutoProxy in case an auto-proxy isn't actually // configured for this url fAutoProxy = WinHttpGetProxyForUrl( hiOpen, pwszUrl, &autoProxyOptions, &autoProxyInfo ); } if ( fAutoProxy ) { // set proxy options for libcurl based on autoProxyInfo } else { if( ieProxyConfig.lpszProxy != NULL ) { // IE has an explicit proxy. set proxy options for libcurl here // based on ieProxyConfig // // note that sometimes IE gives just a single or double colon // for proxy or bypass list, which means "no proxy" } else { // there is no auto proxy and no manually configured proxy } } ```
202,552
<p>How do you get a pointer to the .text section of memory for a program from within that program? I also need the length of the section to do a "Flash to Memory" compare as part of a continuous selftest that runs in the background.</p> <p>The toolset automatically generates the linker .cmd file for the tools I'm using, and the Board Support Package for the board I'm using requires I use the generated .cmd file instead of making my own. (No make file either to add a script to muck with it afterwords.)</p> <p>Edit: I'm working with a TI TMS 6713 DSP using the code composer 3.1 environment. The card I'm using was contracted by our customer and produced by another organization so I can't really point you to any info on it. However the BSP is dependant upon TI's "DSP BIOS" config tool, and I can't really fudge the settings too much without digging into an out of scope effort.</p>
[ { "answer_id": 202572, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": 2, "selected": false, "text": "<p>You need to put \"variables\" in the linker script.</p>\n\n<p>In one of my projects I have this in one of my sections:</p>\n\n<pre><code> __FlashStart = .;\n</code></pre>\n\n<p>In the C program I have this:</p>\n\n<pre><code>extern unsigned long int _FlashStart;\nunsigned long int address = (unsigned long int)&amp;_FlashStart;\n</code></pre>\n" }, { "answer_id": 203670, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 2, "selected": false, "text": "<p>It would definitely be easier if you could modify the linker script. Since you cannot, it is possible to extract section names, addresses, and sizes from the program binary. For example, here is how one would use libbfd to examine all code sections.</p>\n\n<pre><code>#include &lt;bfd.h&gt;\n\nbfd *abfd;\nasection *p;\nchar *filename = \"/path/to/my/file\";\n\nif ((abfd = bfd_openr(filename, NULL)) == NULL) {\n /* ... error handling */\n}\n\nif (!bfd_check_format (abfd, bfd_object)) {\n /* ... error handling */\n}\n\nfor (p = abfd-&gt;sections; p != NULL; p = p-&gt;next) {\n bfd_vma base_addr = bfd_section_vma(abfd, p);\n bfd_size_type size = bfd_section_size (abfd, p);\n const char *name = bfd_section_name(abfd, p);\n flagword flags = bfd_get_section_flags(abfd, p);\n\n if (flags &amp; SEC_CODE) {\n printf(\"%s: addr=%p size=%d\\n\", name, base_addr, size);\n }\n}\n</code></pre>\n\n<p>If you only want to look at the .text segment, you'd strcmp against the section name.</p>\n\n<p>The downside of this approach? Libbfd is licensed under the GPL, so your entire project would be encumbered with the GPL. For a commercial project, this might be a non-starter.</p>\n\n<p>If your binary is in ELF format, you could use libelf instead. I'm not familiar with how the libelf APIs work, so I can't provide sample code. The Linux libelf is also GPL, but I believe the BSD projects have their own libelf which you could use.</p>\n\n<p><b>Edit:</b> as you're working on a DSP in a minimal real-time OS environment, this answer isn't going to work. Sorry, I tried.</p>\n" }, { "answer_id": 203700, "author": "LarryH", "author_id": 13923, "author_profile": "https://Stackoverflow.com/users/13923", "pm_score": 1, "selected": false, "text": "<p>Could you clarify which tool chain and architecture you are interested in.</p>\n\n<p>On the compiler I am using right now (IAR ARM C/C++) there are operators built into the compiler which return the segment begin address <code>__sfb(...)</code>, segment end address <code>__sfe(...)</code>, and segment size <code>__sfs(...)</code></p>\n" }, { "answer_id": 206598, "author": "ZungBang", "author_id": 27831, "author_profile": "https://Stackoverflow.com/users/27831", "pm_score": 1, "selected": false, "text": "<p>The symbols you're looking for are <code>__text__</code> and <code>__etext__</code> which point to the start and end of the <code>.text</code> section, respectively.</p>\n\n<p>You may find the generated <code>.map</code> file useful, as it lists all the symbols and sections defined in your application.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134597/" ]
How do you get a pointer to the .text section of memory for a program from within that program? I also need the length of the section to do a "Flash to Memory" compare as part of a continuous selftest that runs in the background. The toolset automatically generates the linker .cmd file for the tools I'm using, and the Board Support Package for the board I'm using requires I use the generated .cmd file instead of making my own. (No make file either to add a script to muck with it afterwords.) Edit: I'm working with a TI TMS 6713 DSP using the code composer 3.1 environment. The card I'm using was contracted by our customer and produced by another organization so I can't really point you to any info on it. However the BSP is dependant upon TI's "DSP BIOS" config tool, and I can't really fudge the settings too much without digging into an out of scope effort.
You need to put "variables" in the linker script. In one of my projects I have this in one of my sections: ``` __FlashStart = .; ``` In the C program I have this: ``` extern unsigned long int _FlashStart; unsigned long int address = (unsigned long int)&_FlashStart; ```
202,560
<p>So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields. </p> <p>One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:</p> <pre><code>var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg"); </code></pre> <p>As for static fields, is creating singelton-objects their best use? </p>
[ { "answer_id": 202577, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 5, "selected": true, "text": "<p>It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.</p>\n\n<p><strong>EDIT</strong>: From stevemegson in the comments</p>\n\n<blockquote>\n <p>A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.</p>\n</blockquote>\n" }, { "answer_id": 202585, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 5, "selected": false, "text": "<p>Static methods are usually useful for operations that don't require any data from an instance of the class (from <code>this</code>) and can perform their intended purpose solely using their arguments.<br>\nA simple example of this would be a method <code>Point::distance(Point a, Point b);</code> that calculates the distance between two points and don't require an instance.</p>\n\n<p>Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.</p>\n" }, { "answer_id": 202587, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 3, "selected": false, "text": "<p>I would say use static methods whenever you have functions which are independent of the state of the instance, ie. doesn't depend on any instance fields. </p>\n\n<p>The less non-local state that a method depends on, the easier it is to understand, so <code>static</code> is a helpful signal to the reader of the code.</p>\n" }, { "answer_id": 202604, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 3, "selected": false, "text": "<p>I keep it clear by remembering that instance methods work on/inside individual objects while static methods do something for the Class.</p>\n\n<p>In the case of LoadFromFile(), you want a static method because you want a null reference if the load fails - the instance doesn't exist yet. If you implemented it as a constructor, you'd have to throw an Exception on failure.</p>\n\n<p>Other good uses for statics: Compare(obj a, obj b), Delete(obj a) for data objects (an object can't delete itself since its reference is still around), or static Classes for procedural code that honestly can't be modeled in an object.</p>\n" }, { "answer_id": 202617, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 0, "selected": false, "text": "<p>You may use static methods when the client of the class do not have an instance of the class to work with. For instance the Singleton design pattern is used to ensure that only one instance of a class exist in the system. It requires that the constructors of the Singleton be private so that no instances can be created by the client.</p>\n\n<p>So if you cannot create an instance how do you access the instance methods of the class? By calling a static method that returns the Singleton instance of the class.</p>\n\n<p>This is of course just one scenario but there are many others.</p>\n" }, { "answer_id": 202689, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 1, "selected": false, "text": "<p>Here are some examples of when you might want to use static methods:</p>\n\n<p>1) When the function doesn't make use of any member variables. You don't have to use a static method here, but it usually helps if you do.</p>\n\n<p>2) When using factory methods to create objects. They are particularly necessary if you don't know the type to be created in advance: e.g.</p>\n\n<pre><code>class AbstractClass {\n static createObject(int i) {\n if (i==1) {\n return new ConcreteClass1();\n } else if (i==2) {\n return new ConcreteClass2();\n }\n }\n}\n</code></pre>\n\n<p>3) When you are controlling, or otherwise keeping track of, the number of instantiations of the class. The Singleton is the most used example of this.</p>\n\n<p>4) When declaring constants.</p>\n\n<p>5) Operations such as sorts or comparisons that operate on multiple objects of a class and are not tied to any particular instance.</p>\n\n<p>6) When special handling has to be done before the first instantiation of an object.</p>\n" }, { "answer_id": 203880, "author": "David Grayson", "author_id": 28128, "author_profile": "https://Stackoverflow.com/users/28128", "pm_score": 2, "selected": false, "text": "<p>You should use static methods whenever you have a function that does not depend on a particular object of that class.</p>\n\n<p>There is no harm in adding the static keyword: it will not break any of the code that referred to it. So for example, the following code is valid whether or not you have the 'static' keyword:</p>\n\n<pre><code>class Foo\n{\n public Foo(){}\n public static void bar(){} // valid with or without 'static'\n public void nonStatic(){ bar(); }\n}\n\n...\nFoo a = new Foo();\na.bar();\n</code></pre>\n\n<p>So you should add 'static' to whatever methods you can.</p>\n" }, { "answer_id": 49628227, "author": "A Coder", "author_id": 1083030, "author_profile": "https://Stackoverflow.com/users/1083030", "pm_score": 3, "selected": false, "text": "<p>Use a static method when the method does not belong to a specific object.</p>\n\n<p>For example, if you look at the Math class in .NET framework, you will see\nthat all methods are static. Why? Because there is no reason to must create\nan object to use the methods. Why would you want to create an object of the\n<code>Math</code> class, when all you want is the absolute value of something? No, there\nis no reason to do this, and therefore, the method is static.</p>\n\n<p>So when you design a class, ask yourself:</p>\n\n<p>Does this method belong to an object, or the class itself?</p>\n\n<p>A method belongs to an object, if it modifies the state of the object. If\nthe method does not modify a specific object, it can most likely be static.</p>\n\n<p>Another example, suppose that you want to know how many objects of a class\nthat is created (don't ask me why...). For this task, you could create a\nstatic method <code>GetNumberOfObjects()</code> (and you obviously need a static field,\nand some code in the constructor too). Why would i have it static, you might\nask. Well, answer the above question, and you will see. The method does not\nbelong to any specific object. Additionally, it does not modify any object.</p>\n\n<p>I hope this makes sense.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322/" ]
So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields. One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example: ``` var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg"); ``` As for static fields, is creating singelton-objects their best use?
It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string. **EDIT**: From stevemegson in the comments > > A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one. > > >
202,605
<p>What is the best or most concise method for returning a string repeated an arbitrary amount of times?</p> <p>The following is my best shot so far:</p> <pre><code>function repeat(s, n){ var a = []; while(a.length &lt; n){ a.push(s); } return a.join(''); } </code></pre>
[ { "answer_id": 202626, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<pre><code>function repeat(s, n) { var r=\"\"; for (var a=0;a&lt;n;a++) r+=s; return r;}\n</code></pre>\n" }, { "answer_id": 202627, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 9, "selected": false, "text": "<blockquote>\n <p><strong>Note to new readers:</strong> This answer is old and and not terribly practical - it's just \"clever\" because it uses Array stuff to get\n String things done. When I wrote \"less process\" I definitely meant\n \"less code\" because, as others have noted in subsequent answers, it\n performs like a pig. So don't use it if speed matters to you.</p>\n</blockquote>\n\n<p>I'd put this function onto the String object directly. Instead of creating an array, filling it, and joining it with an empty char, just create an array of the proper length, and join it with your desired string. Same result, less process!</p>\n\n<pre><code>String.prototype.repeat = function( num )\n{\n return new Array( num + 1 ).join( this );\n}\n\nalert( \"string to repeat\\n\".repeat( 4 ) );\n</code></pre>\n" }, { "answer_id": 1411966, "author": "BitOfUniverse", "author_id": 172159, "author_profile": "https://Stackoverflow.com/users/172159", "pm_score": 3, "selected": false, "text": "<pre><code>/** \n@desc: repeat string \n@param: n - times \n@param: d - delimiter \n*/\n\nString.prototype.repeat = function (n, d) {\n return --n ? this + (d || '') + this.repeat(n, d) : '' + this\n};\n</code></pre>\n\n<p>this is how to repeat string several times using delimeter.</p>\n" }, { "answer_id": 2433358, "author": "antichris", "author_id": 292382, "author_profile": "https://Stackoverflow.com/users/292382", "pm_score": 4, "selected": false, "text": "<p>Expanding <a href=\"https://stackoverflow.com/questions/202605/repeat-string-javascript/202627#202627\">P.Bailey's solution</a>:</p>\n\n<pre><code>String.prototype.repeat = function(num) {\n return new Array(isNaN(num)? 1 : ++num).join(this);\n }\n</code></pre>\n\n<p>This way you should be safe from unexpected argument types:</p>\n\n<pre><code>var foo = 'bar';\nalert(foo.repeat(3)); // Will work, \"barbarbar\"\nalert(foo.repeat('3')); // Same as above\nalert(foo.repeat(true)); // Same as foo.repeat(1)\n\nalert(foo.repeat(0)); // This and all the following return an empty\nalert(foo.repeat(false)); // string while not causing an exception\nalert(foo.repeat(null));\nalert(foo.repeat(undefined));\nalert(foo.repeat({})); // Object\nalert(foo.repeat(function () {})); // Function\n</code></pre>\n\n<p><em>EDIT: Credits to <a href=\"https://stackoverflow.com/users/108448/jerone\">jerone</a> for his elegant <code>++num</code> idea!</em></p>\n" }, { "answer_id": 4152613, "author": "wnrph", "author_id": 345520, "author_profile": "https://Stackoverflow.com/users/345520", "pm_score": 5, "selected": false, "text": "<p>This one is pretty efficient</p>\n\n<pre><code>String.prototype.repeat = function(times){\n var result=\"\";\n var pattern=this;\n while (times &gt; 0) {\n if (times&amp;1)\n result+=pattern;\n times&gt;&gt;=1;\n pattern+=pattern;\n }\n return result;\n};\n</code></pre>\n" }, { "answer_id": 5450113, "author": "disfated", "author_id": 489553, "author_profile": "https://Stackoverflow.com/users/489553", "pm_score": 8, "selected": false, "text": "<p>I've tested the performance of all the proposed approaches.</p>\n<p>Here is <strong>the fastest variant</strong> I've got.</p>\n<pre><code>String.prototype.repeat = function(count) {\n if (count &lt; 1) return '';\n var result = '', pattern = this.valueOf();\n while (count &gt; 1) {\n if (count &amp; 1) result += pattern;\n count &gt;&gt;= 1, pattern += pattern;\n }\n return result + pattern;\n};\n</code></pre>\n<p>Or as <strong>stand-alone</strong> function:</p>\n<pre><code>function repeat(pattern, count) {\n if (count &lt; 1) return '';\n var result = '';\n while (count &gt; 1) {\n if (count &amp; 1) result += pattern;\n count &gt;&gt;= 1, pattern += pattern;\n }\n return result + pattern;\n}\n</code></pre>\n<p>It is based on <a href=\"https://stackoverflow.com/users/345520/wnrph\">wnrph's</a> algorithm.\nIt is really fast. And the bigger the <code>count</code>, the faster it goes compared with the traditional <code>new Array(count + 1).join(string)</code> approach.</p>\n<p>I've only changed 2 things:</p>\n<ol>\n<li>replaced <code>pattern = this</code> with <code>pattern = this.valueOf()</code> (clears one obvious type conversion);</li>\n<li>added <code>if (count &lt; 1)</code> check from <a href=\"http://www.prototypejs.org/api/string/times\" rel=\"nofollow noreferrer\">prototypejs</a> to the top of function to exclude unnecessary actions in that case.</li>\n<li>applied optimisation from <a href=\"https://stackoverflow.com/users/1913959/dennis\">Dennis</a> <a href=\"https://stackoverflow.com/a/14026829/489553\">answer</a> (5-7% speed up)</li>\n</ol>\n<p><strong>UPD</strong></p>\n<p>Created a little performance-testing playground <a href=\"http://jsfiddle.net/disfated/GejWV/\" rel=\"nofollow noreferrer\">here</a> for those who interested.</p>\n<p><em>variable <code>count</code> ~ 0 .. 100:</em></p>\n<p><a href=\"https://i.stack.imgur.com/i6JSb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i6JSb.png\" alt=\"Performance diagram\" /></a></p>\n<p><em>constant <code>count</code> = 1024:</em></p>\n<p><a href=\"https://i.stack.imgur.com/jidKX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jidKX.png\" alt=\"Performance diagram\" /></a></p>\n<p>Use it and make it even faster if you can :)</p>\n" }, { "answer_id": 6557722, "author": "John", "author_id": 825985, "author_profile": "https://Stackoverflow.com/users/825985", "pm_score": 2, "selected": false, "text": "<p>This may be the smallest recursive one:-</p>\n\n<pre><code>String.prototype.repeat = function(n,s) {\ns = s || \"\"\nif(n&gt;0) {\n s += this\n s = this.repeat(--n,s)\n}\nreturn s}\n</code></pre>\n" }, { "answer_id": 7649473, "author": "Fordi", "author_id": 353872, "author_profile": "https://Stackoverflow.com/users/353872", "pm_score": 1, "selected": false, "text": "<p>Recursive solution using divide and conquer:</p>\n\n<pre><code>function repeat(n, s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n with(Math) { return repeat(floor(n/2), s)+repeat(ceil(n/2), s); }\n}\n</code></pre>\n" }, { "answer_id": 7649897, "author": "Fordi", "author_id": 353872, "author_profile": "https://Stackoverflow.com/users/353872", "pm_score": 2, "selected": false, "text": "<p>Tests of the various methods:</p>\n\n<pre><code>var repeatMethods = {\n control: function (n,s) {\n /* all of these lines are common to all methods */\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n return '';\n },\n divideAndConquer: function (n, s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n with(Math) { return arguments.callee(floor(n/2), s)+arguments.callee(ceil(n/2), s); }\n },\n linearRecurse: function (n,s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n return s+arguments.callee(--n, s);\n },\n newArray: function (n, s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n return (new Array(isNaN(n) ? 1 : ++n)).join(s);\n },\n fillAndJoin: function (n, s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n var ret = [];\n for (var i=0; i&lt;n; i++)\n ret.push(s);\n return ret.join('');\n },\n concat: function (n,s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n var ret = '';\n for (var i=0; i&lt;n; i++)\n ret+=s;\n return ret;\n },\n artistoex: function (n,s) {\n var result = '';\n while (n&gt;0) {\n if (n&amp;1) result+=s;\n n&gt;&gt;=1, s+=s;\n };\n return result;\n }\n};\nfunction testNum(len, dev) {\n with(Math) { return round(len+1+dev*(random()-0.5)); }\n}\nfunction testString(len, dev) {\n return (new Array(testNum(len, dev))).join(' ');\n}\nvar testTime = 1000,\n tests = {\n biggie: { str: { len: 25, dev: 12 }, rep: {len: 200, dev: 50 } },\n smalls: { str: { len: 5, dev: 5}, rep: { len: 5, dev: 5 } }\n };\nvar testCount = 0;\nvar winnar = null;\nvar inflight = 0;\nfor (var methodName in repeatMethods) {\n var method = repeatMethods[methodName];\n for (var testName in tests) {\n testCount++;\n var test = tests[testName];\n var testId = methodName+':'+testName;\n var result = {\n id: testId,\n testParams: test\n }\n result.count=0;\n\n (function (result) {\n inflight++;\n setTimeout(function () {\n result.start = +new Date();\n while ((new Date() - result.start) &lt; testTime) {\n method(testNum(test.rep.len, test.rep.dev), testString(test.str.len, test.str.dev));\n result.count++;\n }\n result.end = +new Date();\n result.rate = 1000*result.count/(result.end-result.start)\n console.log(result);\n if (winnar === null || winnar.rate &lt; result.rate) winnar = result;\n inflight--;\n if (inflight==0) {\n console.log('The winner: ');\n console.log(winnar);\n }\n }, (100+testTime)*testCount);\n }(result));\n }\n}\n</code></pre>\n" }, { "answer_id": 9655348, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here's the JSLint safe version</p>\n\n<pre><code>String.prototype.repeat = function (num) {\n var a = [];\n a.length = num &lt;&lt; 0 + 1;\n return a.join(this);\n};\n</code></pre>\n" }, { "answer_id": 14026829, "author": "Dennis", "author_id": 1913959, "author_profile": "https://Stackoverflow.com/users/1913959", "pm_score": 3, "selected": false, "text": "<p>Here's a 5-7% improvement on disfated's answer.</p>\n\n<p>Unroll the loop by stopping at <code>count &gt; 1</code> and perform an additional <code>result += pattnern</code> concat after the loop. This will avoid the loops final previously unused <code>pattern += pattern</code> without having to use an expensive if-check.\nThe final result would look like this:</p>\n\n<pre><code>String.prototype.repeat = function(count) {\n if (count &lt; 1) return '';\n var result = '', pattern = this.valueOf();\n while (count &gt; 1) {\n if (count &amp; 1) result += pattern;\n count &gt;&gt;= 1, pattern += pattern;\n }\n result += pattern;\n return result;\n};\n</code></pre>\n\n<p>And here's disfated's fiddle forked for the unrolled version: <a href=\"http://jsfiddle.net/wsdfg/\" rel=\"noreferrer\">http://jsfiddle.net/wsdfg/</a></p>\n" }, { "answer_id": 14580575, "author": "Semra", "author_id": 1262441, "author_profile": "https://Stackoverflow.com/users/1262441", "pm_score": 2, "selected": false, "text": "<p>If you think all those prototype definitions, array creations, and join operations are overkill, just use a single line code where you need it. String S repeating N times:</p>\n\n<pre><code>for (var i = 0, result = ''; i &lt; N; i++) result += S;\n</code></pre>\n" }, { "answer_id": 15423652, "author": "Andrew Hallendorff", "author_id": 2171624, "author_profile": "https://Stackoverflow.com/users/2171624", "pm_score": 1, "selected": false, "text": "<p>I came here randomly and never had a reason to repeat a char in javascript before.</p>\n\n<p>I was impressed by artistoex's way of doing it and disfated's results. I noticed that the last string concat was unnecessary, as Dennis also pointed out.</p>\n\n<p>I noticed a few more things when playing with the sampling disfated put together.</p>\n\n<p>The results varied a fair amount often favoring the last run and similar algorithms would often jockey for position. One of the things I changed was instead of using the JSLitmus generated count as the seed for the calls; as count was generated different for the various methods, I put in an index. This made the thing much more reliable. I then looked at ensuring that varying sized strings were passed to the functions. This prevented some of the variations I saw, where some algorithms did better at the single chars or smaller strings. However the top 3 methods all did well regardless of the string size. </p>\n\n<p>Forked test set</p>\n\n<p><a href=\"http://jsfiddle.net/schmide/fCqp3/134/\" rel=\"nofollow\">http://jsfiddle.net/schmide/fCqp3/134/</a></p>\n\n<pre><code>// repeated string\nvar string = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789';\n// count paremeter is changed on every test iteration, limit it's maximum value here\nvar maxCount = 200;\n\nvar n = 0;\n$.each(tests, function (name) {\n var fn = tests[name];\n JSLitmus.test(++n + '. ' + name, function (count) {\n var index = 0;\n while (count--) {\n fn.call(string.slice(0, index % string.length), index % maxCount);\n index++;\n }\n });\n if (fn.call('&gt;', 10).length !== 10) $('body').prepend('&lt;h1&gt;Error in \"' + name + '\"&lt;/h1&gt;');\n});\n\nJSLitmus.runAll();\n</code></pre>\n\n<p>I then included Dennis' fix and decided to see if I could find a way to eek out a bit more.</p>\n\n<p>Since javascript can't really optimize things, the best way to improve performance is to manually avoid things. If I took the first 4 trivial results out of the loop, I could avoid 2-4 string stores and write the final store directly to the result.</p>\n\n<pre><code>// final: growing pattern + prototypejs check (count &lt; 1)\n'final avoid': function (count) {\n if (!count) return '';\n if (count == 1) return this.valueOf();\n var pattern = this.valueOf();\n if (count == 2) return pattern + pattern;\n if (count == 3) return pattern + pattern + pattern;\n var result;\n if (count &amp; 1) result = pattern;\n else result = '';\n count &gt;&gt;= 1;\n do {\n pattern += pattern;\n if (count &amp; 1) result += pattern;\n count &gt;&gt;= 1;\n } while (count &gt; 1);\n return result + pattern + pattern;\n}\n</code></pre>\n\n<p>This resulted in a 1-2% improvement on average over Dennis' fix. However, different runs and different browsers would show a fair enough variance that this extra code probably isn't worth the effort over the 2 previous algorithms.</p>\n\n<p><a href=\"http://chart.apis.google.com/chart?chtt=String.repeat%28%29%20mesure%20-%20jsFiddle%20demo%20by%20schmide|Ops/sec%20%28Chrome%2025.0.1364.172%20on%20Windows%20NT%29&amp;chts=000000,10&amp;cht=bhg&amp;chd=t:43623,125090,796212,1650378,3130496,3242799,3402753&amp;chds=0,3402753&amp;chxt=x&amp;chxl=0%3a|0|3.4M&amp;chsp=0,1&amp;chm=t1.%20new%20Array.join%28%29%20%28prototypejs%29%2843.6K%29,000000,0,0,10|t2.%20array.push%28%29.join%28%29%28125.1K%29,000000,0,1,10|t3.%20%28result%20%2b%3D%20string%29%20x%20count%28796.2K%29,000000,0,2,10|t4.%20result%20%2b%3D%20growing%20pattern%281.7M%29,000000,0,3,10|t5.%20final%283.1M%29,000000,0,4,10|t6.%20final%20unrolled%283.2M%29,000000,0,5,10|t7.%20final%20avoid%283.4M%29,000000,0,6,10&amp;chbh=15,0,5&amp;chs=250x210\" rel=\"nofollow\">A chart</a></p>\n\n<p>Edit: I did this mostly under chrome. Firefox and IE will often favor Dennis by a couple %.</p>\n" }, { "answer_id": 16800987, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 1, "selected": false, "text": "<p>Simple method:</p>\n\n<pre><code>String.prototype.repeat = function(num) {\n num = parseInt(num);\n if (num &lt; 0) return '';\n return new Array(num + 1).join(this);\n}\n</code></pre>\n" }, { "answer_id": 17800645, "author": "Joseph Myers", "author_id": 2188862, "author_profile": "https://Stackoverflow.com/users/2188862", "pm_score": 6, "selected": false, "text": "<p>This problem is a well-known / \"classic\" optimization issue for JavaScript, caused by the fact that JavaScript strings are \"immutable\" and addition by concatenation of even a single character to a string requires creation of, including memory allocation for and copying to, an entire new string.</p>\n\n<p>Unfortunately, the accepted answer on this page is wrong, where \"wrong\" means by a performance factor of 3x for simple one-character strings, and 8x-97x for short strings repeated more times, to 300x for repeating sentences, and infinitely wrong when taking the limit of the ratios of complexity of the algorithms as <code>n</code> goes to infinity. Also, there is another answer on this page which is almost right (based on one of the many generations and variations of the correct solution circulating throughout the Internet in the past 13 years). However, this \"almost right\" solution misses a key point of the correct algorithm causing a 50% performance degradation.</p>\n\n<p><a href=\"http://jsperf.com/repeating-strings\" rel=\"noreferrer\" title=\"JS Performance Results for the accepted answer, the top-performing other answer, and this answer\">JS Performance Results for the accepted answer, the top-performing other answer (based on a degraded version of the original algorithm in this answer), and this answer using my algorithm created 13 years ago</a></p>\n\n<p>~ October 2000 I published an algorithm for this exact problem which was widely adapted, modified, then eventually poorly understood and forgotten. To remedy this issue, in August, 2008 I published an article <a href=\"http://www.webreference.com/programming/javascript/jkm3/3.html\" rel=\"noreferrer\">http://www.webreference.com/programming/javascript/jkm3/3.html</a> explaining the algorithm and using it as an example of simple of general-purpose JavaScript optimizations. By now, <em>Web Reference</em> has scrubbed my contact information and even my name from this article. And once again, the algorithm has been widely adapted, modified, then poorly understood and largely forgotten.</p>\n\n<blockquote>\n <p>Original string repetition/multiplication JavaScript algorithm by\n Joseph Myers, circa Y2K as a text multiplying function within Text.js;\n published August, 2008 in this form by Web Reference:\n <a href=\"http://www.webreference.com/programming/javascript/jkm3/3.html\" rel=\"noreferrer\">http://www.webreference.com/programming/javascript/jkm3/3.html</a> (The\n article used the function as an example of JavaScript optimizations,\n which is the only for the strange name \"stringFill3.\")</p>\n</blockquote>\n\n<pre><code>/*\n * Usage: stringFill3(\"abc\", 2) == \"abcabc\"\n */\n\nfunction stringFill3(x, n) {\n var s = '';\n for (;;) {\n if (n &amp; 1) s += x;\n n &gt;&gt;= 1;\n if (n) x += x;\n else break;\n }\n return s;\n}\n</code></pre>\n\n<p>Within two months after publication of that article, this same question was posted to Stack Overflow and flew under my radar until now, when apparently the original algorithm for this problem has once again been forgotten. The best solution available on this Stack Overflow page is a modified version of my solution, possibly separated by several generations. Unfortunately, the modifications ruined the solution's optimality. In fact, by changing the structure of the loop from my original, the modified solution performs a completely unneeded extra step of exponential duplicating (thus joining the largest string used in the proper answer with itself an extra time and then discarding it).</p>\n\n<p>Below ensues a discussion of some JavaScript optimizations related to all of the answers to this problem and for the benefit of all.</p>\n\n<h2>Technique: Avoid references to objects or object properties</h2>\n\n<p>To illustrate how this technique works, we use a real-life JavaScript function which creates strings of whatever length is needed. And as we'll see, more optimizations can be added!</p>\n\n<p>A function like the one used here is to create padding to align columns of text, for formatting money, or for filling block data up to the boundary. A text generation function also allows variable length input for testing any other function that operates on text. This function is one of the important components of the JavaScript text processing module.</p>\n\n<p>As we proceed, we will be covering two more of the most important optimization techniques while developing the original code into an optimized algorithm for creating strings. The final result is an industrial-strength, high-performance function that I've used everywhere--aligning item prices and totals in JavaScript order forms, data formatting and email / text message formatting and many other uses.</p>\n\n<p><strong>Original code for creating strings <code>stringFill1()</code></strong></p>\n\n<pre><code>function stringFill1(x, n) { \n var s = ''; \n while (s.length &lt; n) s += x; \n return s; \n} \n/* Example of output: stringFill1('x', 3) == 'xxx' */ \n</code></pre>\n\n<p>The syntax is here is clear. As you can see, we've used local function variables already, before going on to more optimizations.</p>\n\n<p>Be aware that there's one innocent reference to an object property <code>s.length</code> in the code that hurts its performance. Even worse, the use of this object property reduces the simplicity of the program by making the assumption that the reader knows about the properties of JavaScript string objects.</p>\n\n<p>The use of this object property destroys the generality of the computer program. The program assumes that <code>x</code> must be a string of length one. This limits the application of the <code>stringFill1()</code> function to anything except repetition of single characters. Even single characters cannot be used if they contain multiple bytes like the HTML entity <code>&amp;nbsp;</code>.</p>\n\n<p>The worst problem caused by this unnecessary use of an object property is that the function creates an infinite loop if tested on an empty input string <code>x</code>. To check generality, apply a program to the smallest possible amount of input. A program which crashes when asked to exceed the amount of available memory has an excuse. A program like this one which crashes when asked to produce nothing is unacceptable. Sometimes pretty code is poisonous code.</p>\n\n<p>Simplicity may be an ambiguous goal of computer programming, but generally it's not. When a program lacks any reasonable level of generality, it's not valid to say, \"The program is good enough as far as it goes.\" As you can see, using the <code>string.length</code> property prevents this program from working in a general setting, and in fact, the incorrect program is ready to cause a browser or system crash.</p>\n\n<p>Is there a way to improve the performance of this JavaScript as well as take care of these two serious problems?</p>\n\n<p>Of course. Just use integers.</p>\n\n<p><strong>Optimized code for creating strings <code>stringFill2()</code></strong></p>\n\n<pre><code>function stringFill2(x, n) { \n var s = ''; \n while (n-- &gt; 0) s += x; \n return s; \n} \n</code></pre>\n\n<p><strong>Timing code to compare <code>stringFill1()</code> and <code>stringFill2()</code></strong></p>\n\n<pre><code>function testFill(functionToBeTested, outputSize) { \n var i = 0, t0 = new Date(); \n do { \n functionToBeTested('x', outputSize); \n t = new Date() - t0; \n i++; \n } while (t &lt; 2000); \n return t/i/1000; \n} \nseconds1 = testFill(stringFill1, 100); \nseconds2 = testFill(stringFill2, 100); \n</code></pre>\n\n<p><strong>The success so far of <code>stringFill2()</code></strong></p>\n\n<p><code>stringFill1()</code> takes 47.297 microseconds (millionths of a second) to fill a 100-byte string, and <code>stringFill2()</code> takes 27.68 microseconds to do the same thing. That's almost a doubling in performance by avoiding a reference to an object property.</p>\n\n<h2>Technique: Avoid adding short strings to long strings</h2>\n\n<p>Our previous result looked good--very good, in fact. The improved function <code>stringFill2()</code> is much faster due to the use of our first two optimizations. Would you believe it if I told you that it can be improved to be many times faster than it is now?</p>\n\n<p>Yes, we can accomplish that goal. Right now we need to explain how we avoid appending short strings to long strings.</p>\n\n<p>The short-term behavior appears to be quite good, in comparison to our original function. Computer scientists like to analyze the \"asymptotic behavior\" of a function or computer program algorithm, which means to study its long-term behavior by testing it with larger inputs. Sometimes without doing further tests, one never becomes aware of ways that a computer program could be improved. To see what will happen, we're going to create a 200-byte string.</p>\n\n<p><strong>The problem that shows up with <code>stringFill2()</code></strong></p>\n\n<p>Using our timing function, we find that the time increases to 62.54 microseconds for a 200-byte string, compared to 27.68 for a 100-byte string. It seems like the time should be doubled for doing twice as much work, but instead it's tripled or quadrupled. From programming experience, this result seems strange, because if anything, the function should be slightly faster since work is being done more efficiently (200 bytes per function call rather than 100 bytes per function call). This issue has to do with an insidious property of JavaScript strings: JavaScript strings are \"immutable.\"</p>\n\n<p>Immutable means that you cannot change a string once it's created. By adding on one byte at a time, we're not using up one more byte of effort. We're actually recreating the entire string plus one more byte.</p>\n\n<p>In effect, to add one more byte to a 100-byte string, it takes 101 bytes worth of work. Let's briefly analyze the computational cost for creating a string of <code>N</code> bytes. The cost of adding the first byte is 1 unit of computational effort. The cost of adding the second byte isn't one unit but 2 units (copying the first byte to a new string object as well as adding the second byte). The third byte requires a cost of 3 units, etc.</p>\n\n<p><code>C(N) = 1 + 2 + 3 + ... + N = N(N+1)/2 = O(N^2)</code>. The symbol <code>O(N^2)</code> is pronounced Big O of N squared, and it means that the computational cost in the long run is proportional to the square of the string length. To create 100 characters takes 10,000 units of work, and to create 200 characters takes 40,000 units of work.</p>\n\n<p>This is why it took more than twice as long to create 200 characters than 100 characters. In fact, it should have taken four times as long. Our programming experience was correct in that the work is being done slightly more efficiently for longer strings, and hence it took only about three times as long. Once the overhead of the function call becomes negligible as to how long of a string we're creating, it will actually take four times as much time to create a string twice as long.</p>\n\n<p>(Historical note: This analysis doesn't necessarily apply to strings in source code, such as <code>html = 'abcd\\n' + 'efgh\\n' + ... + 'xyz.\\n'</code>, since the JavaScript source code compiler can join the strings together before making them into a JavaScript string object. Just a few years ago, the KJS implementation of JavaScript would freeze or crash when loading long strings of source code joined by plus signs. Since the computational time was <code>O(N^2)</code> it wasn't difficult to make Web pages which overloaded the Konqueror Web browser or Safari, which used the KJS JavaScript engine core. I first came across this issue when I was developing a markup language and JavaScript markup language parser, and then I discovered what was causing the problem when I wrote my script for JavaScript Includes.)</p>\n\n<p>Clearly this rapid degradation of performance is a huge problem. How can we deal with it, given that we cannot change JavaScript's way of handling strings as immutable objects? The solution is to use an algorithm which recreates the string as few times as possible.</p>\n\n<p>To clarify, our goal is to avoid adding short strings to long strings, since in order to add the short string, the entire long string also must be duplicated.</p>\n\n<p>How the algorithm works to avoid adding short strings to long strings</p>\n\n<p>Here's a good way to reduce the number of times new string objects are created. Concatenate longer lengths of string together so that more than one byte at a time is added to the output.</p>\n\n<p>For instance, to make a string of length <code>N = 9</code>:</p>\n\n<pre><code>x = 'x'; \ns = ''; \ns += x; /* Now s = 'x' */ \nx += x; /* Now x = 'xx' */ \nx += x; /* Now x = 'xxxx' */ \nx += x; /* Now x = 'xxxxxxxx' */ \ns += x; /* Now s = 'xxxxxxxxx' as desired */\n</code></pre>\n\n<p>Doing this required creating a string of length 1, creating a string of length 2, creating a string of length 4, creating a string of length 8, and finally, creating a string of length 9. How much cost have we saved?</p>\n\n<p>Old cost <code>C(9) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 9 = 45</code>.</p>\n\n<p>New cost <code>C(9) = 1 + 2 + 4 + 8 + 9 = 24</code>.</p>\n\n<p>Note that we had to add a string of length 1 to a string of length 0, then a string of length 1 to a string of length 1, then a string of length 2 to a string of length 2, then a string of length 4 to a string of length 4, then a string of length 8 to a string of length 1, in order to obtain a string of length 9. What we're doing can be summarized as avoiding adding short strings to long strings, or in other words, trying to concatenate strings together that are of equal or nearly equal length.</p>\n\n<p>For the old computational cost we found a formula <code>N(N+1)/2</code>. Is there a formula for the new cost? Yes, but it's complicated. The important thing is that it is <code>O(N)</code>, and so doubling the string length will approximately double the amount of work rather than quadrupling it.</p>\n\n<p>The code that implements this new idea is nearly as complicated as the formula for the computational cost. When you read it, remember that <code>&gt;&gt;= 1</code> means to shift right by 1 byte. So if <code>n = 10011</code> is a binary number, then <code>n &gt;&gt;= 1</code> results in the value <code>n = 1001</code>.</p>\n\n<p>The other part of the code you might not recognize is the bitwise and operator, written <code>&amp;</code>. The expression <code>n &amp; 1</code> evaluates true if the last binary digit of <code>n</code> is 1, and false if the last binary digit of <code>n</code> is 0.</p>\n\n<p><strong>New highly-efficient <code>stringFill3()</code> function</strong></p>\n\n<pre><code>function stringFill3(x, n) { \n var s = ''; \n for (;;) { \n if (n &amp; 1) s += x; \n n &gt;&gt;= 1; \n if (n) x += x; \n else break; \n } \n return s; \n} \n</code></pre>\n\n<p>It looks ugly to the untrained eye, but it's performance is nothing less than lovely.</p>\n\n<p>Let's see just how well this function performs. After seeing the results, it's likely that you'll never forget the difference between an <code>O(N^2)</code> algorithm and an <code>O(N)</code> algorithm.</p>\n\n<p><code>stringFill1()</code> takes 88.7 microseconds (millionths of a second) to create a 200-byte string, <code>stringFill2()</code> takes 62.54, and <code>stringFill3()</code> takes only 4.608. What made this algorithm so much better? All of the functions took advantage of using local function variables, but taking advantage of the second and third optimization techniques added a twenty-fold improvement to performance of <code>stringFill3()</code>.</p>\n\n<p><strong>Deeper analysis</strong></p>\n\n<p>What makes this particular function blow the competition out of the water?</p>\n\n<p>As I've mentioned, the reason that both of these functions, <code>stringFill1()</code> and <code>stringFill2()</code>, run so slowly is that JavaScript strings are immutable. Memory cannot be reallocated to allow one more byte at a time to be appended to the string data stored by JavaScript. Every time one more byte is added to the end of the string, the entire string is regenerated from beginning to end.</p>\n\n<p>Thus, in order to improve the script's performance, one must precompute longer length strings by concatenating two strings together ahead of time, and then recursively building up the desired string length.</p>\n\n<p>For instance, to create a 16-letter byte string, first a two byte string would be precomputed. Then the two byte string would be reused to precompute a four-byte string. Then the four-byte string would be reused to precompute an eight byte string. Finally, two eight-byte strings would be reused to create the desired new string of 16 bytes. Altogether four new strings had to be created, one of length 2, one of length 4, one of length 8 and one of length 16. The total cost is 2 + 4 + 8 + 16 = 30.</p>\n\n<p>In the long run this efficiency can be computed by adding in reverse order and using a geometric series starting with a first term a1 = N and having a common ratio of r = 1/2. The sum of a geometric series is given by <code>a_1 / (1-r) = 2N</code>.</p>\n\n<p>This is more efficient than adding one character to create a new string of length 2, creating a new string of length 3, 4, 5, and so on, until 16. The previous algorithm used that process of adding a single byte at a time, and the total cost of it would be <code>n (n + 1) / 2 = 16 (17) / 2 = 8 (17) = 136</code>.</p>\n\n<p>Obviously, 136 is a much greater number than 30, and so the previous algorithm takes much, much more time to build up a string.</p>\n\n<p>To compare the two methods you can see how much faster the recursive algorithm (also called \"divide and conquer\") is on a string of length 123,457. On my FreeBSD computer this algorithm, implemented in the <code>stringFill3()</code> function, creates the string in 0.001058 seconds, while the original <code>stringFill1()</code> function creates the string in 0.0808 seconds. The new function is 76 times faster.</p>\n\n<p>The difference in performance grows as the length of the string becomes larger. In the limit as larger and larger strings are created, the original function behaves roughly like <code>C1</code> (constant) times <code>N^2</code>, and the new function behaves like <code>C2</code> (constant) times <code>N</code>.</p>\n\n<p>From our experiment we can determine the value of <code>C1</code> to be <code>C1 = 0.0808 / (123457)2 = .00000000000530126997</code>, and the value of <code>C2</code> to be <code>C2 = 0.001058 / 123457 = .00000000856978543136</code>. In 10 seconds, the new function could create a string containing 1,166,890,359 characters. In order to create this same string, the old function would need 7,218,384 seconds of time.</p>\n\n<p>This is almost three months compared to ten seconds!</p>\n\n<p>I'm only answering (several years late) because my original solution to this problem has been floating around the Internet for more than 10 years, and apparently is still poorly-understood by the few who do remember it. I thought that by writing an article about it here I would help:</p>\n\n<p><a href=\"http://www.webreference.com/programming/javascript/jkm3/3.html\" rel=\"noreferrer\" title=\"Performance Optimizations for High Speed JavaScript / Page 3\">Performance Optimizations for High Speed JavaScript / Page 3</a></p>\n\n<p>Unfortunately, some of the other solutions presented here are still some of those that would take three months to produce the same amount of output that a proper solution creates in 10 seconds.</p>\n\n<p>I want to take the time to reproduce part of the article here as a canonical answer on Stack Overflow.</p>\n\n<p>Note that the best-performing algorithm here is clearly based on my algorithm and was probably inherited from someone else's 3rd or 4th generation adaptation. Unfortunately, the modifications resulted in reducing its performance. The variation of my solution presented here perhaps did not understand my confusing <code>for (;;)</code> expression which looks like the main infinite loop of a server written in C, and which was simply designed to allow a carefully-positioned break statement for loop control, the most compact way to avoid exponentially replicating the string one extra unnecessary time.</p>\n" }, { "answer_id": 25135949, "author": "Robin Rizvi", "author_id": 1145904, "author_profile": "https://Stackoverflow.com/users/1145904", "pm_score": 2, "selected": false, "text": "<p>Fiddle: <a href=\"http://jsfiddle.net/3Y9v2/\" rel=\"nofollow\">http://jsfiddle.net/3Y9v2/</a></p>\n\n<pre><code>function repeat(s, n){\n return ((new Array(n+1)).join(s));\n}\nalert(repeat('R', 10));\n</code></pre>\n" }, { "answer_id": 25586878, "author": "Nelo Mitranim", "author_id": 1882154, "author_profile": "https://Stackoverflow.com/users/1882154", "pm_score": 1, "selected": false, "text": "<p>People overcomplicate this to a ridiculous extent or waste performance. Arrays? Recursion? You've got to be kidding me.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function repeat (string, times) {\n var result = ''\n while (times-- &gt; 0) result += string\n return result\n}\n</code></pre>\n\n<p><strong>Edit.</strong> I ran some simple tests to compare with the bitwise version posted by artistoex / disfated and a bunch of other people. The latter was only marginally faster, but orders of magnitude more memory-efficient. For 1000000 repeats of the word 'blah', the Node process went up to 46 megabytes with the simple concatenation algorithm (above), but only 5.5 megabytes with the logarithmic algorithm. The latter is definitely the way to go. Reposting it for the sake of clarity:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function repeat (string, times) {\n var result = ''\n while (times &gt; 0) {\n if (times &amp; 1) result += string\n times &gt;&gt;= 1\n string += string\n }\n return result\n}\n</code></pre>\n" }, { "answer_id": 26414234, "author": "Fred Gandt", "author_id": 1832568, "author_profile": "https://Stackoverflow.com/users/1832568", "pm_score": 2, "selected": false, "text": "<h1>Simple recursive concatenation</h1>\n<p>I just wanted to give it a bash, and made this:</p>\n<pre><code>function ditto( s, r, c ) {\n return c-- ? ditto( s, r += s, c ) : r;\n}\n\nditto( &quot;foo&quot;, &quot;&quot;, 128 );\n</code></pre>\n<p>I can't say I gave it much thought, and it probably shows :-)</p>\n<h2><em>This</em> is arguably better</h2>\n<pre><code>String.prototype.ditto = function( c ) {\n return --c ? this + this.ditto( c ) : this;\n};\n\n&quot;foo&quot;.ditto( 128 );\n</code></pre>\n<p>And it's a lot like an answer already posted - I know this.</p>\n<h2>But why be recursive at all?</h2>\n<p>And how about a little default behaviour too?</p>\n<pre><code>String.prototype.ditto = function() {\n var c = Number( arguments[ 0 ] ) || 2,\n r = this.valueOf();\n while ( --c ) {\n r += this;\n }\n return r;\n}\n\n&quot;foo&quot;.ditto();\n</code></pre>\n<p><strong>Because</strong>, although the non recursive method will handle arbitrarily large repeats without hitting call stack limits, it's a lot slower.</p>\n<h2>Why did I bother adding more methods that aren't half as <em>clever</em> as those already posted?</h2>\n<p>Partly for my own amusement, and partly to point out in the simplest way I know that there are many ways to skin a cat, and depending on the situation, it's quite possible that the apparently <em>best</em> method isn't ideal.</p>\n<p>A relatively fast and sophisticated method may effectively crash and burn under certain circumstances, whilst a slower, simpler method may get the job done - eventually.</p>\n<p>Some methods may be little more than exploits, and as such prone to being <em>fixed</em> out of existence, and other methods may work beautifully in all conditions, but are so constructed that <em>one</em> simply has no idea how it works.</p>\n<p><em>&quot;So what if I dunno how it works?!&quot;</em></p>\n<p>Seriously?</p>\n<p>JavaScript suffers from one of its greatest strengths; it's highly tolerant of bad behaviour, and so flexible it'll bend over backwards to return results, when it might have been better for everyone if it'd snapped!</p>\n<p><em>&quot;With great power, comes great responsibility&quot;</em> ;-)</p>\n<p>But more seriously and importantly, although general questions like this do lead to awesomeness in the form of <em>clever</em> answers that if nothing else, expand one's knowledge and horizons, in the end, the task at hand - the practical script that uses the resulting method - may require a little less, or a little more <em>clever</em> than is suggested.</p>\n<p>These <em>&quot;perfect&quot;</em> algorithms are fun and all, but <em>&quot;one size fits all&quot;</em> will rarely if ever be better than tailor made.</p>\n<p>This sermon was brought to you courtesy of a lack of sleep and a passing interest.\nGo forth and code!</p>\n" }, { "answer_id": 27325273, "author": "André Laszlo", "author_id": 98057, "author_profile": "https://Stackoverflow.com/users/98057", "pm_score": 7, "selected": true, "text": "<p>Good news! <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\" rel=\"nofollow noreferrer\"><code>String.prototype.repeat</code></a> is <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-string.prototype.repeat\" rel=\"nofollow noreferrer\">now a part of JavaScript</a>.</p>\n<pre><code>&quot;yo&quot;.repeat(2);\n// returns: &quot;yoyo&quot;\n</code></pre>\n<p>The method is supported by all major browsers, except Internet Explorer. For an up to date list, see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#Browser_compatibility\" rel=\"nofollow noreferrer\">MDN: String.prototype.repeat &gt; Browser compatibility</a>.</p>\n<p>MDN has <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\" rel=\"nofollow noreferrer\">a polyfill </a> for browsers without support.</p>\n" }, { "answer_id": 27548734, "author": "Guss", "author_id": 53538, "author_profile": "https://Stackoverflow.com/users/53538", "pm_score": 2, "selected": false, "text": "<p>Firstly, the OP's questions seems to be about conciseness - which I understand to mean \"simple and easy to read\", while most answers seem to be about efficiency - which is obviously not the same thing and also I think that unless you implement some very specific large data manipulating algorithms, shouldn't worry you when you come to implement basic data manipulation Javascript functions. Conciseness is much more important.</p>\n\n<p>Secondly, as André Laszlo noted, String.repeat is part of ECMAScript 6 and already available in several popular implementations - so the most concise implementation of <code>String.repeat</code> is not to implement it ;-)</p>\n\n<p>Lastly, if you need to support hosts that don't offer the ECMAScript 6 implementation, MDN's polyfill mentioned by André Laszlo is anything but concise. </p>\n\n<p>So, without further ado - here is my <strong>concise</strong> polyfill:</p>\n\n<pre><code>String.prototype.repeat = String.prototype.repeat || function(n){\n return n&lt;=1 ? this : this.concat(this.repeat(n-1));\n}\n</code></pre>\n\n<p>Yes, this is a recursion. I like recursions - they are simple and if done correctly are easy to understand. Regarding efficiency, if the language supports it they can be very efficient if written correctly.</p>\n\n<p>From my tests, this method is ~60% faster than the <code>Array.join</code> approach. Although it obviously comes nowhere close disfated's implementation, it is much simpler than both. </p>\n\n<p>My test setup is node v0.10, using \"Strict mode\" (I think it enables some sort of <a href=\"https://code.google.com/p/v8/issues/detail?id=457\" rel=\"nofollow\">TCO</a>), calling <code>repeat(1000)</code> on a 10 character string a million times.</p>\n" }, { "answer_id": 29483806, "author": "Lewis", "author_id": 3247703, "author_profile": "https://Stackoverflow.com/users/3247703", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\">String.prototype.repeat</a> is now ES6 Standard.</p>\n\n<pre><code>'abc'.repeat(3); //abcabcabc\n</code></pre>\n" }, { "answer_id": 32133812, "author": "Kalpesh Patel", "author_id": 1044026, "author_profile": "https://Stackoverflow.com/users/1044026", "pm_score": 3, "selected": false, "text": "<p>Use <code>Array(N+1).join(\"string_to_repeat\")</code></p>\n" }, { "answer_id": 33530860, "author": "l3x", "author_id": 1978383, "author_profile": "https://Stackoverflow.com/users/1978383", "pm_score": 2, "selected": false, "text": "<p>Use Lodash for Javascript utility functionality, like repeating strings.</p>\n\n<p>Lodash provides nice performance and ECMAScript compatibility.</p>\n\n<p>I highly recommend it for UI development and it works well server side, too.</p>\n\n<p>Here's how to repeat the string \"yo\" 2 times using Lodash:</p>\n\n<pre><code>&gt; _.repeat('yo', 2)\n\"yoyo\"\n</code></pre>\n" }, { "answer_id": 35634264, "author": "John Slegers", "author_id": 1946501, "author_profile": "https://Stackoverflow.com/users/1946501", "pm_score": 2, "selected": false, "text": "<h3>For all browsers</h3>\n<p>This is about as concise as it gets :</p>\n<pre><code>function repeat(s, n) { return new Array(n+1).join(s); }\n</code></pre>\n<p>If you also care about performance, this is a much better approach :</p>\n<pre><code>function repeat(s, n) { var a=[],i=0;for(;i&lt;n;)a[i++]=s;return a.join(''); }\n</code></pre>\n<p>If you want to compare the performance of both options, see <a href=\"https://jsfiddle.net/mf2jwjym/\" rel=\"nofollow noreferrer\"><strong>this Fiddle</strong></a> and <a href=\"https://jsfiddle.net/mf2jwjym/2/\" rel=\"nofollow noreferrer\"><strong>this Fiddle</strong></a> for benchmark tests. During my own tests, the second option was about 2 times faster in Firefox and about 4 times faster in Chrome!</p>\n<h3>For moderns browsers only :</h3>\n<p>In modern browsers, you can now also do this :</p>\n<pre><code>function repeat(s,n) { return s.repeat(n) };\n</code></pre>\n<p>This option is not only shorter than both other options, but it's <a href=\"http://The%20numbers%20in%20the%20table%20specify%20the%20first%20browser%20version%20that%20fully%20supports%20the%20method.\" rel=\"nofollow noreferrer\"><strong>even faster</strong></a> than the second option.</p>\n<p>Unfortunately, it doesn't work in any version of Internet explorer. The numbers in the table specify the first browser version that fully supports the method :</p>\n<p><a href=\"https://i.stack.imgur.com/B3PVU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B3PVU.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 36173160, "author": "nikolay", "author_id": 626067, "author_profile": "https://Stackoverflow.com/users/626067", "pm_score": 2, "selected": false, "text": "<pre><code>function repeat(pattern, count) {\n for (var result = '';;) {\n if (count &amp; 1) {\n result += pattern;\n }\n if (count &gt;&gt;= 1) {\n pattern += pattern;\n } else {\n return result;\n }\n }\n}\n</code></pre>\n\n<p>You can test it at <a href=\"https://jsfiddle.net/nikolay/h4kxoaog/\" rel=\"nofollow\">JSFiddle</a>. Benchmarked against the hacky <code>Array.join</code> and mine is, roughly speaking, <a href=\"https://jsfiddle.net/nikolay/Lgshxrk8/\" rel=\"nofollow\">10 (Chrome) to 100 (Safari) to 200 (Firefox) times faster</a> (depending on the browser).</p>\n" }, { "answer_id": 36678697, "author": "karlzafiris", "author_id": 4141689, "author_profile": "https://Stackoverflow.com/users/4141689", "pm_score": 1, "selected": false, "text": "<p>Concatenating strings based on an number.</p>\n\n<pre><code>function concatStr(str, num) {\n var arr = [];\n\n //Construct an array\n for (var i = 0; i &lt; num; i++)\n arr[i] = str;\n\n //Join all elements\n str = arr.join('');\n\n return str;\n}\n\nconsole.log(concatStr(\"abc\", 3));\n</code></pre>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 41574167, "author": "xgqfrms", "author_id": 5934465, "author_profile": "https://Stackoverflow.com/users/5934465", "pm_score": 2, "selected": false, "text": "<h1>There are many ways in the <code>ES-Next</code> ways</h1>\n<h2>1. <code>ES2015</code>/<code>ES6</code> has been realized this <code>repeat()</code> method!</h2>\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>/** \n * str: String\n * count: Number\n */\nconst str = `hello repeat!\\n`, count = 3;\n\nlet resultString = str.repeat(count);\n\nconsole.log(`resultString = \\n${resultString}`);\n/*\nresultString = \nhello repeat!\nhello repeat!\nhello repeat!\n*/\n\n({ toString: () =&gt; 'abc', repeat: String.prototype.repeat }).repeat(2);\n// 'abcabc' (repeat() is a generic method)\n\n// Examples\n\n'abc'.repeat(0); // ''\n'abc'.repeat(1); // 'abc'\n'abc'.repeat(2); // 'abcabc'\n'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer)\n// 'abc'.repeat(1/0); // RangeError\n// 'abc'.repeat(-1); // RangeError</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>2. <code>ES2017</code>/<code>ES8</code> new add <code>String.prototype.padStart()</code></h2>\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 str = 'abc ';\nconst times = 3;\n\nconst newStr = str.padStart(str.length * times, str.toUpperCase());\n\nconsole.log(`newStr =`, newStr);\n// \"newStr =\" \"ABC ABC abc \"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>3. <code>ES2017</code>/<code>ES8</code> new add <code>String.prototype.padEnd()</code></h2>\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 str = 'abc ';\nconst times = 3;\n\nconst newStr = str.padEnd(str.length * times, str.toUpperCase());\n\nconsole.log(`newStr =`, newStr);\n// \"newStr =\" \"abc ABC ABC \"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>refs</h2>\n<p><a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.repeat\" rel=\"nofollow noreferrer\">http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.repeat</a></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat</a></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart</a></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd</a></p>\n" }, { "answer_id": 41905186, "author": "oboshto", "author_id": 2160038, "author_profile": "https://Stackoverflow.com/users/2160038", "pm_score": 2, "selected": false, "text": "<p>Just another repeat function:</p>\n\n<pre><code>function repeat(s, n) {\n var str = '';\n for (var i = 0; i &lt; n; i++) {\n str += s;\n }\n return str;\n}\n</code></pre>\n" }, { "answer_id": 55944841, "author": "wizzfizz94", "author_id": 7144427, "author_profile": "https://Stackoverflow.com/users/7144427", "pm_score": 1, "selected": false, "text": "<p>With ES8 you could also use <code>padStart</code> or <code>padEnd</code> for this. eg.</p>\n\n<pre><code>var str = 'cat';\nvar num = 23;\nvar size = str.length * num;\n\"\".padStart(size, str) // outputs: 'catcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcat'\n</code></pre>\n" }, { "answer_id": 63642522, "author": "saigowthamr", "author_id": 9278645, "author_profile": "https://Stackoverflow.com/users/9278645", "pm_score": 1, "selected": false, "text": "<p>To repeat a string in a specified number of times, we can use the built-in <code>repeat()</code> method in JavaScript.</p>\n<p>Here is an example that repeats the following string for 4 times:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const name = &quot;king&quot;;\n\nconst repeat = name.repeat(4);\n\nconsole.log(repeat);\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>&quot;kingkingkingking&quot;\n</code></pre>\n<p>or we can create our own verison of <code>repeat()</code> function like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function repeat(str, n) {\n if (!str || !n) {\n return;\n }\n\n let final = &quot;&quot;;\n while (n) {\n final += s;\n n--;\n }\n return final;\n}\n\nconsole.log(repeat(&quot;king&quot;, 3))\n</code></pre>\n<p>(originally posted at <a href=\"https://reactgo.com/javascript-repeat-string/\" rel=\"nofollow noreferrer\">https://reactgo.com/javascript-repeat-string/</a>)</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
What is the best or most concise method for returning a string repeated an arbitrary amount of times? The following is my best shot so far: ``` function repeat(s, n){ var a = []; while(a.length < n){ a.push(s); } return a.join(''); } ```
Good news! [`String.prototype.repeat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat) is [now a part of JavaScript](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-string.prototype.repeat). ``` "yo".repeat(2); // returns: "yoyo" ``` The method is supported by all major browsers, except Internet Explorer. For an up to date list, see [MDN: String.prototype.repeat > Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#Browser_compatibility). MDN has [a polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat) for browsers without support.
202,609
<p>This is what I currently have:</p> <pre><code>CREATE OR REPLACE TRIGGER MYTRIGGER AFTER INSERT ON SOMETABLE FOR EACH ROW DECLARE v_emplid varchar2(10); BEGIN SELECT personnum into v_emplid FROM PERSON WHERE PERSONID = :new.EMPLOYEEID; dbms_output.put(v_emplid); /* INSERT INTO SOMEOTHERTABLE USING v_emplid and some of the other values from the trigger table*/ END MYTRIGGER; </code></pre> <p>DBA_ERRORS has this error: PL/SQL: ORA-00923: FROM keyword not found where expected</p>
[ { "answer_id": 202621, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": -1, "selected": false, "text": "<p>I would not use a select statment in a trigger ever. Insert into the table rather than a select into. Once the table already exists select into does not work in most databases.</p>\n" }, { "answer_id": 202634, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 4, "selected": true, "text": "<p>1) There must be something else to your example because that sure seems to work for me</p>\n\n<pre><code>SQL&gt; create table someTable( employeeid number );\n\nTable created.\n\nSQL&gt; create table person( personid number, personnum varchar2(10) );\n\nTable created.\n\nSQL&gt; ed\nWrote file afiedt.buf\n\n 1 CREATE OR REPLACE TRIGGER MYTRIGGER\n 2 AFTER INSERT ON SOMETABLE\n 3 FOR EACH ROW\n 4 DECLARE\n 5 v_emplid varchar2(10);\n 6 BEGIN\n 7 SELECT personnum\n 8 into v_emplid\n 9 FROM PERSON\n 10 WHERE PERSONID = :new.EMPLOYEEID;\n 11 dbms_output.put(v_emplid);\n 12 /* INSERT INTO SOMEOTHERTABLE USING v_emplid and some of the other values\n from the trigger table*/\n 13* END MYTRIGGER;\n 14 /\n\nTrigger created.\n\nSQL&gt; insert into person values( 1, '123' );\n\n1 row created.\n\nSQL&gt; insert into sometable values( 1 );\n\n1 row created.\n</code></pre>\n\n<p>2) You probably want to declare V_EMPLID as being of type Person.PersonNum%TYPE so that you can be certain that the data type is correct and so that if the data type of the table changes you won't need to change your code.</p>\n\n<p>3) I assume that you know that your trigger cannot query or update the table on which the trigger is defined (so no queries or inserts into someTable).</p>\n" }, { "answer_id": 202692, "author": "Jason V", "author_id": 27912, "author_profile": "https://Stackoverflow.com/users/27912", "pm_score": 1, "selected": false, "text": "<p>You are playing with Lava (not just fire) in your trigger. DBMS_OUTPUT in a trigger is really, really bad. You can blow-out on a buffer overflow in your trigger and the whole transaction is shot. Good luck tracking that down. If you must do output-to-console like behavior, invoke an AUTONOMOUS TRANSACTION procedure that writes to a table.</p>\n\n<p>Triggers are pretty evil. I used to like them, but they are too hard to remember about. They affect data often times leading to MUTATING data (scary and not just because Halloween is close).</p>\n\n<p>We use triggers to change the value of columns like .new:LAST_MODIFIED := sysdate and .new:LAST_MODIFIED_BY := user. That's it.</p>\n\n<p>Don't ever allow a TRIGGER to prevent a transaction from completing. Find another option.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20836/" ]
This is what I currently have: ``` CREATE OR REPLACE TRIGGER MYTRIGGER AFTER INSERT ON SOMETABLE FOR EACH ROW DECLARE v_emplid varchar2(10); BEGIN SELECT personnum into v_emplid FROM PERSON WHERE PERSONID = :new.EMPLOYEEID; dbms_output.put(v_emplid); /* INSERT INTO SOMEOTHERTABLE USING v_emplid and some of the other values from the trigger table*/ END MYTRIGGER; ``` DBA\_ERRORS has this error: PL/SQL: ORA-00923: FROM keyword not found where expected
1) There must be something else to your example because that sure seems to work for me ``` SQL> create table someTable( employeeid number ); Table created. SQL> create table person( personid number, personnum varchar2(10) ); Table created. SQL> ed Wrote file afiedt.buf 1 CREATE OR REPLACE TRIGGER MYTRIGGER 2 AFTER INSERT ON SOMETABLE 3 FOR EACH ROW 4 DECLARE 5 v_emplid varchar2(10); 6 BEGIN 7 SELECT personnum 8 into v_emplid 9 FROM PERSON 10 WHERE PERSONID = :new.EMPLOYEEID; 11 dbms_output.put(v_emplid); 12 /* INSERT INTO SOMEOTHERTABLE USING v_emplid and some of the other values from the trigger table*/ 13* END MYTRIGGER; 14 / Trigger created. SQL> insert into person values( 1, '123' ); 1 row created. SQL> insert into sometable values( 1 ); 1 row created. ``` 2) You probably want to declare V\_EMPLID as being of type Person.PersonNum%TYPE so that you can be certain that the data type is correct and so that if the data type of the table changes you won't need to change your code. 3) I assume that you know that your trigger cannot query or update the table on which the trigger is defined (so no queries or inserts into someTable).
202,610
<p>I have two scripts that often need to be run with the same parameter:</p> <pre><code>$ populate.ksh 9241 &amp;&amp; check.ksh 9241 </code></pre> <p>When I need to change the parameter (<strong>9241</strong> in this example), I can go back and edit the line in history. But since I need to change the number in two places, I sometimes make a typo. I'd like to be able to change the parameter just once to change it in both places.</p>
[ { "answer_id": 202611, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 1, "selected": false, "text": "<p>One solution is to simply create a wrapper script (<em>populate_check.ksh</em>) that calls the scripts in turn:</p>\n\n<pre><code>r=$1\npopulate.ksh $r &amp;&amp; check.ksh $r\n</code></pre>\n\n<p>Or for multiple parameters:</p>\n\n<pre><code>for r; do\n populate.ksh $r &amp;&amp; check.ksh $r\ndone\n</code></pre>\n\n<p>For tasks that are more transient, you can also parametrize the command so that it's easier to edit in history:</p>\n\n<pre><code>$ r=9241; populate.ksh $r &amp;&amp; check.ksh $r\n</code></pre>\n\n<p>Or to do several at once:</p>\n\n<pre><code>$ for r in 9241 9242; do populate.ksh $r &amp;&amp; check.ksh $r; done\n</code></pre>\n" }, { "answer_id": 202637, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "<p>You can also use the history substitution feature:</p>\n\n<pre><code>!pop:gs/9241/1234\n</code></pre>\n\n<p>Like so:</p>\n\n<pre><code>$ populate.ksh 9241 &amp;&amp; check.ksh 9241\n...\n$ !pop:gs/9241/1234\npopulate.ksh 1234 &amp;&amp; check.ksh 1234\n...\n</code></pre>\n" }, { "answer_id": 202638, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "<p>In bash:</p>\n\n<pre><code>!!:gs/9241/9243/\n</code></pre>\n\n<p>Yes, it uses <code>gs///</code>, not <code>s///g</code>. :-)</p>\n\n<p>(zigdon's answer uses the last command starting with <code>pop</code>, such as <code>populate.sh</code>. My answer uses the last command, full stop. Choose which works for you.)</p>\n" }, { "answer_id": 205286, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "<p>Correct answers have already been given, but for a more general understanding read the manpage with special attention to <strong>\"History Expansion\"</strong> and the associated shell variables (such as \"<code>HISTCONTROL</code>\", \"<code>histchars</code>\", etc.). BTW-- Your pager's search function is very useful when reading <code>man bash</code></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
I have two scripts that often need to be run with the same parameter: ``` $ populate.ksh 9241 && check.ksh 9241 ``` When I need to change the parameter (**9241** in this example), I can go back and edit the line in history. But since I need to change the number in two places, I sometimes make a typo. I'd like to be able to change the parameter just once to change it in both places.
In bash: ``` !!:gs/9241/9243/ ``` Yes, it uses `gs///`, not `s///g`. :-) (zigdon's answer uses the last command starting with `pop`, such as `populate.sh`. My answer uses the last command, full stop. Choose which works for you.)
202,630
<p>How do I determine if an object reference is null in C# w/o throwing an exception if it is null?</p> <p>i.e. If I have a class reference being passed in and I don't know if it is null or not.</p>
[ { "answer_id": 202642, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 0, "selected": false, "text": "<pre><code>(YourObject != Null)\n</code></pre>\n\n<p>you can compare to null?</p>\n\n<p>If it's null instead of throwing an exception you can initialize your object. You can use the Null Pattern.</p>\n" }, { "answer_id": 202646, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 4, "selected": false, "text": "<p>testing against null will never* throw an exception</p>\n\n<pre><code>void DoSomething( MyClass value )\n{\n if( value != null )\n {\n value.Method();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>* never as in <em>should never</em>. As @Ilya Ryzhenkov points out, an <em>incorrect</em> implementation of the != operator for MyClass could throw an exception. Fortunately Greg Beech has a good blog post on <a href=\"http://gregbee.ch/blog/implementing-object-equality-in-dotnet\" rel=\"nofollow noreferrer\">implementing object equality in .NET</a>. </p>\n" }, { "answer_id": 202655, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 0, "selected": false, "text": "<p>Or if you are using value types you can read about nullable types: <a href=\"http://www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx</a></p>\n" }, { "answer_id": 202664, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "<p>What Robert said, but for that particular case I like to express it with a guard clause like this, rather than nest the whole method body in an if block:</p>\n\n<pre><code>void DoSomething( MyClass value )\n{\n if ( value == null ) return;\n // I might throw an ArgumentNullException here, instead\n\n value.Method();\n}\n</code></pre>\n" }, { "answer_id": 202665, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 2, "selected": false, "text": "<pre><code>if(p != null)\n{\n DoWork(p);\n}\n</code></pre>\n\n<p>Also, the 'as' keyword is helpful if you want to detect if a class is of the right type and use it all at once.</p>\n\n<pre><code>IExample e = p as IExample;\nif(e != null)\n DoWork(e);\n</code></pre>\n\n<p>In the above example if you were to cast e like (IExample)e it will throw an exception if e does not implement IExapmle. If you use 'as' and e doesn't implement IExample e will simply be null.</p>\n" }, { "answer_id": 202679, "author": "Fred", "author_id": 177, "author_profile": "https://Stackoverflow.com/users/177", "pm_score": 0, "selected": false, "text": "<p>I have in the application's xaml.cs application derivative definition:</p>\n\n<pre><code>private SortedList myList;\n</code></pre>\n\n<p>And I want to be able to re-use my constructors. So I needed:</p>\n\n<pre><code>if ( myList == null)\n myList = new SortedList();\n</code></pre>\n\n<p>Thanks Robert!</p>\n" }, { "answer_id": 202746, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 3, "selected": false, "text": "<p>Note, that having operator != defined on MyClass would probably lead do different result of a check and NullReferenceException later on. To be absolutely sure, use object.ReferenceEquals(value, null)</p>\n" }, { "answer_id": 202747, "author": "Jason V", "author_id": 27912, "author_profile": "https://Stackoverflow.com/users/27912", "pm_score": 1, "selected": false, "text": "<p>It's nit picky, but I always code these like ...</p>\n\n<pre><code>if (null == obj) {\n obj = new Obj();\n}\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>if (obj == null) {\n obj = new Obj();\n}\n</code></pre>\n\n<p>to avoid accidently writing</p>\n\n<pre><code>if (obj = null) {\n obj = new Obj();\n}\n</code></pre>\n\n<p>because </p>\n\n<pre><code>if (null = obj) {\n obj = new Obj();\n}\n</code></pre>\n\n<p>will give you a compiler error</p>\n" }, { "answer_id": 202760, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": false, "text": "<p>If you look in the majority of the .NET framework source code you will see they put checks like this at the top of their functions.</p>\n\n<pre><code>public void DoSomething(Object myParam)\n{\n if (myParam == null) throw new ArgumentNullException(\"myParam\");\n\n // Carry on\n}\n</code></pre>\n" }, { "answer_id": 35134460, "author": "James Harcourt", "author_id": 1461680, "author_profile": "https://Stackoverflow.com/users/1461680", "pm_score": 2, "selected": false, "text": "<p>With C# 6.0 this is much more elegant; you can do it in one line :-)</p>\n\n<pre><code>value?.Method();\n</code></pre>\n\n<p>If \"value\" is null, nothing will happen - and no exception.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177/" ]
How do I determine if an object reference is null in C# w/o throwing an exception if it is null? i.e. If I have a class reference being passed in and I don't know if it is null or not.
What Robert said, but for that particular case I like to express it with a guard clause like this, rather than nest the whole method body in an if block: ``` void DoSomething( MyClass value ) { if ( value == null ) return; // I might throw an ArgumentNullException here, instead value.Method(); } ```
202,644
<p>e.g, Is the user playing a movie full screen, or looking at powerpoint in full screen mode?</p> <p>I could have sworn I saw a IsFullScreenInteractive API before, but can't find it now</p>
[ { "answer_id": 202680, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "<p>Use GetForegroundWindow to get a handle to the window the user is working with. GetClientRect will give the dimensions of the active part of the window sans borders; use ClientToScreen to convert the rectangle to monitor coordinates.</p>\n\n<p>Call MonitorFromRect or MonitorFromWindow to get the monitor that the window is in. Use GetMonitorInfo to get the coordinates of the monitor.</p>\n\n<p>Compare the two rectangles - if the window rectangle completely covers the monitor rectangle, it's a full screen window.</p>\n" }, { "answer_id": 495389, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 3, "selected": false, "text": "<p>Here's how I've solved this problem:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\n\nnamespace Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(IsForegroundWwindowFullScreen());\n }\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr GetForegroundWindow();\n\n [DllImport(\"user32.dll\")]\n static extern int GetSystemMetrics(int smIndex);\n\n public const int SM_CXSCREEN = 0;\n public const int SM_CYSCREEN = 1;\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool GetWindowRect(IntPtr hWnd, out W32RECT lpRect);\n\n [StructLayout(LayoutKind.Sequential)]\n public struct W32RECT\n {\n public int Left;\n public int Top;\n public int Right;\n public int Bottom;\n }\n\n public static bool IsForegroundWwindowFullScreen()\n {\n int scrX = GetSystemMetrics(SM_CXSCREEN),\n scrY = GetSystemMetrics(SM_CYSCREEN);\n\n IntPtr handle = GetForegroundWindow();\n if (handle == IntPtr.Zero) return false;\n\n W32RECT wRect;\n if (!GetWindowRect(handle, out wRect)) return false;\n\n return scrX == (wRect.Right - wRect.Left) &amp;&amp; scrY == (wRect.Bottom - wRect.Top);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1116727, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The preferred way of detecting the state of a window is by calling <a href=\"http://msdn.microsoft.com/en-us/library/ms633518(VS.85).aspx\" rel=\"nofollow noreferrer\">GetWindowPlacement</a>. If you do that in conjunction with GetForegroundWindow, you can easily check if the user sees a fullscreen window or not.</p>\n" }, { "answer_id": 1211075, "author": "ilmcuts", "author_id": 148178, "author_profile": "https://Stackoverflow.com/users/148178", "pm_score": 2, "selected": false, "text": "<p>Vista indeed has an API pretty much exactly for this purpose - it's called <a href=\"http://msdn.microsoft.com/en-us/library/bb762242%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">SHQueryUserNotificationState</a>.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
e.g, Is the user playing a movie full screen, or looking at powerpoint in full screen mode? I could have sworn I saw a IsFullScreenInteractive API before, but can't find it now
Here's how I've solved this problem: ``` using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Runtime.InteropServices; namespace Test { class Program { static void Main(string[] args) { Console.WriteLine(IsForegroundWwindowFullScreen()); } [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetSystemMetrics(int smIndex); public const int SM_CXSCREEN = 0; public const int SM_CYSCREEN = 1; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetWindowRect(IntPtr hWnd, out W32RECT lpRect); [StructLayout(LayoutKind.Sequential)] public struct W32RECT { public int Left; public int Top; public int Right; public int Bottom; } public static bool IsForegroundWwindowFullScreen() { int scrX = GetSystemMetrics(SM_CXSCREEN), scrY = GetSystemMetrics(SM_CYSCREEN); IntPtr handle = GetForegroundWindow(); if (handle == IntPtr.Zero) return false; W32RECT wRect; if (!GetWindowRect(handle, out wRect)) return false; return scrX == (wRect.Right - wRect.Left) && scrY == (wRect.Bottom - wRect.Top); } } } ```
202,662
<p>I have a VB6 dll that is trying to create a COM object using the following line of code:</p> <pre><code>Set CreateObj = CreateObject("OPSValuer.OPSValue") </code></pre> <p>However this fails with the error "Object variable or With block variable not set".</p> <p>I can see OPSValuer.OPSValue in dcomcnfg and it appears to be registered fine. Does anyone have any ideas about what may be causing the problem?</p>
[ { "answer_id": 202876, "author": "DMKing", "author_id": 10887, "author_profile": "https://Stackoverflow.com/users/10887", "pm_score": 2, "selected": false, "text": "<p>It's possible that the class you are trying to instantiate is not installed correctly or is missing some dependencies. If you have access to OLE View, you can try instantiating that class outside of VB. If it won't instantiate then you have a bad installation or missing dependency. OLE View ships with Visual Studio, search for OleView.exe on your system.</p>\n\n<p>It was located here on my system: D:\\Program Files\\Microsoft Visual Studio 8\\Common7\\Tools\\Bin</p>\n" }, { "answer_id": 202898, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>The error may be thrown within the object initializing routine. That I don't find \"OPSValuer.OPSValue\" on Google makes me think it is custom code that encounters a bug.</p>\n" }, { "answer_id": 203405, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 3, "selected": true, "text": "<p>DMKing is right about OleView. Also try looking at the control in <a href=\"http://www.dependencywalker.com/\" rel=\"nofollow noreferrer\">Dependency Walker</a>, any missing dependencies should come quickly to the surface. </p>\n\n<p>Since this is a DCom component there also may be something failing in the components constructor, if anything fails in the constructor you will get that error. Is this a local DCom object or something running on another tier?</p>\n\n<p>Instead of CreateObject try instantiating it with a standard New and see if it gives you a different error. Adding the reference itself may help out with determining that error. Is there a reason you are using late binding, rather than early binding?</p>\n" }, { "answer_id": 213491, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>Assuming <code>OPSValuer.OPSValue</code> is a component written in VB, this is probably an error raised in the <code>Class_Initialize</code> event of that component. If you have the source code of the component it should be easy to debug.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ]
I have a VB6 dll that is trying to create a COM object using the following line of code: ``` Set CreateObj = CreateObject("OPSValuer.OPSValue") ``` However this fails with the error "Object variable or With block variable not set". I can see OPSValuer.OPSValue in dcomcnfg and it appears to be registered fine. Does anyone have any ideas about what may be causing the problem?
DMKing is right about OleView. Also try looking at the control in [Dependency Walker](http://www.dependencywalker.com/), any missing dependencies should come quickly to the surface. Since this is a DCom component there also may be something failing in the components constructor, if anything fails in the constructor you will get that error. Is this a local DCom object or something running on another tier? Instead of CreateObject try instantiating it with a standard New and see if it gives you a different error. Adding the reference itself may help out with determining that error. Is there a reason you are using late binding, rather than early binding?
202,663
<p>I am testing an application that checks if a file exists across a network. In my testing, I am purposefully pulling the network plug so the file will not be found. The problem is this causes my app to go unresponsive for at least 15 seconds. I have used both the FileExists() and GetAttr() functions in VB6. Does anyone know how to fix this problem? (No, I can't stop using VB6)</p> <p>Thanks, Charlie</p>
[ { "answer_id": 202672, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 0, "selected": false, "text": "<p>I'm not sure you can handle this much more gracefully - if the network is having problems it can take a while for timeouts to indicate that the problem is severe enough that things aren't working.</p>\n\n<p>If VB6 supports threading (I honestly don't recall) you could spin the file open into a background thread, and have the UI allow the user to cancel it (or perform other operations if that makes sense), but that introduces a pretty significant amount of additional complexity.</p>\n" }, { "answer_id": 202762, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>VB is inherently single threaded, but you can divert work to a COM component to do an asynchronous file check and flag an event when it is done. This way the UI thread stays at responsive at least. Trouble is - this is all theory, I don't know such a component. </p>\n\n<p>But wait! Google just turned up this: <a href=\"http://msdn.microsoft.com/en-us/library/bb381704(VS.80).aspx\" rel=\"nofollow noreferrer\">Visual Basic 6 Asynchronous File I/O Using the .NET Framework</a>. Does that help, maybe?</p>\n\n<p>Also, they have something similar over at CodeProject: <a href=\"http://www.codeproject.com/KB/vbscript/AsyncSample.aspx\" rel=\"nofollow noreferrer\">Asynchronous processing - Basics and a walkthrough with VB6/ VB.NET</a></p>\n" }, { "answer_id": 202781, "author": "JFV", "author_id": 1391, "author_profile": "https://Stackoverflow.com/users/1391", "pm_score": 0, "selected": false, "text": "<p>VB6 has some networking functions that can test to see if the network is connected. You should be able to add in under 'References' the 'NetCon 1.0 Type Library'. This adds for you the NETCONLib. Once implemented, you should be able to test for network connectivity first, then test for the FileExists and GetAttr.</p>\n\n<p>Let me know if this helps!</p>\n" }, { "answer_id": 202852, "author": "Bullines", "author_id": 27870, "author_profile": "https://Stackoverflow.com/users/27870", "pm_score": -1, "selected": false, "text": "<p>I agree with Will. Something like this is simple to handle with Script.FileSystemObject:</p>\n\n<pre><code>Dim objFSO As New FileSystemObject \nIf objFSO.FileExists(\"C:\\path\\to\\your_file.txt\") Then\n ' Do some stuff with the file\nElse\n ' File isn't here...be nice to the user.\nEndIf\n</code></pre>\n" }, { "answer_id": 207042, "author": "coderGeek", "author_id": 28426, "author_profile": "https://Stackoverflow.com/users/28426", "pm_score": -1, "selected": false, "text": "<p>Accessing files over a network can cause these hangs.</p>\n\n<p>It's been a while, but I remember multi-threading in VB6 being relatively painful to implement. A quick solution would be to have a small .exe (perhaps also coded in VB) that can handle this. You could use DDE for inter-app communication or the ever so easy but kludgey file-based pipe, by which I mean a file that both apps will mutually read/write to handle inter-app communication. Of course, using file-based pipes, depending on the details of this scenario, may simply exaggerate the File I/O lag.</p>\n\n<p>If there's a reasonable degree with which you can predict where the user will be selecting files from, you may consider preemptively caching a directory listing and reading that rather than the file directly - assuming the directory contents aren't expected to change frequently. Note: getting a directory listing over a network will cause the same lag issues as individual file I/O over a network. Keep that in mind.</p>\n" }, { "answer_id": 207112, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 3, "selected": false, "text": "<p>Unfortunately, VB doesn't make this easy, but luckily the Win32 API does, and it's quite simple to call Win32 functions from within VB.</p>\n\n<p>For the LAN/WAN, you can use a combination of the following Win32 API calls to tell you whether the remote connection exists without having to deal with a network time-out:</p>\n\n<pre><code>Private Declare Function WNetGetConnection Lib \"mpr.dll\" Alias _\n \"WNetGetConnectionA\" (ByVal lpszLocalName As String, _\n ByVal lpszRemoteName As String, ByRef cbRemoteName As Long) As Long\n\nPrivate Declare Function PathIsNetworkPath Lib \"shlwapi.dll\" Alias _\n \"PathIsNetworkPathA\" (ByVal pszPath As String) As Long\n\nPrivate Declare Function PathIsUNC Lib \"shlwapi.dll\" Alias \"PathIsUNCA\" _\n (ByVal pszPath As String) As Long\n</code></pre>\n\n<p>For the Internet, you can use the Win32 API call:</p>\n\n<pre><code>Private Declare Function InternetGetConnectedState Lib \"wininet.dll\" _\n (ByRef lpdwFlags As Long, ByVal dwReserved As Long) As Long\n\nConst INTERNET_CONNECTION_MODEM = 1\nConst INTERNET_CONNECTION_LAN = 2\nConst INTERNET_CONNECTION_PROXY = 4\nConst INTERNET_CONNECTION_MODEM_BUSY = 8\n</code></pre>\n\n<p>This VB site has more discussion on <a href=\"http://vbnet.mvps.org/index.html?code/fileapi/pathisnetworkpath.htm\" rel=\"nofollow noreferrer\">path oriented functions you can call in the Win32 API through VB.</a></p>\n" }, { "answer_id": 5019777, "author": "Kuuri", "author_id": 620094, "author_profile": "https://Stackoverflow.com/users/620094", "pm_score": 1, "selected": false, "text": "<p>use this too</p>\n\n<pre><code>Dim FlSize as long \nflsize=filelen(\"yourfilepath\")\nif err.number=53 then msgbox(\"file not found\")\nif err.number=78 then msgbox(\"Path Does no Exist\")\n</code></pre>\n" }, { "answer_id": 19256033, "author": "barnameha", "author_id": 2680724, "author_profile": "https://Stackoverflow.com/users/2680724", "pm_score": 0, "selected": false, "text": "<p>this code only used for check connection (maybe can help you) for one of your problems :</p>\n\n<pre><code>Private Declare Function InternetGetConnectedState Lib \"wininet.dll\" (ByRef dwFlags As Long, ByVal dwReserved As Long) As Long\n\nPrivate Const CONNECT_LAN As Long = &amp;H2\n Private Const CONNECT_MODEM As Long = &amp;H1\n Private Const CONNECT_PROXY As Long = &amp;H4\n Private Const CONNECT_OFFLINE As Long = &amp;H20\n Private Const CONNECT_CONFIGURED As Long = &amp;H40\n\n\n\n Public Function checknet() As Boolean\nDim Msg As String\n\n If IsWebConnected(Msg) Then\nchecknet = True\n Else\n If (Msg = \"LAN\") Or (Msg = \"Offline\") Or (Msg = \"Configured\") Or (Msg = \"Proxy\") Then\n\n checknet = False\n End If\n End If\n\n End Function\n\n\n\nPrivate Function IsWebConnected(Optional ByRef ConnType As String) As Boolean\n Dim dwFlags As Long\n Dim WebTest As Boolean\n ConnType = \"\"\n WebTest = InternetGetConnectedState(dwFlags, 0&amp;)\n Select Case WebTest\n Case dwFlags And CONNECT_LAN: ConnType = \"LAN\"\n Case dwFlags And CONNECT_MODEM: ConnType = \"Modem\"\n Case dwFlags And CONNECT_PROXY: ConnType = \"Proxy\"\n Case dwFlags And CONNECT_OFFLINE: ConnType = \"Offline\"\n Case dwFlags And CONNECT_CONFIGURED: ConnType = \"Configured\"\n Case dwFlags And CONNECT_RAS: ConnType = \"Remote\"\n End Select\n IsWebConnected = WebTest\n End Function\n</code></pre>\n\n<p><strong>in your event :</strong></p>\n\n<pre><code>If checknet = False Then\n\n...\n\nelse\n\n...\n\nend if\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27689/" ]
I am testing an application that checks if a file exists across a network. In my testing, I am purposefully pulling the network plug so the file will not be found. The problem is this causes my app to go unresponsive for at least 15 seconds. I have used both the FileExists() and GetAttr() functions in VB6. Does anyone know how to fix this problem? (No, I can't stop using VB6) Thanks, Charlie
Unfortunately, VB doesn't make this easy, but luckily the Win32 API does, and it's quite simple to call Win32 functions from within VB. For the LAN/WAN, you can use a combination of the following Win32 API calls to tell you whether the remote connection exists without having to deal with a network time-out: ``` Private Declare Function WNetGetConnection Lib "mpr.dll" Alias _ "WNetGetConnectionA" (ByVal lpszLocalName As String, _ ByVal lpszRemoteName As String, ByRef cbRemoteName As Long) As Long Private Declare Function PathIsNetworkPath Lib "shlwapi.dll" Alias _ "PathIsNetworkPathA" (ByVal pszPath As String) As Long Private Declare Function PathIsUNC Lib "shlwapi.dll" Alias "PathIsUNCA" _ (ByVal pszPath As String) As Long ``` For the Internet, you can use the Win32 API call: ``` Private Declare Function InternetGetConnectedState Lib "wininet.dll" _ (ByRef lpdwFlags As Long, ByVal dwReserved As Long) As Long Const INTERNET_CONNECTION_MODEM = 1 Const INTERNET_CONNECTION_LAN = 2 Const INTERNET_CONNECTION_PROXY = 4 Const INTERNET_CONNECTION_MODEM_BUSY = 8 ``` This VB site has more discussion on [path oriented functions you can call in the Win32 API through VB.](http://vbnet.mvps.org/index.html?code/fileapi/pathisnetworkpath.htm)
202,685
<p>I truly love VIM - it's one of only a handful of applications I've every come across that make you feel warm and fuzzy inside. However, for PHP development, I still use PDT Eclipse although I would love to switch. </p> <p>The reason I can't quite at the moment is the CTRL+SPACE code-assist functionality that I rely on so much - it's so useful, especially when type hinting, or using PHPDoc variable comment blocks. </p> <p>I know there are cool plugins for VIM out there that can probably replicate this functionality and then some - but what are they? </p>
[ { "answer_id": 202725, "author": "user27987", "author_id": 27987, "author_profile": "https://Stackoverflow.com/users/27987", "pm_score": 0, "selected": false, "text": "<p>Code assist it's a new feature of VIM 7\n[Ctrl+x] [Ctrl+o] will auto complete your code or open a popup of options</p>\n\n<p>More features of VIM 7 can be found in this <a href=\"http://linuxhelp.blogspot.com/2006/09/visual-walk-through-of-couple-of-new.html\" rel=\"nofollow noreferrer\">blogpost</a></p>\n\n<p>Btw, I too like vim, but the PDT (and other IDEs) has much more features than code assist that make me preffer them over it.</p>\n" }, { "answer_id": 202726, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": true, "text": "<p>Vim has <a href=\"http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion\" rel=\"nofollow noreferrer\">OmniCompletion</a> built in, you should add this to your .vimrc:</p>\n\n<pre><code>filetype plugin on\nau FileType php set omnifunc=phpcomplete#CompletePHP\n</code></pre>\n\n<p>In addition I recommend you this plugins:</p>\n\n<ul>\n<li><a href=\"http://www.vim.org/scripts/script.php?script_id=184\" rel=\"nofollow noreferrer\">VTreeExplorer</a></li>\n<li><a href=\"http://www.vim.org/scripts/script.php?script_id=1318\" rel=\"nofollow noreferrer\">snippetsEmu</a></li>\n</ul>\n\n<p>and also take a look to this <a href=\"http://tech.blog.box.net/2007/06/20/how-to-debug-php-with-vim-and-xdebug-on-linux/\" rel=\"nofollow noreferrer\">article</a> about php debugging in Vim, and this <a href=\"http://www.scribd.com/doc/263139/VIM-for-PHP-Programmers\" rel=\"nofollow noreferrer\">paper</a>, it has many useful tips for using Vim in PHP Development. </p>\n" }, { "answer_id": 205988, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 0, "selected": false, "text": "<p>Look at <a href=\"http://www.vim.org/scripts/script.php?script_id=1643\" rel=\"nofollow noreferrer\">SuperTab</a> for making tab-autocompletion in Vim a bit easier to use than the standard bindings. You may also want to look into ctags, if you're into code indexing. <a href=\"http://www.google.com/search?q=vim+ctags+php\" rel=\"nofollow noreferrer\">Google \"php vim ctags\"</a> and you'll see plenty of articles describing how to set it up.</p>\n\n<p>The official Vim Wiki has a <a href=\"http://www.vim.org/scripts/script.php?script_id=1643\" rel=\"nofollow noreferrer\">PHP section</a> with some good tips, like integrating the official PHP documentation.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25517/" ]
I truly love VIM - it's one of only a handful of applications I've every come across that make you feel warm and fuzzy inside. However, for PHP development, I still use PDT Eclipse although I would love to switch. The reason I can't quite at the moment is the CTRL+SPACE code-assist functionality that I rely on so much - it's so useful, especially when type hinting, or using PHPDoc variable comment blocks. I know there are cool plugins for VIM out there that can probably replicate this functionality and then some - but what are they?
Vim has [OmniCompletion](http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion) built in, you should add this to your .vimrc: ``` filetype plugin on au FileType php set omnifunc=phpcomplete#CompletePHP ``` In addition I recommend you this plugins: * [VTreeExplorer](http://www.vim.org/scripts/script.php?script_id=184) * [snippetsEmu](http://www.vim.org/scripts/script.php?script_id=1318) and also take a look to this [article](http://tech.blog.box.net/2007/06/20/how-to-debug-php-with-vim-and-xdebug-on-linux/) about php debugging in Vim, and this [paper](http://www.scribd.com/doc/263139/VIM-for-PHP-Programmers), it has many useful tips for using Vim in PHP Development.
202,699
<p>What is the best way to create a clone of a DTO? There is not an ICloneable interface or a BinaryFormatter class in Silverlight. Is reflection the only way?</p>
[ { "answer_id": 216976, "author": "Craig Nicholson", "author_id": 28305, "author_profile": "https://Stackoverflow.com/users/28305", "pm_score": 0, "selected": false, "text": "<p>I believe the standard cloning functionality was left out to keep it simple and lightweight. I believe you could use either JSON or XML serialization to achieve the same thing though. Not sure about the performance costs though. </p>\n" }, { "answer_id": 2195954, "author": "Mike Schall", "author_id": 4231, "author_profile": "https://Stackoverflow.com/users/4231", "pm_score": 4, "selected": true, "text": "<p>Here is the code we came up with for cloning. This works in Silverlight 2 &amp; 3.</p>\n\n<pre><code>Public Shared Function Clone(Of T)(ByVal source As T) As T\n Dim serializer As New DataContractSerializer(GetType(T))\n Using ms As New MemoryStream\n serializer.WriteObject(ms, source)\n ms.Seek(0, SeekOrigin.Begin)\n Return DirectCast(serializer.ReadObject(ms), T)\n End Using\nEnd Function\n</code></pre>\n" }, { "answer_id": 7751623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>How to create clone if my source is IEnumerable. This LayerDto also has some object type(eg MetaItemDto).</p>\n\n<p>Code :</p>\n\n<p>public class LayerDto\n{\n}<br>\npublic class MetaItemDtoList : System.Collections.ObjectModel.ObservableCollection\n{\n}</p>\n\n<p>public static IEnumerable Clone(IEnumerable source)</p>\n\n<p>{</p>\n\n<pre><code> IEnumerable&lt;LayerDto&gt; layers;\n\n DataContractSerializer serializer = new DataContractSerializer(typeof(IEnumerable&lt;LayerDto&gt;));\n using (MemoryStream ms = new MemoryStream())\n {\n serializer.WriteObject(ms, source);\n ms.Seek(0, SeekOrigin.Begin);\n //return (IEnumerable&lt;LayerDto&gt;)serializer.ReadObject(ms);\n layers = (IEnumerable&lt;LayerDto&gt;)serializer.ReadObject(ms);\n return layers;\n }\n</code></pre>\n\n<p>}</p>\n\n<p>but what is problem I am facing is that layer doesn't show it's metaItems(for every layer).</p>\n" }, { "answer_id": 7751814, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>ICloneable is not available in Silverlight 4(I don't know about 1/2/3 or upcoming version) . It is removed from Silverlight 4's public APIs.\nHelp from Mike Schall code; it is working for me.</p>\n\n<pre><code>public LayerDto Clone(LayerDto source)\n {\n\n DataContractSerializer serializer = new DataContractSerializer(typeof(LayerDto));\n using (MemoryStream ms = new MemoryStream())\n {\n serializer.WriteObject(ms, source);\n ms.Seek(0, SeekOrigin.Begin);\n return (LayerDto)serializer.ReadObject(ms);\n }\n }\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4231/" ]
What is the best way to create a clone of a DTO? There is not an ICloneable interface or a BinaryFormatter class in Silverlight. Is reflection the only way?
Here is the code we came up with for cloning. This works in Silverlight 2 & 3. ``` Public Shared Function Clone(Of T)(ByVal source As T) As T Dim serializer As New DataContractSerializer(GetType(T)) Using ms As New MemoryStream serializer.WriteObject(ms, source) ms.Seek(0, SeekOrigin.Begin) Return DirectCast(serializer.ReadObject(ms), T) End Using End Function ```
202,718
<p>Is there a good method for writing C / C++ function headers with default parameters that are function calls? </p> <p>I have some header with the function:</p> <pre><code>int foo(int x, int y = 0); </code></pre> <p>I am working in a large code base where many functions call this function and depend on this default value. This default value now needs to change to something dynamic and I am looking for a way to do:</p> <pre><code>int foo(int x, int y = bar()); </code></pre> <p>Where bar() is some function that generates the default value based on some system parameters. Alternatively this function prototype would look like:</p> <pre><code>int foo(int x, int y = baz.bar()); </code></pre> <p>Where baz is a function belonging to an object that has not been instantiated within the header file.</p>
[ { "answer_id": 202734, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 3, "selected": false, "text": "<p>Yes. What you've written works.</p>\n" }, { "answer_id": 202738, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 4, "selected": true, "text": "<p>Go figure! It does work. <a href=\"http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr237.htm\" rel=\"noreferrer\">Default arguments in C++ functions</a></p>\n" }, { "answer_id": 202741, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 1, "selected": false, "text": "<p>It should be perfectly valid to call a global function or reference a global object in this context, as long as the declaration of the function/object is in scope. It may or may not be advisable (in terms of good design), but it should work.</p>\n" }, { "answer_id": 202758, "author": "Tim Sharrock", "author_id": 12840, "author_profile": "https://Stackoverflow.com/users/12840", "pm_score": 3, "selected": false, "text": "<p>I would use two overloaded functions:</p>\n\n<p><code>int foo(int x, int y);</code></p>\n\n<p><code>int foo(int x){return foo(x,bar);}</code></p>\n\n<p>If you allow the forwarding function to be inlined, then the performance penalty is likely to small to zero. If you keep the body of it out of line in a non-header file there may be a performance cost (likely to be small), but much more flexibility in implementation and reduced coupling.</p>\n" }, { "answer_id": 202759, "author": "user21714", "author_id": 21714, "author_profile": "https://Stackoverflow.com/users/21714", "pm_score": 3, "selected": false, "text": "<p>What's wrong with simply removing the optional parameter in the first declaration and providing a single parameter overload? </p>\n\n<pre><code>int foo(int x)\n{\n Bar bar = //whatever initialization\n return foo(x,bar.baz());\n}\n\nint foo(int x,int y)\n{\n //whatever the implementation is right now\n}\n</code></pre>\n\n<p>I think this tends to be much cleaner and more flexible than trying to use some dynamic default value.</p>\n" }, { "answer_id": 202768, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try making bar() a static member function. This will allow any part of the program which has such a static class in scope to access it. For example:</p>\n\n<p>class Foo\n{\npublic:</p>\n\n<p>static int bar();\n};</p>\n\n<p>Then you would declare:</p>\n\n<p>int foo(int x, int y = Foo::bar());</p>\n\n<p>If you need different objects then pass in the instance of the object instead. </p>\n" }, { "answer_id": 202935, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 2, "selected": false, "text": "<p>Tangential, but that looks to me like it'd introduce dependence issues down the road. I'd go with stbuton.myopenid.com's approach.</p>\n" }, { "answer_id": 203249, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 2, "selected": false, "text": "<p>In the standard, section 8.3.6 (Default arguments), paragraph 5, they give an example using just this approach. Specifically, it calls out that default arguments are <em>expressions</em>, so a function call applies, albeit with restrictions such as name lookup and type compatibility.</p>\n\n<p>In my workplace, we've used signatures like this:</p>\n\n<pre><code>void An_object::An_object(\n const Foo &amp;a,\n const Bar &amp;b,\n const Strategem &amp;s = Default_strategem()\n);\n</code></pre>\n\n<p>to allow clients to override a behavior in a class constructor. It came in handy for conditional behavior which affected performance of a translator...</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3022/" ]
Is there a good method for writing C / C++ function headers with default parameters that are function calls? I have some header with the function: ``` int foo(int x, int y = 0); ``` I am working in a large code base where many functions call this function and depend on this default value. This default value now needs to change to something dynamic and I am looking for a way to do: ``` int foo(int x, int y = bar()); ``` Where bar() is some function that generates the default value based on some system parameters. Alternatively this function prototype would look like: ``` int foo(int x, int y = baz.bar()); ``` Where baz is a function belonging to an object that has not been instantiated within the header file.
Go figure! It does work. [Default arguments in C++ functions](http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr237.htm)
202,723
<p>This is something I've always wondered, and I can't find any mention of it anywhere online. When a shop from, say Japan, writes code, would I be able to read it in English? Or do languages, like C, PHP, anything, have Japanese translations that they write?</p> <p>I guess what I'm asking is does every single coder in the world know enough English to use the exact same reserved words I do?</p> <p>Would this code:</p> <pre><code>If (i &lt; size){ switch case 1: print "hi there" default: print "no, thank you" } else { print "yes, thank you" } </code></pre> <p>display the exact same as I'm seeing it right now in English, or would some other non-English-speaking person see the words "if", "switch", "case", "default", "print", and "else" in their native language?</p> <p>EDIT - yes, this is serious. I didn't know if different localizations of a language have different keywords. or if there are even different localizations at all.</p>
[ { "answer_id": 202742, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "<p>i've seen VBA translated into spanish-like commands. it's one of the ugliest things ever seen. i would be ashamed to have something like this on my computer.</p>\n\n<p>PD: i happen to think that spanish is a much nicer language than english; but translating is WRONG</p>\n" }, { "answer_id": 202744, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": "<p>The programming language defines keywords and standard class names, and it's best practice to give user defined types, variables and functions also English names (as a non-native speaker I can tell ;-).</p>\n\n<p>So yes, if all is well, you'll be able to read the code.</p>\n\n<p>However languages like Java and Perl allow the full Unicode set for identifiers, so if somebody writes his class names in Kanji, you'll likely have a problem.</p>\n\n<p>Update: For Perl there's a <a href=\"http://search.cpan.org/perldoc?Lingua::Romana::Perligata\" rel=\"nofollow noreferrer\">joke module</a> that allows you to write Perl in Latin. But it's really just that, a joke. Nobody uses things like this seriously.</p>\n\n<p>Second Update: The idea of localized programming languages isn't that ridiculous. Excel's macro language is localized, but luckily it's stored in one canonical language (English) in the file, so the localization is just a layer on top of the normal thing. Such things only make sense for small \"programs\", for \"real\" programs it becomes hard to maintain.</p>\n" }, { "answer_id": 202749, "author": "Mike Hordecki", "author_id": 19082, "author_profile": "https://Stackoverflow.com/users/19082", "pm_score": 1, "selected": false, "text": "<p>It would be pointless, IMHO, to i18n a language <em>syntax</em>. It would just kill any sort of portability.</p>\n\n<p>The only exception are educational languages, such as LOGO. They were designed for ease learning, so portability is not an issue.</p>\n" }, { "answer_id": 202757, "author": "Francis Beaudet", "author_id": 14604, "author_profile": "https://Stackoverflow.com/users/14604", "pm_score": 2, "selected": false, "text": "<p>Well, As others pointed-out, the keywords and system calls would likely remain in English. </p>\n\n<p>However, understanding the keywords of the language is only a small part in understanding the code. Variable names, function names and comments all risk being in the native language of the author.</p>\n\n<p><strong>Edit</strong>: I just flashed-back to my youth where I went in the mapping tables of my TRS-80 built-in BASIC to switch the keywords to French. I could change all the keywords but I couldn't make any of them larger. Made for funny programs. </p>\n" }, { "answer_id": 202841, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 5, "selected": false, "text": "<p>In the Java language some methods must be named (at least partially) using the English language because of the JavaBeans convention.</p>\n\n<p>This convention requires that a property X be established via a pair of getX() and setX() methods. Here in French-Canada, where some developers are obliged to code in the French language this leads to the following travesty:</p>\n\n<pre><code>interface Foo {\n\n Color getCouleur();\n\n void setCouleur(Color couleur);\n}\n</code></pre>\n" }, { "answer_id": 202851, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 8, "selected": true, "text": "<p>If I understood well the question actually is: &quot;does every single coder in the world know enough English to use the exact same reserved words as I do?&quot;</p>\n<p>Well.. English is not the subject here but programming language reserved words. I mean, when I started about 10 yrs ago, I didn't have any clue of English, and still I was able to program simple things by learning the programming language, even when I did not know what they meant ( in English ). As a matter of fact this helped me to learn English.</p>\n<p>For example. I know to do an &quot;iteración&quot; ( iteration of course ) I had to write:</p>\n<pre><code> for( i = 0 ; i &lt; 100 ; i++ ) {}\n</code></pre>\n<p>To me, the &quot;for&quot;, the &quot;;&quot; and the &quot;++&quot; were simple foreign words or symbols. Later I learned that &quot;for&quot; meant &quot;para&quot;, &quot;while&quot; meant &quot;mientras&quot;, etc. But, in the meantime, I did not need to know English, what I needed was to know was &quot;C&quot;.</p>\n<p>Of course when I needed to learn more things, I had to learn English, for the documentation is written in that language.</p>\n<p>So the answer is: No, I don't see if, while, for etc. in my native language. I see them in English, but they didn't mean to me any other thing that they meant for the programming language in turn.</p>\n<p>Is like switch statement in bash: case .. esac. What Is &quot;esac&quot;... for me the end of the switch statement in bash.</p>\n<p>I guess that's what we call &quot;abstraction&quot;</p>\n" }, { "answer_id": 202870, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>Don't make fun of this. Some years ago, Microsoft had announced G# (German Sharp) - C# with German keywords and API. Of course, it was an April Fools joke, but the entire site about that looked so real and professional (and was on microsoft.com). Scary.</p>\n\n<p>At work, we use two field bus systems, both developed in German-speaking countries, which have a scary mix of German and English for identifiers, including some lovely false friends. It's a mess.</p>\n\n<p>No, English keywords and identifiers are fine. Though some might argue if it should be Color or Colour :)</p>\n" }, { "answer_id": 202928, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 1, "selected": false, "text": "<p>I read a lot of code, but the problem always is at variable/method names and comments, if they are commenting their code on their own language, using a language special characters like Japanese or Cyrillic, we are in trouble! but the keywords I think they will stay in English as they are.</p>\n" }, { "answer_id": 202932, "author": "rshimoda", "author_id": 23297, "author_profile": "https://Stackoverflow.com/users/23297", "pm_score": 2, "selected": false, "text": "<p>In several VBA project I've worked on (yes, very early in my career) we had to detect the version of office which was installed on the user's machine and change the formulas used in the speradsheets accordingly.</p>\n\n<p>As i program in portuguese\"SUM\" would have to be translated into \"SOMA\" and so on and so forth. I just can't imagine the necessary work to make this happen in several languages. Has anyone else suffered with this problem?</p>\n" }, { "answer_id": 203527, "author": "Juan Pablo Califano", "author_id": 24170, "author_profile": "https://Stackoverflow.com/users/24170", "pm_score": 4, "selected": false, "text": "<p>As many people already pointed out, in most programming languages you just have to learn a few keywords, so it doesn't matter that much if they're in English (or a language other than yours, for that matter). It's just a symbol you associate with some construct. For instance, in VB you have \"THEN\", which in many C-style languages would be \"{\" and it doesn't make a big difference in readability (well, at least that's how I see it, being a Non-English native speaker).</p>\n\n<p>But where things can sometimes get hairy, and where the choice of (natural) language matters is in naming identifiers. If the names of variables, functions, classes, etc, don't have a meaningful name for you because of a language barrier, following even the simplest code can be rather challenging.</p>\n\n<p>I remember someone once gave me a short snippet of Actionscript taken from some blog. The names were in German and since I don't speak a word of that language, stuff could have been called var_123, var_562 or func_333 as well (and probably it would have been easier for me to remember the names or at least to have a chance of spelling them right without copying and pasting). Since this was a short, self-contained snippet, I used an online translator to give those vars and functions meaningful names in my native language (Spanish) and after that, everything was clear. The point is that the code was actually simple, but I was only able to make sense out of it without too much (unnecessary) extra effort just when I overcame the language barrier.</p>\n\n<p>Since then, I've switched to using English for naming identifiers. Whether you like it or not, it's the \"koine\" for programming, engineering and generally technical stuff. Most of the APIs are written in English and so is most documentation (and probably the best resources you can find are in English as well). As a nice aside, it keeps your code more coherent with the code you're likely to be interacting with, and I think it tends to be more compact and succinct than other languages like Spanish (which otherwise would be my natural choice).</p>\n\n<p>Of course, if you can't understand at least some English, the problem remains the same, so it's not a perfect solution. But, given a number of developers from many different countries, chances are that the common language for them to communicate (through code and of course other means) will be English. So, choosing English is perhaps the best option, even though it would be not the perfect solution to this problem.</p>\n" }, { "answer_id": 203564, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 2, "selected": false, "text": "<p>AppleScript was once available in French and Japanese dialects. I do not know why it was withdrawn. </p>\n" }, { "answer_id": 203602, "author": "Uri", "author_id": 23072, "author_profile": "https://Stackoverflow.com/users/23072", "pm_score": 2, "selected": false, "text": "<p>Generally speaking, most programmers adapt to the English form. \nI learned to program when I was 7 years old and only spoke Hebrew (which is right to left) and with no english, which made it quite a fascinating experience.</p>\n\n<p>The problem you would usually get is with documentation, variables, and function names. I have seen my share of variables in other languages using english alphabet.</p>\n\n<p>The only language I'm familiar with that actually got translated was good old Logo (still amazing to this day). </p>\n" }, { "answer_id": 283947, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 3, "selected": false, "text": "<p>Actually there <em>are</em> some <a href=\"http://en.wikipedia.org/wiki/Non-English-based_programming_languages\" rel=\"noreferrer\">Non-English-based programming languages</a> (Wikipedia)</p>\n\n<p>I'm Norwegian but I've allways used English for all code except output (ignoring some silly code from school). Actually I usually write everything in English and then <em>translate</em> it to my native language, using gettext (or something).</p>\n" }, { "answer_id": 286357, "author": "Luke Halliwell", "author_id": 3974, "author_profile": "https://Stackoverflow.com/users/3974", "pm_score": 2, "selected": false, "text": "<p>When I was a kid we went to France, and in a museum we went to, I remember finding a display which showed you how to write computer programmes. The language was some kind of BASIC variant and I distinctly remember it using POUR instead of FOR, and so on. I was 7 years old and had only just learned BASIC, and it seemed completely natural to me that the French would have their own dialect like this!!</p>\n\n<p>I guess it may have been <a href=\"http://en.wikipedia.org/wiki/LSE_(programming_language)\" rel=\"nofollow noreferrer\">LSE</a> that I saw?</p>\n" }, { "answer_id": 288226, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 0, "selected": false, "text": "<p>I think WordBasic was localized. WordBasic was used to write macro's for in Word before VBA was used.</p>\n\n<p>If I remember it correctly, only WordBasic written in the English version would execute on all localized version. If you would write a Dutch version, you could only execute it on a Dutch Word.</p>\n" }, { "answer_id": 288320, "author": "Dinah", "author_id": 356, "author_profile": "https://Stackoverflow.com/users/356", "pm_score": 2, "selected": false, "text": "<p>Taking this to the next level, what about being able to substitute symbols?</p>\n\n<p>After seeing languages like <a href=\"http://en.wikipedia.org/wiki/Brainfuck\" rel=\"nofollow noreferrer\">Brainf**k</a> and <a href=\"http://compsoc.dur.ac.uk/whitespace/\" rel=\"nofollow noreferrer\">Whitespace</a> I thought of making a language like this: it'd be identical to C except you use closing braces to open, opening braces to close, swap the meanings of + and -, * and /, ; and :, > and &lt;, etc.</p>\n\n<p>The concept is nothing more than a gimmicky altered C compiler. But, like thinking of keywords differently, it challenges you to rethink some basic assumptions if you've never thought of such things before. Ex:</p>\n\n<pre><code>int foo)int i, char c( }\n int six = 2 / 3:\n int two = six + 4:\n if )i &gt; 0( }\n printf)\"i is negative\"(:\n {\n{\n</code></pre>\n" }, { "answer_id": 290327, "author": "Tom Future", "author_id": 3691, "author_profile": "https://Stackoverflow.com/users/3691", "pm_score": 2, "selected": false, "text": "<p>Filemaker's scripting language is localized. The scripts (and data!) are stored in a terrible \"sorta canonical\" form.</p>\n\n<p>So if you write a script in the American version, then open it up in the French version, all the keywords and built-in function names will be in French. But why won't it run?! Aha! The French version uses \",\" as the decimal point, and therefore to avoid ambiguity uses \";\" to separate function arguments -- where the American version uses \".\" and \",\" respectively. This conversion you have to do yourself.</p>\n\n<p>So you work through the incredibly bad script editing interface (you can't write scripts as text files) to fix all these things. It runs! Great! The results are all wrong! Oh no! Aha! The Jan-7-2004 date you entered in the American version is being interpreted as July-1-2004 -- apparently dates are not only displayed but <em>stored</em> in locale-dependent order. <em>Am I kidding you</em>? No.</p>\n\n<p>[Note: Filemaker 8 and 9 may be sane -- I only ever worked with 3 - 7.]</p>\n" }, { "answer_id": 290462, "author": "Lara Dougan", "author_id": 4081, "author_profile": "https://Stackoverflow.com/users/4081", "pm_score": 5, "selected": false, "text": "<p>I really have not thought too much about programming in Japanese before, but here we go, using the question's code sample.</p>\n\n<p>Using only the language statements in Japanese with the variables in English:</p>\n\n<pre><code>// In Japanese, it makes more sense to put the keywords/modifiers as\n// postfix expressions rather than prefix expressions.\n(i &lt; size)か {\n (l[i])は {\n 1だ:\n 「もしもし。」を書く;\n 省略時値:\n 「いいえ、いいですよ。」を書く;\n }\n} ない {\n 「はい、ありがとうございます。」を書く;\n}\n</code></pre>\n" }, { "answer_id": 293063, "author": "jes5199", "author_id": 13195, "author_profile": "https://Stackoverflow.com/users/13195", "pm_score": 5, "selected": false, "text": "<p>I'm having trouble finding references, but I'm reminded of three stories.</p>\n\n<p>A Lisp hacker defends meaningless functions like \"cdr\" and \"car\" by comparing them to programming in your non-native language:\n<a href=\"http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg01171.html\" rel=\"noreferrer\">http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg01171.html</a></p>\n\n<p>When Yukihiro Matsumoto (\"Matz\") started developing Ruby, he used english keywords <i>even though he was writing all the documentation in Japanese!</i>. There was no English documentation for Ruby for a couple years, and very few Americans using the language. But now it's a world-class language, and it the fact that it was born in Japan is only of historical interest. If the language had been using keywords in hiragana, it would have had a much more difficult time gaining popularity.</p>\n\n<p>I read an essay once -- maybe someone else can find it, Google is no help today -- that suggested that translating keywords was misguided because the words aren't actually English-- they're jargon. Not only do (to use the examples above) <i>para</i> and <i>pour</i> not quite have the exact meaning that <i>for</i> has in English, to non-programmers the phrase \"for loop\" is jibberish. Even Americans have to learn a new meaning. So to translate the words's superficial meaning into another language is more like making a cross-language pun rather than actually being helpful.</p>\n" }, { "answer_id": 295103, "author": "Patrick J Collins", "author_id": 38180, "author_profile": "https://Stackoverflow.com/users/38180", "pm_score": 2, "selected": false, "text": "<p>I'm in a French team developing a software system in C#. Despite the fact that the programming language keywords are ostensibly English, I imagine that you would have great difficulty reading the code as all the function names, variables, code comments, database tables and columns, technical specifications, protocols and so on, are all in French, including those lovely accented characters ç, é, è, ù, etc. I'm not even certain if the system would even run elsewhere due to localisation bugs, such as relying on the comma to be the default decimal seperator.</p>\n\n<p>Otherwise, WinDev is a popular programming platform in France, and its programming language WLanguage has keywords in either French or English, see and example here : <a href=\"http://fr.wikipedia.org/wiki/WLangage#Bilingue\" rel=\"nofollow noreferrer\">link text</a></p>\n" }, { "answer_id": 304273, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": false, "text": "<p>Your question is an interesting one with regard to Perl because it's syntax is designed to follow (English) natural language. I wonder if that makes it more difficult for non-English speakers...</p>\n\n<p>Of course, Perl and Perlers refuse to play by conventional rules. Mad scientist Damian Conway wrote the <a href=\"http://search.cpan.org/perldoc?Lingua::Romana::Perligata\" rel=\"nofollow noreferrer\">Lingua::Romana::Perligata</a> module which uses the black magic of source filters to allow you to write Perl in latin!</p>\n" }, { "answer_id": 322759, "author": "Dean Rather", "author_id": 14966, "author_profile": "https://Stackoverflow.com/users/14966", "pm_score": 2, "selected": false, "text": "<p>Here in Australia we still need to spell <b>colour</b> like <b>color</b>.\nHowever, I do find it annoying when other (Australian) developers, working on an Australian project, decide that internal variable names need to be spelt the american way. </p>\n" }, { "answer_id": 323964, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I am British and a problem we often run into is the American/British spelling clash. This often occurs with programming related terms such as Initialise() or Initialize(), Analyse() or Analyze() etc. This can (has) lead to problems trying to overriding methods, and is sometimes difficult to spot.</p>\n\n<p>Since the framework (in our case C#) was designed by Americans, we found that it is best to be consistent and use American spellings. We even adopt Color.</p>\n\n<p>We have a mix of nationalities in our development teams and most non-British people tend towards American spellings naturally.</p>\n" }, { "answer_id": 1284297, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 2, "selected": false, "text": "<p>The only <em>language</em> I saw localized is Excel with its macros. If you try to sum a column using an Italian version of Office you have to write <code>SOMMA(A1:A10)</code> and not SUM. That's a shame.</p>\n\n<p>By the way, just because it's fun, here's how your code should look like with Italian keywords:</p>\n\n<pre><code>se (i &lt; size){\n commuta\n caso 1:\n stampa \"hi there\"\n normalmente:\n stampa \"no, thank you\"\n} altrimenti {\n stampa \"yes, thank you\"\n}\n</code></pre>\n" }, { "answer_id": 1284299, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 2, "selected": false, "text": "<p>There are some languages that have translated keywords. Excel formulas, for example. If you write some calculations in a spreadsheet, this will be in your language. </p>\n\n<p>Fortunately, this is not a general practice, and even non-English speakers like me thank God that there is a standard language for keywords :</p>\n\n<ul>\n<li>it's easier to share you work.</li>\n<li>it prevent documentation from becoming a bigger nightmare that it already is.</li>\n<li>English words and sentences are usually short and syntactically pragmatic. In literature, Latin languages are much more beautiful, but for technical stuff, English rocks.</li>\n</ul>\n\n<p>And where to stop ? Can you imagine a C in ancient Greek ?</p>\n\n<p>Keywords must stay in one language, and well, it started with English, let it stay that way. This could have been worst (Asian language ?). And so we have to write methods and comments in English. Ok, more work for us, but at least the international code base stay congruent.</p>\n\n<p>There is, however, one case where using native language method names and comments can be a good practice : in third world country. I'm going to Senegal in some months to manage a Django project. Senegal have a huge analphabetization rate, and therefor it's already great that they spead energy in improving they programming knowledge. French is the native language here, so it would be inefficient to force them to learn computing AND a new tongue at the same time.</p>\n\n<p>BTW, that would be your code with French keywords :</p>\n\n<pre><code>Si (i &lt; taille) {\n cas par cas :\n cas 1:\n afficher \"salut\"\n défaut:\n afficher \"non merci\"\n} sinon {\n afficher \"oui, merci\"\n}\n</code></pre>\n\n<p>Not that translating the keywords have nothing to do with translating the strings. Of course, we have \"hi, there\" translated in our language. European coders even tend to use I18N much more than American sot their service can reach a wider audience.</p>\n" }, { "answer_id": 1284323, "author": "Stefano Borini", "author_id": 78374, "author_profile": "https://Stackoverflow.com/users/78374", "pm_score": 1, "selected": false, "text": "<p>in Italian</p>\n\n<pre><code>se (i &lt; dimensione){\n scegli\n caso 1:\n stampa \"ciao\"\n mancante:\n stampa \"no, grazie\"\n} altrimenti {\n stampa \"sì, grazie\"\n}\n</code></pre>\n\n<p>To confirm the worries of some previous poster I've seen a Fortran code with a macro include to translate all the keywords from English to French. Allow me not to continue on this.</p>\n\n<p>I also had to work with a code simultaneously containing identifiers in Italian, German, English and French, not only because it was developed in many different places, but also because the main developer thought it was fun and helped him not to duplicate identifier names (of course, with a routine 2000 lines long....)</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50/" ]
This is something I've always wondered, and I can't find any mention of it anywhere online. When a shop from, say Japan, writes code, would I be able to read it in English? Or do languages, like C, PHP, anything, have Japanese translations that they write? I guess what I'm asking is does every single coder in the world know enough English to use the exact same reserved words I do? Would this code: ``` If (i < size){ switch case 1: print "hi there" default: print "no, thank you" } else { print "yes, thank you" } ``` display the exact same as I'm seeing it right now in English, or would some other non-English-speaking person see the words "if", "switch", "case", "default", "print", and "else" in their native language? EDIT - yes, this is serious. I didn't know if different localizations of a language have different keywords. or if there are even different localizations at all.
If I understood well the question actually is: "does every single coder in the world know enough English to use the exact same reserved words as I do?" Well.. English is not the subject here but programming language reserved words. I mean, when I started about 10 yrs ago, I didn't have any clue of English, and still I was able to program simple things by learning the programming language, even when I did not know what they meant ( in English ). As a matter of fact this helped me to learn English. For example. I know to do an "iteración" ( iteration of course ) I had to write: ``` for( i = 0 ; i < 100 ; i++ ) {} ``` To me, the "for", the ";" and the "++" were simple foreign words or symbols. Later I learned that "for" meant "para", "while" meant "mientras", etc. But, in the meantime, I did not need to know English, what I needed was to know was "C". Of course when I needed to learn more things, I had to learn English, for the documentation is written in that language. So the answer is: No, I don't see if, while, for etc. in my native language. I see them in English, but they didn't mean to me any other thing that they meant for the programming language in turn. Is like switch statement in bash: case .. esac. What Is "esac"... for me the end of the switch statement in bash. I guess that's what we call "abstraction"
202,740
<p>Can I set timeouts for JSP pages in tomcat either on a per page or server level?</p>
[ { "answer_id": 202795, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 3, "selected": true, "text": "<p>For server level, you can try this.<br>\nyou have to change <code>catalina.bat</code> / <code>catalina.sh</code> file<br></p>\n\n<pre><code>jvm OPTIONS : -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 \n</code></pre>\n" }, { "answer_id": 230399, "author": "Mojo", "author_id": 30462, "author_profile": "https://Stackoverflow.com/users/30462", "pm_score": 3, "selected": false, "text": "<p>In the Tomcat <em>server.xml</em> file, the Connector element also has a <code>connectionTimeout</code> attribute in milliseconds.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;Connector\n URIEncoding=\"UTF-8\"\n acceptCount=\"100\"\n connectionTimeout=\"20000\"\n disableUploadTimeout=\"true\"\n enableLookups=\"false\"\n maxHttpHeaderSize=\"8192\"\n maxSpareThreads=\"75\"\n maxThreads=\"150\"\n minSpareThreads=\"25\"\n port=\"7777\"\n redirectPort=\"8443\" /&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14481/" ]
Can I set timeouts for JSP pages in tomcat either on a per page or server level?
For server level, you can try this. you have to change `catalina.bat` / `catalina.sh` file ``` jvm OPTIONS : -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 ```
202,750
<p>I mean, is there a coded language with human style coding? For example:</p> <pre><code>Create an object called MyVar and initialize it to 10; Take MyVar and call MyMethod() with parameters. . . </code></pre> <p>I know it's not so useful, but it can be interesting to create such a grammar.</p>
[ { "answer_id": 202763, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 3, "selected": false, "text": "<p>Perl, some people claim.</p>\n\n<pre><code>print \"hello!\" and open my $File, '&lt;', $path or die \"Couldn't open the file after saying hello!\";\n</code></pre>\n" }, { "answer_id": 202766, "author": "Chris Serra", "author_id": 13435, "author_profile": "https://Stackoverflow.com/users/13435", "pm_score": 5, "selected": false, "text": "<p>AppleScript is pretty close to that, though that is obviously platform dependent.</p>\n\n<p>Here's a script for opening iTunes and playing a playlist</p>\n\n<pre><code>tell application \"iTunes\"\n activate\n play playlist \"Party Shuffle\"\nend tell\n</code></pre>\n\n<p>Source: <a href=\"http://sial.org/code/applescript/\" rel=\"noreferrer\">AppleScript Examples</a></p>\n" }, { "answer_id": 202771, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Cobol\" rel=\"noreferrer\">COBOL</a> is a lot like that.</p>\n\n<pre><code>SET MYVAR TO 10.\nEXECUTE MYMETHOD with 10, MYVAR.\n</code></pre>\n\n<p>Another sample from Wikipedia:</p>\n\n<pre><code>ADD YEARS TO AGE.\nMULTIPLY PRICE BY QUANTITY GIVING COST.\nSUBTRACT DISCOUNT FROM COST GIVING FINAL-COST.\n</code></pre>\n\n<p>Oddly enough though, despite its design to be readable as English, most programmers completely undermined this with bizarre naming conventions:</p>\n\n<pre><code>SET VAR_00_MYVAR_PIC99 TO 10.\nEXECUTE PROC_10_MYMETHOD with 10, VAR_00_MYVAR_PIC99.\n</code></pre>\n" }, { "answer_id": 202772, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://developer.apple.com/applescript/\" rel=\"nofollow noreferrer\">Applescript</a>:</p>\n\n<pre><code>tell application \"Finder\"\n set the percent_free to ¬\n (((the free space of the startup disk) / (the capacity of the startup disk)) * 100) div 1\nend tell\nif the percent_free is less than 10 then\n tell application (path to frontmost application as text)\n display dialog \"The startup disk has only \" &amp; the percent_free &amp; ¬\n \" percent of its capacity available.\" &amp; return &amp; return &amp; ¬\n \"Should this script continue?\" with icon 1\n end tell\nend if\n</code></pre>\n" }, { "answer_id": 202775, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": false, "text": "<p>VB is as close as I can think of one:</p>\n\n<p>If MyLife.Sucks Then MyLife.End Else MyLife.Continue</p>\n" }, { "answer_id": 202776, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 3, "selected": false, "text": "<p>Do a google search for \"natural language programming\" and you'll find lots of information (including why this is a bad idea).</p>\n" }, { "answer_id": 202779, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 0, "selected": false, "text": "<p>Visual Basic (and BASIC based languages in general) are about as close to human language as you get. I'd argue Python comes pretty close too. Using these you can makes your code read as structed english if you care enough, but no, there's no natural English compilers because there's just too much ambiguity there.</p>\n" }, { "answer_id": 202780, "author": "mike511", "author_id": 9593, "author_profile": "https://Stackoverflow.com/users/9593", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Cobol\" rel=\"nofollow noreferrer\">Cobol</a> was kind of like that.</p>\n" }, { "answer_id": 202787, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 3, "selected": false, "text": "<p>Yes. It's called <a href=\"http://www.csis.ul.ie/COBOL/examples/Accept/Multiplier.htm\" rel=\"noreferrer\">COBOL</a>, and people generally detest it.</p>\n" }, { "answer_id": 202797, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 0, "selected": false, "text": "<p>Basic was a first approach in that direction, and as has been shown in another reply, Perl also allows code that's fairly close to human language - if you ignore all that punctuation.</p>\n\n<p>I just read a very interesting <a href=\"http://www.csse.monash.edu.au/~damian/papers/HTML/Perligata.html\" rel=\"nofollow noreferrer\">article on how to translate Latin to Perl</a> (for which there's also a Perl module).</p>\n\n<p>So if the human language has enough structure, and you introduce enough restrictions to avoid ambiguousness, you can indeed program in (mostly) human language.</p>\n\n<p>But really nobody really does, because it's very verbose, and hard to make both readable and accurate.</p>\n" }, { "answer_id": 202799, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/COBOL\" rel=\"nofollow noreferrer\">COBOL</a> was intended to be read by managers, and has \"noise words\" to make it more readable.</p>\n\n<p>The funny thing is, it reads a bit like a verbose DSL.</p>\n" }, { "answer_id": 202800, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 7, "selected": false, "text": "<p>How about <a href=\"http://lolcode.com/home\" rel=\"noreferrer\">LOLCODE</a>?</p>\n\n<pre><code>HAI\nCAN HAS STDIO?\nVISIBLE \"HAI WORLD!\"\nKTHXBYE\n</code></pre>\n\n<p>Simplicity itself!</p>\n" }, { "answer_id": 202805, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": 0, "selected": false, "text": "<p>Why would you do that? It's machine-unfriendly to our R2D2 in the brain, which reads the code to us.</p>\n" }, { "answer_id": 202812, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 1, "selected": false, "text": "<p>IMHO, human readability is pretty subjective. However, if you want to learn more I would suggest exploring the following topics:</p>\n\n<ul>\n<li>Python - which uses prefers whitespace to 'special characters' (such as { &amp; } for syntax).</li>\n<li>Smalltalk - which allows arguments to be spread through the method name.</li>\n<li>Ruby</li>\n<li>Fluent APIs / Domain specific languages</li>\n</ul>\n" }, { "answer_id": 202818, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 4, "selected": false, "text": "<p>Having a programming language read like a (verbose) normal language, would be like requiring people to converse all the time in legalese. All the extra verbiage just gets in the way.</p>\n\n<p>An ideal programming language should have syntax that is as transparent as possible and let the concepts behind the program stand out. Obviously there is a trade off between having a quick learning curve and having minimal but obscure syntax (think Perl, or even K).</p>\n" }, { "answer_id": 202844, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 4, "selected": false, "text": "<p>By creating a set of rules, it is possible to do logic programming in <a href=\"http://en.wikipedia.org/wiki/Prolog\" rel=\"nofollow noreferrer\">Prolog</a> like this. You can build a grammar (or download one) for a particular domain, create a knowledge base and then query it. After defining your grammar you could do something like:</p>\n\n<pre><code>bob is a parent of tim.\nmary is a parent of bob.\n\n?- X is a grandparent of tim.\nX = mary\n\n?- jim is a parent of bob.\nfalse\n</code></pre>\n" }, { "answer_id": 202874, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 4, "selected": false, "text": "<p>All languages are 'human readable'. :) How else would someone be able to create it? That being said, languages that support DSLs can be incredibly intuitive such as <a href=\"http://boo.codehaus.org/\" rel=\"noreferrer\">Boo</a>.</p>\n" }, { "answer_id": 202916, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 5, "selected": false, "text": "<p>This was \"the next big thing\" around about the early 1980s and I spent much of my first couple of years as a a coder working in \"NATURAL\", which was the supposedly the best of the new crop of 4GLs (fourth generation languages) which were designed to make data access (in this case to an ADABAS database) human readable.</p>\n\n<p>Of course it did absolutely nothing of the type. All we ended up with was verbose badly structured code. Both of these products are still around, but you've never heard of them, which sort of proves the what a dead end it was.</p>\n\n<p>Actually at that period there appeared to be a general desire to move beyond 'programming' into some sort of 2001 inspired AI heaven. Oracle were really keen on code generation and I remember with some interest a product called 'the last one' that was being marketed to managers as a product that would automatically generate any program you wanted and make all your programming staff redundant. Seems not to have lived up to expectations ;-)</p>\n\n<p>It's worth remembering to that SQL was originally marketed in some quarters as a way to allow management to directly query their data. I was even sent on a course to learn basic SQL (in a large national transport organization that ran on rails - the steel variety) where junior management types were included because they had plans to put basic query tools in their hands. What a disaster that was.</p>\n\n<p>Maybe it might be different in 50 years, but at the current stage of play coding demands a certain clarity of thought and implementation which is best mediated through a dedicated syntax designed for those ends, not any approximation to a natural language which is unclear and ambiguous. The nearest approximation is possibly physics where the essence of the subject is in the mathematics used (think a programming language for physics) not verbose wordage. </p>\n\n<p><strong>ADDED</strong></p>\n\n<p>I was forgetting, apart from COBOL there was also PL/1, sometime credited with allowing NASA to put a man on the moon it was just as verbose as COBOL and tried even harder to be 'Manager-readable'. Which is why no-one has really heard of it now either :-)</p>\n" }, { "answer_id": 202927, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 3, "selected": false, "text": "<p>I can read C. That means it's human-readable(because I'm a human). It's just too terse for the average person. The general concept of programming languages is to maximize the information about how the computer should operate in a given line.</p>\n\n<p>This is why Ruby is so popular; it maximizes the functionality in minimal text. English(or any other other natural language) is a pretty imprecise, low-information/character language.</p>\n\n<p>In sum, it is: (i)done before and (ii)a known weaker idea. </p>\n" }, { "answer_id": 202945, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 3, "selected": false, "text": "<p>Clarity of Expression is important.</p>\n\n<p>But Clarity of Thought is far, far more important.</p>\n" }, { "answer_id": 202950, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://inform7.com/\" rel=\"noreferrer\"><strong>Inform 7</strong></a></p>\n\n<p>Inform 7 is perhaps the language I feel is most appropriately designed in a human language fashion. It is quite application specific for writing adventure games.</p>\n\n<p>It is based on rule-based semantics, where you write a lot of rules describing the relationship between objects and their location. For instance, the section below is an Inform 7 program:</p>\n\n<pre><code>\"Hello Deductible\" by \"I.F. Author\"\n\nThe story headline is \"An Interactive Example\".\n\nThe Living Room is a room. \"A comfortably furnished living room.\"\nThe Kitchen is north of the Living Room.\nThe Front Door is south of the Living Room.\nThe Front Door is a door. The Front Door is closed and locked.\n\nThe insurance salesman is a man in the Living Room. The description is \"An insurance salesman in a tacky polyester suit. He seems eager to speak to you.\" Understand \"man\" as the insurance salesman.\n\nA briefcase is carried by the insurance salesman. The description is \"A slightly worn, black briefcase.\" Understand \"case\" as the briefcase.\n\nThe insurance paperwork is in the briefcase. The description is \"Page after page of small legalese.\" Understand \"papers\" or \"documents\" or \"forms\" as the paperwork.\n\nInstead of listening to the insurance salesman: \n say \"The salesman bores you with a discussion of life insurance policies. From his briefcase he pulls some paperwork which he hands to you.\";\n move the insurance paperwork to the player.\n</code></pre>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Inform#Example_game_2\" rel=\"noreferrer\">Example cited from Wikipedia</a></p>\n" }, { "answer_id": 202972, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://inform7.com/\" rel=\"nofollow noreferrer\">Inform 7</a> is the most successful such system I've seen. It has two advantages over the cruder systems listed in other answers here: it's for a domain particularly appropriate for natural language (interactive fiction), and it does a fancier analysis of the input code based on more computational-linguistics lore, not just a conventional programming-language grammar that happens to use English words instead of braces, etc.</p>\n" }, { "answer_id": 202996, "author": "Rahul", "author_id": 16308, "author_profile": "https://Stackoverflow.com/users/16308", "pm_score": 1, "selected": false, "text": "<p>While not a programming language itself, the <a href=\"http://community.moertel.com/pxsl/\" rel=\"nofollow noreferrer\">parsimonious XML shorthand language (PXSL)</a> makes XSL a hell of a lot more human-readable (and less verbose!) than it arguably already is:</p>\n\n<pre><code> &lt;doc keywords=\"x y z\"&gt; doc -keywords=&lt;&lt;x y z&gt;&gt;\n &lt;title/&gt; title\n &lt;body id=\"db13\"&gt; body -id=db13\n This is text. &lt;&lt;This is text.&gt;&gt;\n &lt;/body&gt;\n&lt;/doc&gt;\n</code></pre>\n" }, { "answer_id": 203078, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 3, "selected": false, "text": "<p>This is actually a hot topic.</p>\n\n<p>For starters - What is Human readable?</p>\n\n<p>A Chinese-reader cannot read Russian and vice versa. \nIt you narrow your domain for example to Chinese pharmacists writing a perscription you could design a language around that. And that would be <em>human readable</em>.</p>\n\n<p>Such as language would fall under a the umbrella of <a href=\"http://en.wikipedia.org/wiki/Domain_Specific_Language\" rel=\"noreferrer\">Domain Specific Languages</a>.</p>\n" }, { "answer_id": 203282, "author": "Ken Liu", "author_id": 25688, "author_profile": "https://Stackoverflow.com/users/25688", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/HyperTalk\" rel=\"nofollow noreferrer\">HyperTalk</a> and its descendant <a href=\"http://en.wikipedia.org/wiki/AppleScript\" rel=\"nofollow noreferrer\">AppleScript</a> were designed to be similar to the English language.</p>\n" }, { "answer_id": 203326, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.dangermouse.net/esoteric/chef.html\" rel=\"noreferrer\">Chef</a>! Anyone can read recipes right? Behold <a href=\"http://www.dangermouse.net/esoteric/chef_hello.html\" rel=\"noreferrer\">hello world</a>!</p>\n\n<pre><code>Ingredients.\n72 g haricot beans\n101 eggs\n108 g lard\n111 cups oil\n32 zucchinis\n119 ml water\n114 g red salmon\n100 g dijon mustard\n33 potatoes\n\nMethod.\nPut potatoes into the mixing bowl. Put dijon mustard into the mixing bowl. \nPut lard into the mixing bowl. Put red salmon into the mixing bowl. Put oil into the mixing bowl. \nPut water into the mixing bowl. Put zucchinis into the mixing bowl. Put oil into the mixing bowl. \nPut lard into the mixing bowl. Put lard into the mixing bowl. Put eggs into the mixing bowl. \nPut haricot beans into the mixing bowl. Liquefy contents of the mixing bowl. \nPour contents of the mixing bowl into the baking dish.\n</code></pre>\n\n<p>Sorry if it's not a serious answer, but this is way awesome. :-)</p>\n" }, { "answer_id": 203560, "author": "Gregory Higley", "author_id": 27779, "author_profile": "https://Stackoverflow.com/users/27779", "pm_score": 2, "selected": false, "text": "<p>I agree with the general consensus here. \"Human readable\" <strong>general purpose</strong> programming languages are mostly a bad idea, but human readable Domain Specific Languages are very worthwhile.</p>\n\n<p>REBOL has a great system for creating DSLs.</p>\n" }, { "answer_id": 204773, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 4, "selected": false, "text": "<p>I see the <a href=\"http://en.wikipedia.org/wiki/Shakespeare_programming_language\" rel=\"noreferrer\">Shakespeare programming language</a> have yet to be mentioned.</p>\n\n<p>These programs are coded to look like shakespear plays, the individial characters in the play being variables that can hold numbers and the various phrases in the play manipulate the characters and the number they hold. For instance, \"Speak your mind\" orders a character to output his value.</p>\n" }, { "answer_id": 204809, "author": "Jeff Kotula", "author_id": 1382162, "author_profile": "https://Stackoverflow.com/users/1382162", "pm_score": 1, "selected": false, "text": "<p>I think the two constructs have very different purposes. Natural language has a very loose structure that is subject to interpretation and presumes the existence of a high-level inference engine to understand it -- and it is expected that it will be interpreted incorrectly a good portion of the time! Programming languages are meant to be precise, unambiguous specifications that leave little if anything open to interpretation.</p>\n\n<p>Given that you'd think that using natural language as a programming construct should be a simple matter of taming its variability and clarifying its meaning. But once you've done that you're left with the semantics of a programming language, regardless of how it is syntactically wrapped and packaged.</p>\n" }, { "answer_id": 205063, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 2, "selected": false, "text": "<p>Sure, Erlang.</p>\n\n<pre><code>-module(listsort).\n-export([by_length/1]).\n\n by_length(Lists) -&gt;\n F = fun(A,B) when is_list(A), is_list(B) -&gt;\n length(A) &lt; length(B)\n end,\n qsort(Lists, F).\n\n qsort([], _)-&gt; [];\n qsort([Pivot|Rest], Smaller) -&gt;\n qsort([ X || X &lt;- Rest, Smaller(X,Pivot)], Smaller)\n ++ [Pivot] ++\n qsort([ Y ||Y &lt;- Rest, not(Smaller(Y, Pivot))], Smaller).\n</code></pre>\n\n<p>I'm a human, it's a programming language, and I can read it. I don't know what any of it means, but I see a lot of English words in there, I think.</p>\n\n<p>(Tongue firmly in cheek.)</p>\n" }, { "answer_id": 287891, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 2, "selected": false, "text": "<p>DSLs can be very natural-looking. See <a href=\"http://www.codinginstinct.com/2008/11/creating-watin-dsl-using-mgrammar.html\" rel=\"nofollow noreferrer\">this example</a> created with <a href=\"http://msdn.microsoft.com/en-us/library/dd129869.aspx\" rel=\"nofollow noreferrer\">MGrammar</a>:</p>\n\n<pre><code>test \"Searching google for watin\"\n goto \"http://www.google.se\"\n type \"watin\" into \"q\"\n click \"btnG\"\n assert that text \"WatiN Home\" exists\n assert that element \"res\" exists\nend\n</code></pre>\n" }, { "answer_id": 287933, "author": "Marc", "author_id": 27947, "author_profile": "https://Stackoverflow.com/users/27947", "pm_score": 1, "selected": false, "text": "<p>That has to be whitespace. The only programming language where there's simply nothing to read: <a href=\"http://en.wikipedia.org/wiki/Whitespace_(programming_language)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Whitespace_(programming_language)</a></p>\n" }, { "answer_id": 287978, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 2, "selected": false, "text": "<p>Being more human-readable than most was one of the early selling points of Ada. I find it a silly argument these days, as any sufficently complex task in <em>any</em> language is going to require a competent practicioner to understand. However, it does beat the bejeezus out of C-syntax languages. Its dominant coding styles can enhance this effect too. For example, comparing loops in an if statement:\nAda:</p>\n\n<pre><code>if Time_To_Loop then\n for i in Some_Array loop\n Some_Array(i) := i;\n end loop;\nend if;\n</code></pre>\n\n<p>C:</p>\n\n<pre><code>if (timeToLoop != 0) {\n for (int i=0;i&lt;SOME_ARRAY_LENGTH;i++) {\n someArray[i] = i;\n }\n}\n</code></pre>\n\n<p>The C code would look even worse if I used Hungarian notation like Microsoft, but I'm trying to be nice. :-)</p>\n" }, { "answer_id": 407746, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>Projects promoting programming in\n \"natural language\" are intrinsically\n doomed to fail.</p>\n</blockquote>\n\n<p>-- Edsger W.Dijkstra, <a href=\"http://www.cs.virginia.edu/~evans/cs655/readings/ewd498.html\" rel=\"noreferrer\">How do we tell truths that might hurt?</a></p>\n" }, { "answer_id": 665599, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Funny. Imagine an analphabet asking \"Is there a human readable newspaper?\".</p>\n\n<p>Before you can read something you have to learn to read first.</p>\n" }, { "answer_id": 665651, "author": "Martin", "author_id": 770, "author_profile": "https://Stackoverflow.com/users/770", "pm_score": 3, "selected": false, "text": "<p>SQL</p>\n\n<pre><code>SELECT name, address FROM customers WHERE region = 'Europe'\n</code></pre>\n" }, { "answer_id": 694662, "author": "Arjan", "author_id": 84237, "author_profile": "https://Stackoverflow.com/users/84237", "pm_score": 0, "selected": false, "text": "<p>In the early days Microsoft actually translated <em>WordBasic</em> (since many years known as <em>Visual Basic for Applications</em>) to match the GUI language. Constructs like </p>\n\n<pre><code>If &lt;condition&gt; Then\n &lt;something&gt;\nEnd If\n</code></pre>\n\n<p>would, in the Dutch version of Word, be entered and displayed like</p>\n\n<pre><code>Als &lt;condition&gt; Dan\n &lt;something&gt;\nEinde Als\n</code></pre>\n\n<p>Of course, in theory this made it easier for people to understand recorded macros. But I doubt those people would ever take a look at the code to start with...</p>\n" }, { "answer_id": 694677, "author": "ewakened", "author_id": 38354, "author_profile": "https://Stackoverflow.com/users/38354", "pm_score": 0, "selected": false, "text": "<p>There are lots of great <strong>DSLs</strong> (Domain Specific Languages) that read very much like human language.</p>\n\n<p>A great example is Starbucks. You could write a DSL like this. This is using Ruby but could be done in many different languages. The advantages to Ruby or Python is that they are dynamic languages so you can use Duck Typing.</p>\n\n<pre>\n<code>\n\nventi = Starbucks.new(:kind => :coffee, :size => :venti)\nhalf_foam_venti = add_half_foam(venti)\nserve(half_foam_venti)\n\n</code>\n</pre>\n\n<p>But I have to agree that Ruby / Python might be the closest out of the box.</p>\n\n<p>Kent</p>\n" }, { "answer_id": 700993, "author": "peSHIr", "author_id": 50846, "author_profile": "https://Stackoverflow.com/users/50846", "pm_score": 1, "selected": false, "text": "<p>Haven't seen <a href=\"http://homepages.cwi.nl/~steven/abc/\" rel=\"nofollow noreferrer\" title=\"A Short Introduction to the ABC Language\">ABC</a> mentioned yet. Worked with that during first year computer science at Utrecht University and always thought that quite \"human readable\" (whatever that means exactly).</p>\n\n<p>Here is an example function words to collect the set of all words in a document:</p>\n\n<pre><code> HOW TO RETURN words document:\n PUT {} IN collection\n FOR line IN document:\n FOR word IN split line:\n IF word not.in collection:\n INSERT word IN collection\n RETURN collection\n</code></pre>\n" }, { "answer_id": 718979, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I says LOLcode for readablity:</p>\n\n<p>HAI</p>\n\n<p>I HAS A VAR ITZ \"Hai der Werld\", I HAS END </p>\n\n<p>VISIBLE VAR</p>\n\n<p>GIMMEH END</p>\n\n<p>KTHXBYE</p>\n\n<p>or</p>\n\n<p>HAI</p>\n\n<p>I HAS END</p>\n\n<p>VISIBLE \"Hai der Werld 2.0\"</p>\n\n<p>GIMMEH END</p>\n\n<p>KTHXBYE</p>\n\n<p>\"w/o gimmeh the thing would only stay up for a split second\"\ngo to lolcode.com for moar info</p>\n" }, { "answer_id": 1457822, "author": "James Anderson", "author_id": 38207, "author_profile": "https://Stackoverflow.com/users/38207", "pm_score": 0, "selected": false, "text": "<p>I used to be able to \"read\" OS/360 object code a talent born of many hours of 2 am dump analysis with the OPs manager pacing in the backgound. </p>\n\n<p>So I suppose OBJECT code counts as human readable.</p>\n\n<p>The main problem with 'natural language' code is they can be so ambiguous. English especially depends on cultural, contextual and 'mood's to interpret a sentance correctly.\nThis is why legal documents are written in a such wierd stilted language, its the only way to acheive any sort of precision with English.</p>\n\n<p>This was one of COBOLs big pitfalls.\nThe compilers interpretation of 'IF A NOT = B OR C ' was the exact opposite a a casual readers interprataion ie in C \"!(A == B) || A == C\" whereas you may think it should be !(A == B || A == C).</p>\n\n<p>The other big problem was puncutuation. Your brain \"preprocesses\" punctuation so you dont really \"see\" it a concious level. The period '.' was vital in early COBOL as they delimited blocks of code, but missing or extra periods were maddeningly difficult to spot. Its a bit like spotting an '=' vs. '==' in C except much much worse. </p>\n" }, { "answer_id": 1457834, "author": "iceangel89", "author_id": 119032, "author_profile": "https://Stackoverflow.com/users/119032", "pm_score": 0, "selected": false, "text": "<p>i think what you maybe referring to is Functional Programming? i think F# is 1. tho i seem to think its more complex to me as a developer</p>\n" }, { "answer_id": 1457850, "author": "Pascal Thivent", "author_id": 70604, "author_profile": "https://Stackoverflow.com/users/70604", "pm_score": 0, "selected": false, "text": "<p>You should read Martin Fowler's essay on <a href=\"http://www.martinfowler.com/bliki/BusinessReadableDSL.html\" rel=\"nofollow noreferrer\">Business-Readable DSLs</a>. </p>\n" }, { "answer_id": 1457904, "author": "NoahD", "author_id": 76836, "author_profile": "https://Stackoverflow.com/users/76836", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://www.perl.org\" rel=\"nofollow noreferrer\">PERL</a> ;-)</p>\n" }, { "answer_id": 1537028, "author": "DevTun", "author_id": 172519, "author_profile": "https://Stackoverflow.com/users/172519", "pm_score": 0, "selected": false, "text": "<p>Windev is very easy and human readable language.\n<a href=\"http://www.pcsoft.fr/windev/presentation.htm\" rel=\"nofollow noreferrer\">http://www.pcsoft.fr/windev/presentation.htm</a></p>\n" }, { "answer_id": 1564514, "author": "Sudhakar Kalmari", "author_id": 179367, "author_profile": "https://Stackoverflow.com/users/179367", "pm_score": 0, "selected": false, "text": "<p>Rebol Comes Close </p>\n" }, { "answer_id": 3286568, "author": "Rolf", "author_id": 396389, "author_profile": "https://Stackoverflow.com/users/396389", "pm_score": 0, "selected": false, "text": "<p>While I know COBOL (and closer to us... SQL) can suck, these were designed decades ago. I also think they took advantage of the hype about \"english\" programming languages, and I dont think they went very far in proper linguistic analysis. I think it is possible to program in ENGLISH nowadays (natural english...the language) if good programmers got together and analyzed the language and put it to work. It is a big project, but with the computing power we have it is possible, I am pretty sure.\nIn other words, I don't like how people discard the idea of english-like programming because of COBOL. Cobol was an early programming language, and its designers back then decided to take spoken english as a reference, because they didn't know any better, they had no ideas of the complication laying ahead, and they thought english made it look familiar, and maybe it also looked good on marketing material. I don't think they tried really hard to make the COBOL compiler read natural english. If a serious effort was made nowadays to learn from the past and complete a proper system of natural language recognition, then I think it can work - after some time (most probably a matter of years).\nAnd assuming that, wouldn't it be nice to be able to program in plain english? Of course, it would have to be self-learning (the computer has to learn stuff on the fly) and interactive (the computer must be able to ask the user to pick among choices when confused).</p>\n" }, { "answer_id": 3286632, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>GradStudent</p>\n\n<p>It only has one statement: <strong>\"you - write me a program to do x\"</strong><br>\nIt's valid for all values of X and has the advantage that x doesn't have to be defined and can be changed after the program is written.</p>\n\n<p>A commercial dialect is available called intern: development cost is lower but it isn't guaranteed to work</p>\n" }, { "answer_id": 3385837, "author": "Ken", "author_id": 283311, "author_profile": "https://Stackoverflow.com/users/283311", "pm_score": 1, "selected": false, "text": "<p>Have you looked at Python?</p>\n" }, { "answer_id": 3822713, "author": "OceanBlue", "author_id": 289918, "author_profile": "https://Stackoverflow.com/users/289918", "pm_score": 2, "selected": false, "text": "<p>Interesting question. Your question can be read as \"<em>Is there any programming language that is easily readable by humans</em>?\", OR ELSE as \"<em>Is there a human language that can be used for programming</em>?\". All the answers here have focused on the former, so let me try answering the latter.</p>\n\n<p>Have you heard of Sanskrit? It is an ancient Indian language on which modern Indian languages like Hindi are based.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Sanskrit\" rel=\"nofollow\">wiki/Sanskrit</a></p>\n\n<p>I've been hearing for years that it is precise and complete enough to be used, as it is, as a high-level language on a computer. Ofcourse, you need a compiler to convert Sanskrit instructions to machine language. I know the script &amp; yes, it is precise (entirely phonetic so you never have to ask \"how do you spell that\"), but I don't know the grammer well enough.</p>\n\n<p>This is completeley anecdotal, so I don't vouch for the accuracy of this. Just wanted to share what I know regarding this. :-)</p>\n" }, { "answer_id": 8052147, "author": "user1035804", "author_id": 1035804, "author_profile": "https://Stackoverflow.com/users/1035804", "pm_score": 0, "selected": false, "text": "<p>Please check the web site from the Research and Incubation Center of Northwestern Polytechnic University, <a href=\"http://www.jumpulse.com\" rel=\"nofollow\">http://www.jumpulse.com</a> to see a human-language programming language <em>New</em>, which communicates exclusively in human language with the user. New is based on a completely automated software. It should be usable by people from 10-years old and up.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68336/" ]
I mean, is there a coded language with human style coding? For example: ``` Create an object called MyVar and initialize it to 10; Take MyVar and call MyMethod() with parameters. . . ``` I know it's not so useful, but it can be interesting to create such a grammar.
[COBOL](http://en.wikipedia.org/wiki/Cobol) is a lot like that. ``` SET MYVAR TO 10. EXECUTE MYMETHOD with 10, MYVAR. ``` Another sample from Wikipedia: ``` ADD YEARS TO AGE. MULTIPLY PRICE BY QUANTITY GIVING COST. SUBTRACT DISCOUNT FROM COST GIVING FINAL-COST. ``` Oddly enough though, despite its design to be readable as English, most programmers completely undermined this with bizarre naming conventions: ``` SET VAR_00_MYVAR_PIC99 TO 10. EXECUTE PROC_10_MYMETHOD with 10, VAR_00_MYVAR_PIC99. ```
202,777
<p>I'm creating a invoice crystal report for sage mas 500 AR module. In it, I'm attempting to add the <code>tarinvoice.balance</code> field with the following formula: </p> <pre><code>if {tarPrintInvcHdrWrk.Posted} = 1 then ToText({tarInvoice.Balance}) </code></pre> <p>I'm assuming that when the <code>{tarPrintInvcHdrWrk.Posted} = 1</code> conditional statement holds FALSE, it doesn't attempt to pull the invoice field because when I remove the formula from the report, the form displays correctly without it. </p> <p>When the conditional statement renders true in the report, the balance fields behaves correctly. However, with the formula renders FALSE in the CR form, the entire crystal report bombs and displays blank. Any ideas why or what I'm doing wrong?</p> <hr> <p>Just tried setting everything to zero and the report still bombs. I'm starting to think its more of a query error in the report. I wish there was a way to exclude the field in the query when posted = 0. </p> <p>With <code>tarinvoice.balance</code> removed when the posted = 0, the report works fine.<br> With <code>tarinvoice.balance</code> included and posted = 1, report works fine. </p> <p>With <code>tarinvoice.balance</code> included and posted =0, report bombs.</p>
[ { "answer_id": 202882, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 2, "selected": false, "text": "<p>I believe the conditional statement fails immediately if you encounter a NULL, so your formula needs to test <strong>IsNull({tarPrintInvcHdrWrk.Posted})</strong> before it tests equality with \"1\".</p>\n" }, { "answer_id": 203840, "author": "Anthony K", "author_id": 1682, "author_profile": "https://Stackoverflow.com/users/1682", "pm_score": 0, "selected": false, "text": "<p>You can change the way Crystal handles a null value for a value in a formula. At the top of the Formula Workshop there is a drop down box that usually says \"Exceptions For Nulls\".<br>\nChange this to the other option \"Default Values For Nulls\" and your formula should no longer bomb out. You used to be able to specify the what the default values applied were, but more recent versions of Crystal have these hard coded.\nSearch the help for \"Null Treatment\" for a table showing them. </p>\n" }, { "answer_id": 205047, "author": "user28014", "author_id": 28014, "author_profile": "https://Stackoverflow.com/users/28014", "pm_score": 0, "selected": false, "text": "<p>I modified the formula to this: </p>\n\n<pre><code>if isnull({tarPrintInvcHdrWrk.Posted}) = FALSE then \n if {tarPrintInvcHdrWrk.Posted} = 1 then \n if isnull({tarInvoice.Balance}) = FALSE then \n ToText({tarInvoice.Balance})\n else \n \"0.00\" \n else \n \"0.0\"\nelse \n\"0\"\n</code></pre>\n\n<p>The crystal report still bombs.. Nevertheless, it does show \"0\" in the appropriate space.</p>\n" }, { "answer_id": 211416, "author": "Anthony K", "author_id": 1682, "author_profile": "https://Stackoverflow.com/users/1682", "pm_score": 0, "selected": false, "text": "<p>I saw a suggestion on Exp.Exch to try putting the field into a variable before converting it to text.<br>\ne.g. </p>\n\n<pre><code>NumberVar InvoiceBalance; \nIf isnull({tarInvoice.Balance}) then\n InvoiceBalance := 0\nElse\n InvoiceBalance := {tarInvoice.Balance};\n\nIf {tarPrintInvcHdrWrk.Posted} = 1 then\n ToText(InvoiceBalance);\n\n</code></pre>\n\n<p>I also tried to recreate your problem, since I have see similar things before.<br>\nNo luck though trying with CR 8.5 &amp; XI R2. Perhpas it has to do with linked tables as well, since I only tried on a simple single table.<br>\nI have also seen similar behaviour when using a formula within a Running Total - they do not like nulls at all!</p>\n" }, { "answer_id": 255200, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 0, "selected": false, "text": "<p>If you put {tarInvoice.Balance} directly on report (into details \"debug\" section - often needed, don't forget supress it in production :)), what values it displays or does report become empty?</p>\n" }, { "answer_id": 905306, "author": "Michael Buen", "author_id": 11432, "author_profile": "https://Stackoverflow.com/users/11432", "pm_score": 0, "selected": false, "text": "<p>Maybe you have Suppress If Blank section on your report. Try to put: Else \" \"</p>\n" }, { "answer_id": 7685700, "author": "vice", "author_id": 933136, "author_profile": "https://Stackoverflow.com/users/933136", "pm_score": 0, "selected": false, "text": "<pre><code>if isnull({tarPrintInvcHdrWrk.Posted}) or {tarPrintInvcHdrWrk.Posted}=0 then\n\" \"\nelse\nif {tarPrintInvcHdrWrk.Posted} = 1 then \n ToText({tarInvoice.Balance})\nelse\n\" \"\n</code></pre>\n\n<p>I have trouble with this kind of field when making reports to export to excel. A field with no data in will pull all columns to the right of it over to \"fill the gap\".</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28014/" ]
I'm creating a invoice crystal report for sage mas 500 AR module. In it, I'm attempting to add the `tarinvoice.balance` field with the following formula: ``` if {tarPrintInvcHdrWrk.Posted} = 1 then ToText({tarInvoice.Balance}) ``` I'm assuming that when the `{tarPrintInvcHdrWrk.Posted} = 1` conditional statement holds FALSE, it doesn't attempt to pull the invoice field because when I remove the formula from the report, the form displays correctly without it. When the conditional statement renders true in the report, the balance fields behaves correctly. However, with the formula renders FALSE in the CR form, the entire crystal report bombs and displays blank. Any ideas why or what I'm doing wrong? --- Just tried setting everything to zero and the report still bombs. I'm starting to think its more of a query error in the report. I wish there was a way to exclude the field in the query when posted = 0. With `tarinvoice.balance` removed when the posted = 0, the report works fine. With `tarinvoice.balance` included and posted = 1, report works fine. With `tarinvoice.balance` included and posted =0, report bombs.
I believe the conditional statement fails immediately if you encounter a NULL, so your formula needs to test **IsNull({tarPrintInvcHdrWrk.Posted})** before it tests equality with "1".
202,786
<p>I need to merge a forked project. Unfortunately, the CVS $Id lines are different so the merge tools I tried report that all the files are different (and 95% of them have only this line different)</p> <p>Is there a merge tool that can be configured to ignore line comparison results based on a pattern ?</p> <p>[edit] I discovered that WinMerge has line filters - setting up them correctly actually works.</p> <p>Francesco</p>
[ { "answer_id": 202826, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.grigsoft.com/wincmp3.htm\" rel=\"nofollow noreferrer\">CompareIT</a> allow to use <a href=\"http://www.grigsoft.com/wincmp3/help/source/html/cmp_usingregularexpressions.htm\" rel=\"nofollow noreferrer\">regular expression</a> matching. I used it for automatically generated code comparison and it was very useful. </p>\n" }, { "answer_id": 202868, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 2, "selected": false, "text": "<p>I use meld, which can use regex filters to ignore.\nIt has some preset ones you can select including CVS keywords.\nThe regex it uses for that BTW is:</p>\n\n<pre><code>\\$\\w+(:[^\\n$]+)?\\$\n</code></pre>\n\n<p>You can get meld on any linux distro or\ndownload from here: <a href=\"http://meld.sourceforge.net/\" rel=\"nofollow noreferrer\">http://meld.sourceforge.net/</a>\nI'm not sure how it's supported on windos,\nbut I do know kdiff3 supports windows so you could\ngive it a try there: <a href=\"http://kdiff3.sourceforge.net/\" rel=\"nofollow noreferrer\">http://kdiff3.sourceforge.net/</a></p>\n" }, { "answer_id": 212946, "author": "Sally", "author_id": 6539, "author_profile": "https://Stackoverflow.com/users/6539", "pm_score": 1, "selected": false, "text": "<p>well you could use \ncvs update -kk \nwhick does not expand the $words.</p>\n\n<p>of course this is still a problems the $log which is expanded on commits and not updates.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to merge a forked project. Unfortunately, the CVS $Id lines are different so the merge tools I tried report that all the files are different (and 95% of them have only this line different) Is there a merge tool that can be configured to ignore line comparison results based on a pattern ? [edit] I discovered that WinMerge has line filters - setting up them correctly actually works. Francesco
I use meld, which can use regex filters to ignore. It has some preset ones you can select including CVS keywords. The regex it uses for that BTW is: ``` \$\w+(:[^\n$]+)?\$ ``` You can get meld on any linux distro or download from here: <http://meld.sourceforge.net/> I'm not sure how it's supported on windos, but I do know kdiff3 supports windows so you could give it a try there: <http://kdiff3.sourceforge.net/>
202,790
<p>I have an <strong>"ldquo"</strong>, <strong>"rdquo"</strong> and several other entities under my RSS feed. Seems like if I add</p> <pre><code>&lt;!DOCTYPE rss [ &lt;!ENTITY % HTMLspec PUBLIC "-//W3C//ENTITIES Latin 1 for XHTML//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent"&gt; %HTMLspec; </code></pre> <p>below the <strong>xml</strong> tag and above the <strong>rss</strong> tag then I'll be able to include those entities. I added but it doesn't seem to work. Does anyone knows what I missing? Thanks</p>
[ { "answer_id": 203765, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 2, "selected": false, "text": "<p>it doesn't seem likely that many feed readers will know what to do with that. i would recommend sticking with numbered entity references. for example, change <code>&amp;ldquo;</code> to <code>&amp;#8220;</code>. you can get the full entity reference <a href=\"http://www.w3.org/TR/REC-html40/sgml/entities.html\" rel=\"nofollow noreferrer\">right here from w3c</a>.</p>\n\n<p>additionally, you can read <a href=\"http://myst-technology.com/public/item/11878\" rel=\"nofollow noreferrer\">this article</a> and <a href=\"http://dotjay.co.uk/2006/sep/named-html-entities-in-rss\" rel=\"nofollow noreferrer\">this one</a> which gives some good tips on this topic.</p>\n" }, { "answer_id": 322224, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 1, "selected": false, "text": "<p>Forget entities. Just use UTF-8 for all characters. </p>\n\n<p>It will work reliably regardless whether RSS clients properly parse XML or not (sadly, the latter isn't uncommon).</p>\n" }, { "answer_id": 13870473, "author": "giacoder", "author_id": 582864, "author_profile": "https://Stackoverflow.com/users/582864", "pm_score": 1, "selected": false, "text": "<p>Strangely enough but in RSS instead of </p>\n\n<p><code>&amp;rsquo;</code> </p>\n\n<p>I used</p>\n\n<p><code>&amp;amp;rsquo;</code> </p>\n\n<p>and it worked in all browsers that I have (IE, Mozilla, Google Chrome)</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an **"ldquo"**, **"rdquo"** and several other entities under my RSS feed. Seems like if I add ``` <!DOCTYPE rss [ <!ENTITY % HTMLspec PUBLIC "-//W3C//ENTITIES Latin 1 for XHTML//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent"> %HTMLspec; ``` below the **xml** tag and above the **rss** tag then I'll be able to include those entities. I added but it doesn't seem to work. Does anyone knows what I missing? Thanks
it doesn't seem likely that many feed readers will know what to do with that. i would recommend sticking with numbered entity references. for example, change `&ldquo;` to `&#8220;`. you can get the full entity reference [right here from w3c](http://www.w3.org/TR/REC-html40/sgml/entities.html). additionally, you can read [this article](http://myst-technology.com/public/item/11878) and [this one](http://dotjay.co.uk/2006/sep/named-html-entities-in-rss) which gives some good tips on this topic.
202,792
<p>I'm using a whole bunch of CALayers, creating a tile-based image not unlike GoogleMaps (different versions of the same image with more/less detail).</p> <p>The code I'm using to do this is:</p> <pre><code>UIImage* image = [self loadImage:obj.fileName zoomLevel:obj.zoomLevel]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; obj.layerToAddTo.contents = [image CGImage]; [CATransaction commit]; </code></pre> <p>I don't really feel like loading the CGImage from file using CoreGraphics because I'm lazy. But I will if there's a big performance boost! LoadImage just mangles a string to get the right path for loading said image, and obj is a NSObject-struct that holds all the info I need for this thread. </p> <p>Help?</p>
[ { "answer_id": 202933, "author": "heckj", "author_id": 19477, "author_profile": "https://Stackoverflow.com/users/19477", "pm_score": 3, "selected": true, "text": "<p>There's not a big performance boost - if anything it's the other way around. By going throuh UIImage to load up your images, you'll get all the benefits of caching that it does for you and it'll be a very speedy critter to use with your various CALayers.</p>\n" }, { "answer_id": 209156, "author": "Jason Harris", "author_id": 1345109, "author_profile": "https://Stackoverflow.com/users/1345109", "pm_score": -1, "selected": false, "text": "<p>I don't have a definite answer but I'd guess that you'd see a slower load time when using UIImage than you'd see when using CGImage. With CGImage, you specify the image type (jpg or png) during creation, but with UIImage, the object type needs to be determined dynamically. Admittedly, this is probably as simple as looking at the first few bytes of the image file, but it might not be.</p>\n\n<p>Once the image is actually in use, I wouldn't imagine that there'd be any difference at all between using the CGImage that internally represents a UIImage vs. using a CGImage you created yourself. I'd think they'd be exactly equivalent.</p>\n" }, { "answer_id": 216413, "author": "Jason Harris", "author_id": 1345109, "author_profile": "https://Stackoverflow.com/users/1345109", "pm_score": 1, "selected": false, "text": "<p>I just tried this and using pure CoreGraphics to load the image rather than using UIImage gave a noticeable speed improvement when loading many images in one go.</p>\n" }, { "answer_id": 894544, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>\"I just tried this and using pure CoreGraphics to load the image rather than using UIImage gave a noticeable speed improvement when loading many images in one go.\"</p>\n\n<p>How did you avoid using a UIImage? Or more precisely, how do you load an image file directly into CoreGraphics without going through a UIImage?</p>\n" }, { "answer_id": 3815801, "author": "Phil M", "author_id": 450263, "author_profile": "https://Stackoverflow.com/users/450263", "pm_score": -1, "selected": false, "text": "<p>One reason why NOT to use <code>UIImage -imageNamed:</code> to load images is that they are stored in the internal cache and that cache is not cleared in low memory situation.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28019/" ]
I'm using a whole bunch of CALayers, creating a tile-based image not unlike GoogleMaps (different versions of the same image with more/less detail). The code I'm using to do this is: ``` UIImage* image = [self loadImage:obj.fileName zoomLevel:obj.zoomLevel]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; obj.layerToAddTo.contents = [image CGImage]; [CATransaction commit]; ``` I don't really feel like loading the CGImage from file using CoreGraphics because I'm lazy. But I will if there's a big performance boost! LoadImage just mangles a string to get the right path for loading said image, and obj is a NSObject-struct that holds all the info I need for this thread. Help?
There's not a big performance boost - if anything it's the other way around. By going throuh UIImage to load up your images, you'll get all the benefits of caching that it does for you and it'll be a very speedy critter to use with your various CALayers.
202,813
<p>Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:</p> <pre><code>int[] terms; for(int runs = 0; runs &lt; 400; runs++) { terms[] = runs; } </code></pre> <p>For those who have used PHP, here's what I'm trying to do in C#:</p> <pre><code>$arr = array(); for ($i = 0; $i &lt; 10; $i++) { $arr[] = $i; } </code></pre>
[ { "answer_id": 202830, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "<p>You have to allocate the array first:</p>\n\n<pre><code>int [] terms = new int[400]; // allocate an array of 400 ints\nfor(int runs = 0; runs &lt; terms.Length; runs++) // Use Length property rather than the 400 magic number again\n{\n terms[runs] = value;\n}\n</code></pre>\n" }, { "answer_id": 202839, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 1, "selected": false, "text": "<pre><code>int[] terms = new int[400];\n\nfor(int runs = 0; runs &lt; 400; runs++)\n{\n terms[runs] = value;\n}\n</code></pre>\n" }, { "answer_id": 202849, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 3, "selected": false, "text": "<pre><code>int ArraySize = 400;\n\nint[] terms = new int[ArraySize];\n\n\nfor(int runs = 0; runs &lt; ArraySize; runs++)\n{\n\n terms[runs] = runs;\n\n}\n</code></pre>\n\n<p>That would be how I'd code it.</p>\n" }, { "answer_id": 202853, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": false, "text": "<p>You can't just add an element to an array easily. You can set the element at a given position as <em>fallen888</em> outlined, but I recommend to use a <code>List&lt;int&gt;</code> or a <code>Collection&lt;int&gt;</code> instead, and use <code>ToArray()</code> if you need it converted into an array.</p>\n" }, { "answer_id": 202854, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 11, "selected": true, "text": "<p>You can do this way -</p>\n\n<pre><code>int[] terms = new int[400];\nfor (int runs = 0; runs &lt; 400; runs++)\n{\n terms[runs] = value;\n}\n</code></pre>\n\n<p>Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.</p>\n\n<pre><code>List&lt;int&gt; termsList = new List&lt;int&gt;();\nfor (int runs = 0; runs &lt; 400; runs++)\n{\n termsList.Add(value);\n}\n\n// You can convert it back to an array if you would like to\nint[] terms = termsList.ToArray();\n</code></pre>\n\n<p><strong>Edit:</strong> <a href=\"https://stackoverflow.com/a/365658/495455\">a) <strong>for</strong> loops on List&lt;T> are a bit more than 2 times cheaper than <strong>foreach</strong> loops on List&lt;T>, b) Looping on array is around 2 times cheaper than looping on List&lt;T>, c) looping on array using <strong>for</strong> is 5 times cheaper than looping on List&lt;T> using <strong>foreach</strong> (which most of us do).</a></p>\n" }, { "answer_id": 202861, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": false, "text": "<p>C# arrays are fixed length and always indexed. Go with Motti's solution:</p>\n\n<pre><code>int [] terms = new int[400];\nfor(int runs = 0; runs &lt; 400; runs++)\n{\n terms[runs] = value;\n}\n</code></pre>\n\n<p>Note that this array is a dense array, a contiguous block of 400 bytes where you can drop things. If you want a dynamically sized array, use a List&lt;int>.</p>\n\n<pre><code>List&lt;int&gt; terms = new List&lt;int&gt;();\nfor(int runs = 0; runs &lt; 400; runs ++)\n{\n terms.Add(runs);\n}\n</code></pre>\n\n<p>Neither int[] nor List&lt;int> is an associative array -- that would be a Dictionary&lt;> in C#. Both arrays and lists are dense.</p>\n" }, { "answer_id": 202865, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "<p>Answers on how to do it using an array are provided here.</p>\n<p>However, C# has a very handy thing called System.Collections</p>\n<p>Collections are fancy alternatives to using an array, though many of them use an array internally.</p>\n<p>For example, C# has a collection called List that functions very similar to the PHP array.</p>\n<pre><code>using System.Collections.Generic;\n\n// Create a List, and it can only contain integers.\nList&lt;int&gt; list = new List&lt;int&gt;();\n\nfor (int i = 0; i &lt; 400; i++)\n{\n list.Add(i);\n}\n</code></pre>\n" }, { "answer_id": 203330, "author": "Amanda Mitchell", "author_id": 26628, "author_profile": "https://Stackoverflow.com/users/26628", "pm_score": 7, "selected": false, "text": "<p>If you're writing in C# 3, you can do it with a one-liner:</p>\n<pre><code>int[] terms = Enumerable.Range(0, 400).ToArray();\n</code></pre>\n<p>This code snippet assumes that you have a using directive for System.Linq at the top of your file.</p>\n<p>On the other hand, if you're looking for something that can be dynamically resized, as it appears is the case for PHP (I've never actually learned it), then you may want to use a List instead of an int[]. Here's what <em>that</em> code would look like:</p>\n<pre><code>List&lt;int&gt; terms = Enumerable.Range(0, 400).ToList();\n</code></pre>\n<p>Note, however, that you cannot simply add a 401st element by setting terms[400] to a value. You'd instead need to call Add() like this:</p>\n<pre><code>terms.Add(1337);\n</code></pre>\n" }, { "answer_id": 14620935, "author": "jhyap", "author_id": 2028195, "author_profile": "https://Stackoverflow.com/users/2028195", "pm_score": 2, "selected": false, "text": "<pre><code>int[] terms = new int[10]; //create 10 empty index in array terms\n\n//fill value = 400 for every index (run) in the array\n//terms.Length is the total length of the array, it is equal to 10 in this case \nfor (int run = 0; run &lt; terms.Length; run++) \n{\n terms[run] = 400;\n}\n\n//print value from each of the index\nfor (int run = 0; run &lt; terms.Length; run++)\n{\n Console.WriteLine(\"Value in index {0}:\\t{1}\",run, terms[run]);\n}\n\nConsole.ReadLine();\n</code></pre>\n\n<blockquote>\n <p>/*Output:</p>\n \n <p>Value in index 0: 400\n <br/>Value in index 1: 400\n <br/>Value in index 2: 400\n <br/>Value in index 3: 400\n <br/>Value in index 4: 400\n <br/>Value in index 5: 400\n <br/>Value in index 6: 400\n <br/>Value in index 7: 400\n <br/>Value in index 8: 400\n <br/>Value in index 9: 400\n <br/>*/</p>\n</blockquote>\n" }, { "answer_id": 22375937, "author": "user3404904", "author_id": 3404904, "author_profile": "https://Stackoverflow.com/users/3404904", "pm_score": 1, "selected": false, "text": "<pre><code> static void Main(string[] args)\n {\n int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/\n int i, j;\n\n\n /*initialize elements of array arrayname*/\n for (i = 0; i &lt; 5; i++)\n {\n arrayname[i] = i + 100;\n }\n\n /*output each array element value*/\n for (j = 0; j &lt; 5; j++)\n {\n Console.WriteLine(\"Element and output value [{0}]={1}\",j,arrayname[j]);\n }\n Console.ReadKey();/*Obtains the next character or function key pressed by the user.\n The pressed key is displayed in the console window.*/\n }\n</code></pre>\n" }, { "answer_id": 22376114, "author": "user3404904", "author_id": 3404904, "author_profile": "https://Stackoverflow.com/users/3404904", "pm_score": 1, "selected": false, "text": "<pre><code> /*arrayname is an array of 5 integer*/\n int[] arrayname = new int[5];\n int i, j;\n /*initialize elements of array arrayname*/\n for (i = 0; i &lt; 5; i++)\n {\n arrayname[i] = i + 100;\n }\n</code></pre>\n" }, { "answer_id": 25880091, "author": "Ali Humayun", "author_id": 1845464, "author_profile": "https://Stackoverflow.com/users/1845464", "pm_score": 2, "selected": false, "text": "<p>Just a different approach:</p>\n\n<pre><code>int runs = 0; \nbool batting = true; \nstring scorecard;\n\nwhile (batting = runs &lt; 400)\n scorecard += \"!\" + runs++;\n\nreturn scorecard.Split(\"!\");\n</code></pre>\n" }, { "answer_id": 30147352, "author": "Steve", "author_id": 4817023, "author_profile": "https://Stackoverflow.com/users/4817023", "pm_score": 3, "selected": false, "text": "<p>If you really need an array the following is probly the simplest:</p>\n\n<pre><code>using System.Collections.Generic;\n\n// Create a List, and it can only contain integers.\nList&lt;int&gt; list = new List&lt;int&gt;();\n\nfor (int i = 0; i &lt; 400; i++)\n{\n list.Add(i);\n}\n\nint [] terms = list.ToArray();\n</code></pre>\n" }, { "answer_id": 30314234, "author": "LCarter", "author_id": 688126, "author_profile": "https://Stackoverflow.com/users/688126", "pm_score": 2, "selected": false, "text": "<p>If you don't know the size of the Array or already have an existing array that you are adding to. You can go about this in two ways. The first is using a generic <code>List&lt;T&gt;</code>:\nTo do this you will want convert the array to a <code>var termsList = terms.ToList();</code> and use the Add method. Then when done use the <code>var terms = termsList.ToArray();</code> method to convert back to an array.</p>\n<pre><code>var terms = default(int[]);\nvar termsList = terms == null ? new List&lt;int&gt;() : terms.ToList();\n\nfor(var i = 0; i &lt; 400; i++)\n termsList.Add(i);\n\nterms = termsList.ToArray();\n</code></pre>\n<p>The second way is resizing the current array:</p>\n<pre><code>var terms = default(int[]);\n\nfor(var i = 0; i &lt; 400; i++)\n{\n if(terms == null)\n terms = new int[1];\n else \n Array.Resize&lt;int&gt;(ref terms, terms.Length + 1);\n \n terms[terms.Length - 1] = i;\n}\n</code></pre>\n<p>If you are using .NET 3.5 <code>Array.Add(...);</code></p>\n<p>Both of these will allow you to do it dynamically. If you will be adding lots of items then just use a <code>List&lt;T&gt;</code>. If it's just a couple of items then it will have better performance resizing the array. This is because you take more of a hit for creating the <code>List&lt;T&gt;</code> object.</p>\n<p><strong>Times</strong> <em>in ticks:</em></p>\n<p><strong>3 items</strong></p>\n<blockquote>\n<p>Array Resize Time: 6</p>\n<p>List Add Time: 16</p>\n</blockquote>\n<p><strong>400 items</strong></p>\n<blockquote>\n<p>Array Resize Time: 305</p>\n<p>List Add Time: 20</p>\n</blockquote>\n" }, { "answer_id": 31542691, "author": "Thracx", "author_id": 296924, "author_profile": "https://Stackoverflow.com/users/296924", "pm_score": 4, "selected": false, "text": "<p>Using a List as an intermediary is the easiest way, as others have described, but since your input is an array and you don't just want to keep the data in a List, I presume you might be concerned about performance.</p>\n\n<p>The most efficient method is likely allocating a new array and then using Array.Copy or Array.CopyTo. This is not hard if you just want to add an item to the end of the list:</p>\n\n<pre><code>public static T[] Add&lt;T&gt;(this T[] target, T item)\n{\n if (target == null)\n {\n //TODO: Return null or throw ArgumentNullException;\n }\n T[] result = new T[target.Length + 1];\n target.CopyTo(result, 0);\n result[target.Length] = item;\n return result;\n}\n</code></pre>\n\n<p>I can also post code for an Insert extension method that takes a destination index as input, if desired. It's a little more complicated and uses the static method Array.Copy 1-2 times.</p>\n" }, { "answer_id": 32515159, "author": "Mark", "author_id": 1463355, "author_profile": "https://Stackoverflow.com/users/1463355", "pm_score": 4, "selected": false, "text": "<p>Based on the answer of Thracx (I don't have enough points to answer):</p>\n\n<pre><code>public static T[] Add&lt;T&gt;(this T[] target, params T[] items)\n {\n // Validate the parameters\n if (target == null) {\n target = new T[] { };\n }\n if (items== null) {\n items = new T[] { };\n }\n\n // Join the arrays\n T[] result = new T[target.Length + items.Length];\n target.CopyTo(result, 0);\n items.CopyTo(result, target.Length);\n return result;\n }\n</code></pre>\n\n<p>This allows to add more than just one item to the array, or just pass an array as a parameter to join two arrays.</p>\n" }, { "answer_id": 43203172, "author": "Yitzhak Weinberg", "author_id": 4871015, "author_profile": "https://Stackoverflow.com/users/4871015", "pm_score": 7, "selected": false, "text": "<p>Using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq\" rel=\"noreferrer\">Linq</a>'s method <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.concat\" rel=\"noreferrer\">Concat</a> makes this simple</p>\n\n<pre><code>int[] array = new int[] { 3, 4 };\n\narray = array.Concat(new int[] { 2 }).ToArray();\n</code></pre>\n\n<p>result\n3,4,2</p>\n" }, { "answer_id": 56422608, "author": "David", "author_id": 948366, "author_profile": "https://Stackoverflow.com/users/948366", "pm_score": 2, "selected": false, "text": "<p>I will add this for a another variant. I prefer this type of functional coding lines more.</p>\n\n<pre><code>Enumerable.Range(0, 400).Select(x =&gt; x).ToArray();\n</code></pre>\n" }, { "answer_id": 60394294, "author": "Maghalakshmi Saravana", "author_id": 12562878, "author_profile": "https://Stackoverflow.com/users/12562878", "pm_score": 0, "selected": false, "text": "<p><strong>To add the list values to string array using C# without using ToArray() method</strong></p>\n\n<pre><code> List&lt;string&gt; list = new List&lt;string&gt;();\n list.Add(\"one\");\n list.Add(\"two\");\n list.Add(\"three\");\n list.Add(\"four\");\n list.Add(\"five\");\n string[] values = new string[list.Count];//assigning the count for array\n for(int i=0;i&lt;list.Count;i++)\n {\n values[i] = list[i].ToString();\n }\n</code></pre>\n\n<p>Output of the value array contains:</p>\n\n<p>one</p>\n\n<p>two</p>\n\n<p>three</p>\n\n<p>four</p>\n\n<p>five</p>\n" }, { "answer_id": 61063681, "author": "Safi Habhab", "author_id": 9339924, "author_profile": "https://Stackoverflow.com/users/9339924", "pm_score": 2, "selected": false, "text": "<p>one approach is to fill an array via LINQ</p>\n\n<p>if you want to fill an array with one element \nyou can simply write</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>string[] arrayToBeFilled;\narrayToBeFilled= arrayToBeFilled.Append(\"str\").ToArray();\n</code></pre>\n\n<p>furthermore, If you want to fill an array with multiple elements you can use the \nprevious code in a loop</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>//the array you want to fill values in\nstring[] arrayToBeFilled;\n//list of values that you want to fill inside an array\nList&lt;string&gt; listToFill = new List&lt;string&gt; { \"a1\", \"a2\", \"a3\" };\n//looping through list to start filling the array\n\nforeach (string str in listToFill){\n// here are the LINQ extensions\narrayToBeFilled= arrayToBeFilled.Append(str).ToArray();\n}\n\n</code></pre>\n" }, { "answer_id": 63263549, "author": "Manar Gul", "author_id": 6312235, "author_profile": "https://Stackoverflow.com/users/6312235", "pm_score": 2, "selected": false, "text": "<p>You can't do this directly. However, you can use <strong>Linq</strong> to do this:</p>\n<pre><code>List&lt;int&gt; termsLst=new List&lt;int&gt;();\nfor (int runs = 0; runs &lt; 400; runs++)\n{\n termsLst.Add(runs);\n}\nint[] terms = termsLst.ToArray();\n</code></pre>\n<p>If the array <em>terms</em> wasn't empty in the beginning, you can convert it to <strong>List</strong> first then do your stuf. Like:</p>\n<pre><code> List&lt;int&gt; termsLst = terms.ToList();\n for (int runs = 0; runs &lt; 400; runs++)\n {\n termsLst.Add(runs);\n }\n terms = termsLst.ToArray();\n</code></pre>\n<blockquote>\n<p><strong>Note:</strong> don't miss adding '<strong>using System.Linq;</strong>' at the begaining of the file.</p>\n</blockquote>\n" }, { "answer_id": 63923685, "author": "Phillip Holmes", "author_id": 1084830, "author_profile": "https://Stackoverflow.com/users/1084830", "pm_score": 2, "selected": false, "text": "<p>This seems like a lot less trouble to me:</p>\n<pre><code>var usageList = usageArray.ToList();\nusageList.Add(&quot;newstuff&quot;);\nusageArray = usageList.ToArray();\n</code></pre>\n" }, { "answer_id": 63974902, "author": "jerryurenaa", "author_id": 11611288, "author_profile": "https://Stackoverflow.com/users/11611288", "pm_score": 0, "selected": false, "text": "<p>You can do this is with a list. here is how</p>\n<pre><code>List&lt;string&gt; info = new List&lt;string&gt;();\ninfo.Add(&quot;finally worked&quot;);\n</code></pre>\n<p>and if you need to return this array do</p>\n<pre><code>return info.ToArray();\n</code></pre>\n" }, { "answer_id": 64387791, "author": "Leandro Bardelli", "author_id": 888472, "author_profile": "https://Stackoverflow.com/users/888472", "pm_score": 6, "selected": false, "text": "<p>By 2019 you can use <code>Append</code>, <code>Prepend</code> using <code>LinQ</code> in just one line</p>\n<pre><code>using System.Linq;\n</code></pre>\n<p>and then in NET 6.0:</p>\n<pre><code>terms = terms.Append(21);\n</code></pre>\n<p>or versions lower than NET 6.0</p>\n<pre><code>terms = terms.Append(21).ToArray();\n</code></pre>\n" }, { "answer_id": 66295175, "author": "Mondonno", "author_id": 11824362, "author_profile": "https://Stackoverflow.com/users/11824362", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://dotnetfiddle.net/dTnU2t\" rel=\"nofollow noreferrer\">Array Push Example</a></p>\n<pre class=\"lang-cs prettyprint-override\"><code>public void ArrayPush&lt;T&gt;(ref T[] table, object value)\n{\n Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)\n table.SetValue(value, table.Length - 1); // Setting the value for the new element\n}\n</code></pre>\n" }, { "answer_id": 72397743, "author": "theAccountant.py", "author_id": 2130154, "author_profile": "https://Stackoverflow.com/users/2130154", "pm_score": -1, "selected": false, "text": "<p>Here is one way how to deal with adding new numbers and strings to Array:</p>\n<pre><code>int[] ids = new int[10];\nids[0] = 1;\nstring[] names = new string[10];\n\ndo\n{\n for (int i = 0; i &lt; names.Length; i++)\n {\n Console.WriteLine(&quot;Enter Name&quot;);\n names[i] = Convert.ToString(Console.ReadLine());\n Console.WriteLine($&quot;The Name is: {names[i]}&quot;);\n Console.WriteLine($&quot;the index of name is: {i}&quot;);\n Console.WriteLine(&quot;Enter ID&quot;);\n ids[i] = Convert.ToInt32(Console.ReadLine());\n Console.WriteLine($&quot;The number is: {ids[i]}&quot;);\n Console.WriteLine($&quot;the index is: {i}&quot;);\n }\n\n\n} while (names.Length &lt;= 10);\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example: ``` int[] terms; for(int runs = 0; runs < 400; runs++) { terms[] = runs; } ``` For those who have used PHP, here's what I'm trying to do in C#: ``` $arr = array(); for ($i = 0; $i < 10; $i++) { $arr[] = $i; } ```
You can do this way - ``` int[] terms = new int[400]; for (int runs = 0; runs < 400; runs++) { terms[runs] = value; } ``` Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list. ``` List<int> termsList = new List<int>(); for (int runs = 0; runs < 400; runs++) { termsList.Add(value); } // You can convert it back to an array if you would like to int[] terms = termsList.ToArray(); ``` **Edit:** [a) **for** loops on List<T> are a bit more than 2 times cheaper than **foreach** loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using **for** is 5 times cheaper than looping on List<T> using **foreach** (which most of us do).](https://stackoverflow.com/a/365658/495455)
202,860
<p>I know this sounds like a really obvious question, but it's proving harder to figure out than I thought. I'm developing in Flash 8/ActionScript 2.0.</p> <p>I have a label component, and I'm dynamically assigning it text from an xml document. For example:</p> <pre><code>label.text = "&lt;b&gt;" + xml_node.firstChild + "&lt;/b&gt;"; </code></pre> <p>This successfully changes the label's text to whatever is in that XML node, and since I enabled HTML, it makes it bold. However, I want to increase the size of the label's font, and using <code>&lt;font&gt;</code> tags won't work.</p> <p>Am I missing something? How do I make the font larger? ActionScript is just so picky!</p>
[ { "answer_id": 202960, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 0, "selected": false, "text": "<p>I can't say for sure but I think you probably need to set the fontSize style of the Label. </p>\n" }, { "answer_id": 202967, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 2, "selected": false, "text": "<p>When you say \"label component\", do you mean a Flex 2 label, or a TextField?</p>\n\n<p>In the latter case, the font tag should work just fine. will set the font to 24px text for example. If it doesn't, you can use the stylesheet class to specify a font size and then assign it to the TextField.</p>\n\n<p>In the case of of Flex 2 label, use label.setStyle(\"fontSize\", 24) to set it to 24px text for example.</p>\n" }, { "answer_id": 202968, "author": "vanhornRF", "author_id": 1945, "author_profile": "https://Stackoverflow.com/users/1945", "pm_score": 0, "selected": false, "text": "<p>The font tag will really only work if you have a web ready font like Arial, Verdana, or Times New Roman and even then it's still kinda goofy. A lot of times AS will usually just ignore the font tag, at least that's what I've run into. If you want to format your text I'd use the TextFormat class to manipulate your text instead of trying to set it through HTML tags. Unless you're setting the HTML tags because it's really being formatted with CSS?</p>\n\n<p>In that case I'd go through and make absolutely sure that your textfield is set up for HTML tags. Instead of using label.text I would try to use label.htmlText? It really could be any number of issues...</p>\n" }, { "answer_id": 209472, "author": "MattSayar", "author_id": 557, "author_profile": "https://Stackoverflow.com/users/557", "pm_score": 2, "selected": true, "text": "<p>Thanks for everyone's input! After reading David Arno's post, I figured it out. Here's what I was doing.</p>\n\n<pre><code>label.text = \"&lt;b&gt;&lt;font size=24&gt;\" + xml_node.firstChild + \"&lt;/font&gt;&lt;/b&gt;\";\n</code></pre>\n\n<p>Here's what works:</p>\n\n<pre><code>//note the 'single quotes' around the 24\nlabel.text = \"&lt;b&gt;&lt;font size='24'&gt;\" + xml_node.firstChild + \"&lt;/font&gt;&lt;/b&gt;\";\n</code></pre>\n\n<p>I just tried different ways of typing 24 in there, and the single quotes worked. Also, don't forget to set HTML to true from the label's Parameters tab.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/557/" ]
I know this sounds like a really obvious question, but it's proving harder to figure out than I thought. I'm developing in Flash 8/ActionScript 2.0. I have a label component, and I'm dynamically assigning it text from an xml document. For example: ``` label.text = "<b>" + xml_node.firstChild + "</b>"; ``` This successfully changes the label's text to whatever is in that XML node, and since I enabled HTML, it makes it bold. However, I want to increase the size of the label's font, and using `<font>` tags won't work. Am I missing something? How do I make the font larger? ActionScript is just so picky!
Thanks for everyone's input! After reading David Arno's post, I figured it out. Here's what I was doing. ``` label.text = "<b><font size=24>" + xml_node.firstChild + "</font></b>"; ``` Here's what works: ``` //note the 'single quotes' around the 24 label.text = "<b><font size='24'>" + xml_node.firstChild + "</font></b>"; ``` I just tried different ways of typing 24 in there, and the single quotes worked. Also, don't forget to set HTML to true from the label's Parameters tab.
202,871
<p>I use MyGeneration along with nHibernate to create the basic POCO objects and XML mapping files. I have heard some people say they think code generators are not a good idea. What is the current best thinking? Is it just that code generation is bad when it generates thousands of lines of not understandable code?</p>
[ { "answer_id": 202879, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": false, "text": "<p>My stance is that code generators are not bad, but MANY uses of them are.</p>\n\n<p>If you are using a code generator for time savings that writes good code, then great, but often times it is not optimized, or adds a lot of overhead, in those cases I think it is bad.</p>\n" }, { "answer_id": 202886, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 0, "selected": false, "text": "<p>In certain (not many) cases they are useful. Such as if you want to generate classes based on lookup-type data in the database tables.</p>\n" }, { "answer_id": 202888, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>Code generation is bad when it makes programming more difficult (IE, poorly generated code, or a maintenance nightmare), but they are good when they make programming more efficient.</p>\n\n<p>They probably don't always generate optimal code, but depending on your need, you might decide that developer manhours saved make up for a few minor issues.</p>\n\n<p>All that said, my biggest gripe with ORM code generators is that maintenance the generated code can be a PITA if the schema changes.</p>\n" }, { "answer_id": 202889, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "<p>Code generators are not bad, but sometimes they are used in situations when another solution exists (ie, instantiating a million objects when an array of objects would have been more suitable and accomplished in a few lines of code).</p>\n\n<p>The other situation is when they are used incorrectly, or coded badly. Too many people swear off code generators because they've had bad experiences due to bugs, or their misunderstanding of how to correctly configure it.</p>\n\n<p>But in and of themselves, code generators are not bad.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 202890, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 0, "selected": false, "text": "<p>They are like any other tool. Some give beter results than others, but it is up to the user to know when to use them or not. A hammer is a terrible tool if you are trying to screw in a screw.</p>\n" }, { "answer_id": 202893, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 0, "selected": false, "text": "<p>This is one of those highly contentious issues. Personally, I think code generators are really bad due to the unoptimized crap code most of them put out.</p>\n\n<p>However, the question is really one that only you can answer. In a lot of organizations, development time is more important than project execution speed or even maintainability.</p>\n" }, { "answer_id": 202894, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 0, "selected": false, "text": "<p>We use code generators for generating data entity classes, database objects (like triggers, stored procs), service proxies etc. Anywhere you see lot of repititive code following a pattern and lot of manual work involved, code generators can help. But, you should not use it too much to the extend that maintainability is a pain. Some issues also arise if you want to regenerate them.</p>\n\n<p>Tools like Visual Studio, Codesmith have their own templates for most of the common tasks and make this process easier. But, it is easy to roll out on your own.</p>\n" }, { "answer_id": 202895, "author": "Josh Mein", "author_id": 2486, "author_profile": "https://Stackoverflow.com/users/2486", "pm_score": 0, "selected": false, "text": "<p>It can really become an issue with maintainability when you have to come back and cant understand what is going on in the code. Therefore many times you have to weigh how important it is to get the project done fast compared to easy maintainability</p>\n\n<p>maintainability &lt;> easy or fast coding process</p>\n" }, { "answer_id": 202900, "author": "Aaron Smith", "author_id": 12969, "author_profile": "https://Stackoverflow.com/users/12969", "pm_score": 0, "selected": false, "text": "<p>I use My Generation with Entity Spaces and I don't have any issues with it. If I have a schema change I just regenerate the classes and it all works out just fine.</p>\n" }, { "answer_id": 202906, "author": "DMKing", "author_id": 10887, "author_profile": "https://Stackoverflow.com/users/10887", "pm_score": 4, "selected": false, "text": "<p>The biggest problem I've had with code generators is during maintenance. If you modify the generated code and then make a change to your schema or template and try to regenerate you can have problems. </p>\n\n<p>One problem is if the tool doesn't allow you to protect changes you've made to the modified code then your changes will be overwritten. </p>\n\n<p>Another problem I've seen, particularly with code generators in RSA for web services, if you change the generated code too much the generator will complain that there is a mismatch and refuse to regenerate the code. This can happen for something as simple as changing the type of a variable. Then you are stuck generating the code to a different project and merging the results back into your original code.</p>\n" }, { "answer_id": 202908, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>They serve as a crutch that can disable your ability to maintain the program long-term.</p>\n" }, { "answer_id": 202942, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "<p>Code generation might cause you some grief if you like to mix behaviour into your classes. An equally productive alternative might be attributes/annotations and runtime reflection.</p>\n" }, { "answer_id": 202956, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 0, "selected": false, "text": "<p>The first C++ compilers were code generators that spit out C code (CFront).</p>\n\n<p>I'm not sure if this is an argument for or against code generators.</p>\n" }, { "answer_id": 203011, "author": "kloucks", "author_id": 20186, "author_profile": "https://Stackoverflow.com/users/20186", "pm_score": 1, "selected": false, "text": "<p>If its a mainframe cobol code generator that Fran Tarkenton is trying to sell you then absolutely yes!</p>\n" }, { "answer_id": 203020, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 2, "selected": false, "text": "<p>Compilers are code generators, so they are not inherently bad unless you only like to program in raw machine code. </p>\n\n<p>I believe however that code generators should always completely encapsulate the generated code. I.e. you should <em>never</em> have to modify the generated code by hand, any change should be done by modifying the input to the generator and regenerate the code.</p>\n" }, { "answer_id": 203052, "author": "Byron Ross", "author_id": 1811110, "author_profile": "https://Stackoverflow.com/users/1811110", "pm_score": 0, "selected": false, "text": "<p>I think that Mitchel has hit it on the head.\nCode generation has its place. There are some circumstances where it's more effective to have the computer do the work for you!\nIt can give you the freedom to change your mind about the implementation of a particular component when the time cost of making the code changes is small. Of course, it is still probably important to understand the output the code generator, but not always.\nWe had an example on a project we just finished where a number of C++ apps needed to communicate with a C# app over named pipes. It was better for us to use small, simple, files that defined the messages and have all the classes and code generated for each side of the transaction. When a programmer was working on problem X, the last thing they needed was to worry about the implentation details of the messages and the inevitable cache hit that would entail.</p>\n" }, { "answer_id": 203070, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 6, "selected": true, "text": "<p>Code generated by a code-generator should not (as a generalisation) be used in a situation where it is subsequently edited by human intervention. Some systems such the wizards on various incarnations of Visual C++ generated code that the programmer was then expected to edit by hand. This was not popular as it required developers to pick apart the generated code, understand it and make modifications. It also meant that the generation process was one shot.</p>\n\n<p>Generated code should live in separate files from other code in the system and only be generated from the generator. The generated code code should be clearly marked as such to indicate that people shouldn't modify it. I have had occasion to do quite a few code-generation systems of one sort or another and <em>All</em> of the code so generated has something like this in the preamble:</p>\n\n<pre><code>-- =============================================================\n-- === Foobar Module ===========================================\n-- =============================================================\n--\n-- === THIS IS GENERATED CODE. DO NOT EDIT. ===\n--\n-- =============================================================\n</code></pre>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1930110979\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Code Generation in Action</a> is quite a good book on the subject. </p>\n" }, { "answer_id": 203081, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 1, "selected": false, "text": "<p>I've written a few code generators before - and to be honest they saved my butt more than once!</p>\n\n<p>Once you have a clearly defined object - collection - user control design, you can use a code generator to build the basics for you, allowing your time as a developer to be used more effectively in building the complex stuff, after all, who really wants to write 300+ public property declarations and variable instatiations? I'd rather get stuck into the business logic than all the mindless repetitive tasks.</p>\n" }, { "answer_id": 203120, "author": "Jon Davis", "author_id": 11398, "author_profile": "https://Stackoverflow.com/users/11398", "pm_score": 0, "selected": false, "text": "<p>This is a workflow question. ASP.NET is a code generator. The XAML parsing engine actually generates C# before it gets converted to MSIL. When a code generator becomes an external product like CodeSmith that is isolated from your development workflow, special care must be taken to keep your project in sync. For example, if the generated code is ORM output, and you make a change to the database schema, you will either have to either completely abandon the code generator or else take advantage of C#'s capacity to work with partial classes (which let you add members and functionality to an existing class without inheriting it). </p>\n\n<p>I personally dislike the isolated / Alt-Tab nature of generator workflows; if the code generator is not part of my IDE then I feel like it's a kludge. Some code generators, such as Entity Spaces 2009 (not yet released), are more integrated than previous generations of generators.</p>\n\n<p>I think the panacea to the <em>purpose</em> of code generators can be enjoyed in precompilation routines. C# and other .NET languages lack this, although ASP.NET enjoys it and that's why, say, SubSonic works so well for ASP.NET but not much else. SubSonic generates C# code at build-time just before the normal ASP.NET compilation kicks in. </p>\n\n<p>Ask your tools vendor (i.e. Microsoft) to support pre-build routines more thoroughly, so that code generators can be integrated into the workflow of your solutions using metadata, rather than manually managed as externally outputted code files that have to be maintained in isolation.</p>\n\n<p>Jon</p>\n" }, { "answer_id": 203154, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "<p>Code generators can be a boon for productivity, but there are a few things to look for:</p>\n\n<p><strong>Let you work the way you want to work.</strong></p>\n\n<p>If you have to bend your non-generated code to fit around the generated code, then you should probably choose a different approach.</p>\n\n<p><strong>Run as part of your regular build.</strong></p>\n\n<p>The output should be generated to an intermediates directory, and not be checked in to source control. The input must be checked in to source control, however.</p>\n\n<p><strong>No install</strong></p>\n\n<p>Ideally, you check the tool in to source control, too. Making people install things when preparing a new build machine is bad news. For example, if you branch, you want to be able to version the tools with the code.</p>\n\n<p>If you must, make a single script that will take a clean machine with a copy of the source tree, and configure the machine as required. Fully automated, please.</p>\n\n<p><strong>No editing output</strong></p>\n\n<p>You shouldn't have to edit the output. If the output isn't useful enough as-is, then the tool isn't working for you.</p>\n\n<p>Also, the output should clearly state that it is a generated file &amp; should not be edited. </p>\n\n<p><strong>Readable output</strong></p>\n\n<p>The output should be written &amp; formatted well. You want to be able to open the output &amp; read it without a lot of trouble.</p>\n\n<p><strong><code>#line</code></strong></p>\n\n<p>Many languages support something like a <code>#line</code> directive, which lets you map the contents of the output back to the input, for example when producing compiler error messages or when stepping in the debugger. This can be useful, but it can also be annoying unless done really well, so it's not a requirement.</p>\n" }, { "answer_id": 203470, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 4, "selected": false, "text": "<p><strong>Code generators are great, bad code is bad.</strong></p>\n\n<p>Most of the other responses on this page are along the lines of \"No, because often the generated code is not very good.\"</p>\n\n<p>This is a poor answer because:</p>\n\n<p>1) Generators are tool like anything else - if you misuse them, dont blame the tool. </p>\n\n<p>2) Developers tend to pride themselves on their ability to write great code one time, but you dont use code generators for one off projects.</p>\n\n<p>We use a Code Generation system for persistence in all our Java projects and have thousands of generated classes in production. </p>\n\n<p><strong>As a manager I love them because:</strong></p>\n\n<p>1) Reliability: There are no significant remaining bugs in that code. It has been so exhaustively tested and refined over the years than when debugging I never worry about the persistence layer.</p>\n\n<p>2) Standardisation: Every developers code is identical in this respect so there is much less for a guy to learn when picking up a new project from a coworker.</p>\n\n<p>3) Evolution: If we find a better way to do things we can update the templates and update 1000's of classes quickly and consistently.</p>\n\n<p>4) Revolution: If we switch to a different persistence system in the future then the fact that every single persistent class has an exactly identical API makes my job far easier.</p>\n\n<p>5) Productivity: It is just a few clicks to build a persistent object system from metadata - this saves thousands of boring developer hours.</p>\n\n<p>Code generation is like using a compiler - on an individual case basis you might be able to write better optimised assembly language, but over large numbers of projects you would rather have the compiler do it for you right?</p>\n\n<p>We employ a simple trick to ensure that classes can always be regenerated without losing customisations: every generated class is abstract. Then the developer extends it with a concrete class, adds the custom business logic and overrides any base class methods he wants to differ from the standard. If there is a change in metadata he can regenerate the abstract class at any time, and if the new model breaks his concrete class the compiler will let him know.</p>\n" }, { "answer_id": 203651, "author": "Anderson Imes", "author_id": 3244, "author_profile": "https://Stackoverflow.com/users/3244", "pm_score": 1, "selected": false, "text": "<p>The mistake many people make when using code generation is to edit the generated code. If you keep in mind that if you feel like you need to edit the code, you actually need to be editing the code generation tool it's a boon to productivity. If you are constantly fighting the code that gets generated it's going to end up costing productivity.</p>\n\n<p>The best code generators I've found are those that allow you to edit the templates that generate the code. I really like Codesmith for this reason, because it's template-based and the templates are easily editable. When you find there is a deficiency in the code that gets generated, you just edit the template and regenerate your code and you are forever good after that.</p>\n\n<p>The other thing that I've found is that a lot of code generators aren't super easy to use with a source control system. The way we've gotten around this is to check in the <em>templates</em> rather than the code and the only thing we check into source control that is generated is a compiled version of the generated code (DLL files, mostly). This saves you a lot of grief because you only have to check in a few DLLs rather than possibly hundreds of generated files.</p>\n" }, { "answer_id": 204710, "author": "Rui Curado", "author_id": 15970, "author_profile": "https://Stackoverflow.com/users/15970", "pm_score": 0, "selected": false, "text": "<p>The best application of a code generator is when the entire project is a model, and all the project's source code is generated from that model. I am not talking UML and related crap. In this case, the project model also contains custom code.</p>\n\n<p>Then the only thing developers have to care about is the model. A simple architectural change may result in instant modification of thousands of source code lines. But everything remains in sync.</p>\n\n<p>This is IMHO the best approach. Sound utopic? At least I know it's not ;) The near future will tell.</p>\n" }, { "answer_id": 204791, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In a recent project we built our own code generator. We generated all the data base stuff, and all the base code for our view and view controller classes. Although the generator took several months to build (mostly because this was the first time we had done this, and we had a couple of false starts) it paid for itself the first time we ran it and generated the basic framework for the whole app in about ten minutes.\nThis was all in Java, but Ruby makes an excellent code-writing language particularly for small, one-off type projects.\nThe best thing was the consistency of the code and the project organization. In addition you kind of have to think the basic framework out ahead of time, which is always good.</p>\n" }, { "answer_id": 1063679, "author": "pbailey19", "author_id": 144729, "author_profile": "https://Stackoverflow.com/users/144729", "pm_score": 1, "selected": false, "text": "<p>Our current project makes heavy use of a code generator. That means I've seen both the \"obvious\" benefits of generating code for the first time - no coder error, no typos, better adherence to a standard coding style - and, after a few months in maintenance mode, the unexpected downsides. Our code generator did, indeed, improve our codebase quality initially. We made sure that it was fully automated and integrated with our automated builds. However, I would say that:</p>\n\n<p>(1) A code generator can be a crutch. We have several massive, ugly blobs of tough-to-maintain code in our system now, because at one point in the past it was easier to add twenty new classes to our code generation XML file, than it was to do proper analysis and class refactoring.</p>\n\n<p>(2) Exceptions to the rule kill you. We use the code generator to create several hundred Screen and Business Object classes. Initially, we enforced a standard on what methods could appear in a class, but like all standards, we started making exceptions. Now, our code generation XML file is a massive monster, filled with special-case snippets of Java code that are inserted into select classes. It's nearly impossible to parse or understand.</p>\n\n<p>(3) Since so much of our code is generated, using values from a database, it's proven difficult for developers to maintain a consistent code base on their individual workstations (since there can be multiple versions of the database). Debugging and tracing through the software is a lot harder, and newbies to the team take much longer to figure out the \"flow\" of the code, because of the extra abstraction and implicit relationships between classes. IDE's cannot pick up relationships between two classes that communicate via a code-generated class.</p>\n\n<p>That's probably enough for now. I think Code Generators are great as part of a developer's individual toolkit; a set of scripts that write out your boilerplate code make starting a project a lot easier. But Code Generators do <em>not</em> make maintenance problems go away.</p>\n" }, { "answer_id": 4320792, "author": "fastcodejava", "author_id": 184730, "author_profile": "https://Stackoverflow.com/users/184730", "pm_score": 0, "selected": false, "text": "<p>Code generators are great assuming it is a good code generator. Especially working c++/java which is very verbose.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
I use MyGeneration along with nHibernate to create the basic POCO objects and XML mapping files. I have heard some people say they think code generators are not a good idea. What is the current best thinking? Is it just that code generation is bad when it generates thousands of lines of not understandable code?
Code generated by a code-generator should not (as a generalisation) be used in a situation where it is subsequently edited by human intervention. Some systems such the wizards on various incarnations of Visual C++ generated code that the programmer was then expected to edit by hand. This was not popular as it required developers to pick apart the generated code, understand it and make modifications. It also meant that the generation process was one shot. Generated code should live in separate files from other code in the system and only be generated from the generator. The generated code code should be clearly marked as such to indicate that people shouldn't modify it. I have had occasion to do quite a few code-generation systems of one sort or another and *All* of the code so generated has something like this in the preamble: ``` -- ============================================================= -- === Foobar Module =========================================== -- ============================================================= -- -- === THIS IS GENERATED CODE. DO NOT EDIT. === -- -- ============================================================= ``` [Code Generation in Action](https://rads.stackoverflow.com/amzn/click/com/1930110979) is quite a good book on the subject.
202,907
<p>i'm having a problem to create a text_field without a method association. Maybe i even don't need it :-)</p> <p>I have two radio_buttons associated to the same method:</p> <pre><code>&lt;%= radio_button :comment, :author, "anonymous" %&gt; Anonymous &lt;br&gt; &lt;%= radio_button :comment, :author, "real_name" %&gt; Name &lt;br&gt; </code></pre> <p>What i would like to do is to have an text_field which when the user click on the radio_button "real_name" i can verify the value in this new text_field. </p> <p>Basically my Controller would be something like:</p> <p>@comment = Comment.new(params[:comment])</p> <p>if @comment.author == "real_name" @comment.author = "value-from-the-new-textfield end</p> <p>There is any way to do it?</p> <p>Regards,</p> <p>Victor</p>
[ { "answer_id": 202970, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 4, "selected": true, "text": "<p>If you want to generate a text_field without an associated object/method, use <a href=\"http://api.rubyonrails.com/classes/ActionView/Helpers/FormTagHelper.html#M001701\" rel=\"noreferrer\"><code>text_field_tag</code></a></p>\n" }, { "answer_id": 204141, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": 1, "selected": false, "text": "<p>You can use another parameter instead of :comment</p>\n\n<pre><code>&lt;%= radio_button :verify, :author, \"anonymous\" %&gt; Anonymous &lt;br&gt;\n&lt;%= radio_button :verify, :author, \"real_name\" %&gt; Name &lt;br&gt;\n</code></pre>\n\n<p>So in your controller you can get the value of selected button with</p>\n\n<pre><code>if params[:verify][:author] == 'real_name' ...\n</code></pre>\n" }, { "answer_id": 209276, "author": "Misplaced", "author_id": 13710, "author_profile": "https://Stackoverflow.com/users/13710", "pm_score": 0, "selected": false, "text": "<p><code>text_field_tag</code> is definitely the easiest way, but if you want to add a field that acts as part of a model, adding an <code>attr_accessor</code> attribute might be worth looking into as well.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18642/" ]
i'm having a problem to create a text\_field without a method association. Maybe i even don't need it :-) I have two radio\_buttons associated to the same method: ``` <%= radio_button :comment, :author, "anonymous" %> Anonymous <br> <%= radio_button :comment, :author, "real_name" %> Name <br> ``` What i would like to do is to have an text\_field which when the user click on the radio\_button "real\_name" i can verify the value in this new text\_field. Basically my Controller would be something like: @comment = Comment.new(params[:comment]) if @comment.author == "real\_name" @comment.author = "value-from-the-new-textfield end There is any way to do it? Regards, Victor
If you want to generate a text\_field without an associated object/method, use [`text_field_tag`](http://api.rubyonrails.com/classes/ActionView/Helpers/FormTagHelper.html#M001701)
202,912
<p>I have some hierarchical data - each entry has an id and a (nullable) parent entry id. I want to retrieve all entries in the tree under a given entry. This is in a SQL Server 2005 database. I am querying it with LINQ to SQL in C# 3.5.</p> <p>LINQ to SQL does not support <a href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" rel="noreferrer">Common Table Expressions</a> directly. My choices are to assemble the data in code with several LINQ queries, or to make a view on the database that surfaces a CTE. </p> <p>Which option (or another option) do you think will perform better when data volumes get large? Is SQL Server 2008's <a href="http://msdn.microsoft.com/en-us/library/bb677173.aspx" rel="noreferrer">HierarchyId type</a> supported in Linq to SQL?</p>
[ { "answer_id": 202929, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 2, "selected": false, "text": "<p>In MS SQL 2008 you could use <a href=\"http://msdn.microsoft.com/en-us/library/bb677290.aspx\" rel=\"nofollow noreferrer\">HierarchyID</a> directly, in sql2005 you may have to implement them manually. ParentID is not that performant on large data sets. Also check <a href=\"http://msdn.microsoft.com/en-us/library/bb677173.aspx\" rel=\"nofollow noreferrer\">this article</a> for more discussion on the topic.</p>\n" }, { "answer_id": 203071, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<p>I would set up a view and an associated table-based function based on the CTE. My reasoning for this is that, while you could implement the logic on the application side, this would involve sending the intermediate data over the wire for computation in the application. Using the DBML designer, the view translates into a Table entity. You can then associate the function with the Table entity and invoke the method created on the DataContext to derive objects of the type defined by the view. Using the table-based function allows the query engine to take your parameters into account while constructing the result set rather than applying a condition on the result set defined by the view after the fact.</p>\n\n<pre><code>CREATE TABLE [dbo].[hierarchical_table](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [parent_id] [int] NULL,\n [data] [varchar](255) NOT NULL,\n CONSTRAINT [PK_hierarchical_table] PRIMARY KEY CLUSTERED \n(\n [id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\nCREATE VIEW [dbo].[vw_recursive_view]\nAS\nWITH hierarchy_cte(id, parent_id, data, lvl) AS\n(SELECT id, parent_id, data, 0 AS lvl\n FROM dbo.hierarchical_table\n WHERE (parent_id IS NULL)\n UNION ALL\n SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl\n FROM dbo.hierarchical_table AS t1 INNER JOIN\n hierarchy_cte AS h ON t1.parent_id = h.id)\nSELECT id, parent_id, data, lvl\nFROM hierarchy_cte AS result\n\n\nCREATE FUNCTION [dbo].[fn_tree_for_parent] \n(\n @parent int\n)\nRETURNS \n@result TABLE \n(\n id int not null,\n parent_id int,\n data varchar(255) not null,\n lvl int not null\n)\nAS\nBEGIN\n WITH hierarchy_cte(id, parent_id, data, lvl) AS\n (SELECT id, parent_id, data, 0 AS lvl\n FROM dbo.hierarchical_table\n WHERE (id = @parent OR (parent_id IS NULL AND @parent IS NULL))\n UNION ALL\n SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl\n FROM dbo.hierarchical_table AS t1 INNER JOIN\n hierarchy_cte AS h ON t1.parent_id = h.id)\n INSERT INTO @result\n SELECT id, parent_id, data, lvl\n FROM hierarchy_cte AS result\nRETURN \nEND\n\nALTER TABLE [dbo].[hierarchical_table] WITH CHECK ADD CONSTRAINT [FK_hierarchical_table_hierarchical_table] FOREIGN KEY([parent_id])\nREFERENCES [dbo].[hierarchical_table] ([id])\n\nALTER TABLE [dbo].[hierarchical_table] CHECK CONSTRAINT [FK_hierarchical_table_hierarchical_table]\n</code></pre>\n\n<p>To use it you would do something like -- assuming some reasonable naming scheme:</p>\n\n<pre><code>using (DataContext dc = new HierarchicalDataContext())\n{\n HierarchicalTableEntity h = (from e in dc.HierarchicalTableEntities\n select e).First();\n var query = dc.FnTreeForParent( h.ID );\n foreach (HierarchicalTableViewEntity entity in query) {\n ...process the tree node...\n }\n}\n</code></pre>\n" }, { "answer_id": 203106, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "<p>I have done this two ways:</p>\n\n<ol>\n<li>Drive the retrieval of each layer of the tree based on user input. Imagine a tree view control populated with the root node, the children of the root, and the grandchildren of the root. Only the root and the children are expanded (grandchildren are hidden with the collapse). As the user expands a child node the grandchildren of the root are display (that were previously retrieved and hidden), and a retrieval of all of the great-grandchildren is launched. Repeat the pattern for N-layers deep. This pattern works very well for large trees (depth or width) because it only retrieves the portion of the tree needed.</li>\n<li>Use a stored procedure with LINQ. Use something like a common table expression on the server to build your results in a flat table, or build an XML tree in T-SQL. Scott Guthrie has a <a href=\"http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx\" rel=\"nofollow noreferrer\">great article</a> about using stored procs in LINQ. Build your tree from the results when they come back if in a flat format, or use the XML tree if that is that is what you return.</li>\n</ol>\n" }, { "answer_id": 203159, "author": "JarrettV", "author_id": 16340, "author_profile": "https://Stackoverflow.com/users/16340", "pm_score": 2, "selected": false, "text": "<p>This extension method could potentially be modified to use IQueryable. I've used it succesfully in the past on a collection of objects. It may work for your scenario.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; ByHierarchy&lt;T&gt;(\n this IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; startWith, Func&lt;T, T, bool&gt; connectBy)\n{\n if (source == null)\n throw new ArgumentNullException(\"source\");\n\n if (startWith == null)\n throw new ArgumentNullException(\"startWith\");\n\n if (connectBy == null)\n throw new ArgumentNullException(\"connectBy\");\n\n foreach (T root in source.Where(startWith))\n {\n yield return root;\n foreach (T child in source.ByHierarchy(c =&gt; connectBy(root, c), connectBy))\n {\n yield return child;\n }\n }\n}\n</code></pre>\n\n<p>Here is how I called it:</p>\n\n<pre><code>comments.ByHierarchy(comment =&gt; comment.ParentNum == parentNum, \n (parent, child) =&gt; child.ParentNum == parent.CommentNum &amp;&amp; includeChildren)\n</code></pre>\n\n<p>This code is an improved, bug-fixed version of the code found <a href=\"http://weblogs.asp.net/okloeten/archive/2006/07/09/Hierarchical-Linq-Queries.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 203190, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 1, "selected": false, "text": "<p>I got this approach from <a href=\"http://blog.wekeroad.com/mvc-storefront/\" rel=\"nofollow noreferrer\">Rob Conery's blog</a> (check around Pt. 6 for this code, also on codeplex) and I love using it. This could be refashioned to support multiple \"sub\" levels.</p>\n\n<pre><code>var categories = from c in db.Categories\n select new Category\n {\n CategoryID = c.CategoryID,\n ParentCategoryID = c.ParentCategoryID,\n SubCategories = new List&lt;Category&gt;(\n from sc in db.Categories\n where sc.ParentCategoryID == c.CategoryID\n select new Category {\n CategoryID = sc.CategoryID, \n ParentProductID = sc.ParentProductID\n }\n )\n };\n</code></pre>\n" }, { "answer_id": 203309, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>The trouble with fetching the data from the client side is that you can never be sure how deep you need to go. This method will do one roundtrip per depth and it could be union'd to do from 0 to a specified depth in one roundtrip.</p>\n\n<pre><code>public IQueryable&lt;Node&gt; GetChildrenAtDepth(int NodeID, int depth)\n{\n IQueryable&lt;Node&gt; query = db.Nodes.Where(n =&gt; n.NodeID == NodeID);\n for(int i = 0; i &lt; depth; i++)\n query = query.SelectMany(n =&gt; n.Children);\n //use this if the Children association has not been defined\n //query = query.SelectMany(n =&gt; db.Nodes.Where(c =&gt; c.ParentID == n.NodeID));\n return query;\n}\n</code></pre>\n\n<p>It can't, however, do arbitrary depth. If you really do require arbitrary depth, you need to do that in the database - so you can make the correct decision to stop.</p>\n" }, { "answer_id": 1110685, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>This <a href=\"http://www.scip.be/index.php?Page=ArticlesNET18\" rel=\"noreferrer\">option</a> might also prove useful:</p>\n\n<p><strong>LINQ AsHierarchy() extension method</strong> <br>\n<a href=\"http://www.scip.be/index.php?Page=ArticlesNET18\" rel=\"noreferrer\">http://www.scip.be/index.php?Page=ArticlesNET18</a></p>\n" }, { "answer_id": 2503467, "author": "too", "author_id": 291496, "author_profile": "https://Stackoverflow.com/users/291496", "pm_score": 3, "selected": false, "text": "<p>I am surprised nobody has mentioned an alternative database design - when hierarchy needs to be flattened from multiple levels and retrieved with high performance (not so considering storage space) it is better to use another entity-2-entity table to track hierarchy instead of parent_id approach. </p>\n\n<p>It will allow not only single parent relations but also multi parent relations, level indications and different types of relationships:</p>\n\n<pre><code>CREATE TABLE Person (\n Id INTEGER,\n Name TEXT\n);\n\nCREATE TABLE PersonInPerson (\n PersonId INTEGER NOT NULL,\n InPersonId INTEGER NOT NULL,\n Level INTEGER,\n RelationKind VARCHAR(1)\n);\n</code></pre>\n" }, { "answer_id": 2552829, "author": "Jacob Jojan", "author_id": 305994, "author_profile": "https://Stackoverflow.com/users/305994", "pm_score": 0, "selected": false, "text": "<p>Please read the following link.</p>\n\n<p><a href=\"http://support.microsoft.com/default.aspx?scid=kb;en-us;q248915\" rel=\"nofollow noreferrer\">http://support.microsoft.com/default.aspx?scid=kb;en-us;q248915</a></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5599/" ]
I have some hierarchical data - each entry has an id and a (nullable) parent entry id. I want to retrieve all entries in the tree under a given entry. This is in a SQL Server 2005 database. I am querying it with LINQ to SQL in C# 3.5. LINQ to SQL does not support [Common Table Expressions](http://msdn.microsoft.com/en-us/library/ms190766.aspx) directly. My choices are to assemble the data in code with several LINQ queries, or to make a view on the database that surfaces a CTE. Which option (or another option) do you think will perform better when data volumes get large? Is SQL Server 2008's [HierarchyId type](http://msdn.microsoft.com/en-us/library/bb677173.aspx) supported in Linq to SQL?
I would set up a view and an associated table-based function based on the CTE. My reasoning for this is that, while you could implement the logic on the application side, this would involve sending the intermediate data over the wire for computation in the application. Using the DBML designer, the view translates into a Table entity. You can then associate the function with the Table entity and invoke the method created on the DataContext to derive objects of the type defined by the view. Using the table-based function allows the query engine to take your parameters into account while constructing the result set rather than applying a condition on the result set defined by the view after the fact. ``` CREATE TABLE [dbo].[hierarchical_table]( [id] [int] IDENTITY(1,1) NOT NULL, [parent_id] [int] NULL, [data] [varchar](255) NOT NULL, CONSTRAINT [PK_hierarchical_table] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] CREATE VIEW [dbo].[vw_recursive_view] AS WITH hierarchy_cte(id, parent_id, data, lvl) AS (SELECT id, parent_id, data, 0 AS lvl FROM dbo.hierarchical_table WHERE (parent_id IS NULL) UNION ALL SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl FROM dbo.hierarchical_table AS t1 INNER JOIN hierarchy_cte AS h ON t1.parent_id = h.id) SELECT id, parent_id, data, lvl FROM hierarchy_cte AS result CREATE FUNCTION [dbo].[fn_tree_for_parent] ( @parent int ) RETURNS @result TABLE ( id int not null, parent_id int, data varchar(255) not null, lvl int not null ) AS BEGIN WITH hierarchy_cte(id, parent_id, data, lvl) AS (SELECT id, parent_id, data, 0 AS lvl FROM dbo.hierarchical_table WHERE (id = @parent OR (parent_id IS NULL AND @parent IS NULL)) UNION ALL SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl FROM dbo.hierarchical_table AS t1 INNER JOIN hierarchy_cte AS h ON t1.parent_id = h.id) INSERT INTO @result SELECT id, parent_id, data, lvl FROM hierarchy_cte AS result RETURN END ALTER TABLE [dbo].[hierarchical_table] WITH CHECK ADD CONSTRAINT [FK_hierarchical_table_hierarchical_table] FOREIGN KEY([parent_id]) REFERENCES [dbo].[hierarchical_table] ([id]) ALTER TABLE [dbo].[hierarchical_table] CHECK CONSTRAINT [FK_hierarchical_table_hierarchical_table] ``` To use it you would do something like -- assuming some reasonable naming scheme: ``` using (DataContext dc = new HierarchicalDataContext()) { HierarchicalTableEntity h = (from e in dc.HierarchicalTableEntities select e).First(); var query = dc.FnTreeForParent( h.ID ); foreach (HierarchicalTableViewEntity entity in query) { ...process the tree node... } } ```
202,914
<p>I have a storyboard(1) that does some basic animations in 2 seconds. I want the storyboard(1) to do all the property animations I have set it up to do (this all works fine). But at 3 seconds into the storyboard(1) I want to begin storyboard(2) and exit storyboard(1) without user interaction at all.</p> <p>Only thing I've seen that allows me to do this is when the user clicks on something. I want this to be automatic based on the position of the current storyboard(1) timeline.</p> <p>I hope this makes enough sense. Please let me know if you need me to explain something in more detail.</p> <p>Thanks.</p> <p>Edit: Please post the answer in XAML or VB.net language. :)</p>
[ { "answer_id": 205118, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 3, "selected": false, "text": "<p>Normally in order to control animations during the timeline you would use \"keyframes\". Keyframe animations allow you to define specific values for the property you are animating at specific times. In WPF every animation has a corresponding keyframe animation, like 'DoubleAnimation' has 'DoubleAnimationUsingKeyFrames'.</p>\n\n<p>I don't think it's possible to start a new storyboard from within an animation. However you could achieve the same result by having both storyboards on the same timeline and starting storyboard(2) with a specific delay based on the duration of storyboard(1). Something like:</p>\n\n<pre><code>&lt;StackPanel&gt;\n &lt;Rectangle Name=\"recProgressBar\"\n Fill=\"Orange\"\n Width=\"1\"\n Height=\"25\"\n Margin=\"20\"\n HorizontalAlignment=\"Left\" /&gt;\n &lt;Button Content=\"Start Animation\"\n Width=\"150\"\n Height=\"25\"&gt;\n &lt;Button.Triggers&gt;\n &lt;EventTrigger RoutedEvent=\"Button.Click\"&gt;\n &lt;BeginStoryboard&gt;\n &lt;Storyboard&gt;\n &lt;DoubleAnimation Storyboard.TargetName=\"recProgressBar\"\n Storyboard.TargetProperty=\"Width\"\n From=\"0\"\n To=\"250\"\n Duration=\"0:0:2\" /&gt;\n &lt;Storyboard BeginTime=\"0:0:3\"&gt;\n &lt;ColorAnimation Storyboard.TargetName=\"recProgressBar\"\n Storyboard.TargetProperty=\"Fill.Color\"\n To=\"DarkGreen\"\n Duration=\"0:0:1\" /&gt;\n &lt;/Storyboard&gt;\n &lt;/Storyboard&gt;\n &lt;/BeginStoryboard&gt;\n &lt;/EventTrigger&gt;\n &lt;/Button.Triggers&gt;\n &lt;/Button&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n\n<p>Here the color animation will start 1 second after the width animation has finished. It could be worth a try.</p>\n" }, { "answer_id": 205184, "author": "ScottN", "author_id": 27494, "author_profile": "https://Stackoverflow.com/users/27494", "pm_score": 0, "selected": false, "text": "<p>Thanks Megakemp, that's what I was afraid of having to do. I didn't want to have to manage two copies of a storyboard in XAML. If I have to add a control and manage it via storyboard(1) I will have to remember to copy and paste the changes to this other storyboard(2). I guess those are the hoops you have to jump thru until the functionality comes that I'm looking for.</p>\n\n<p>Now I did think of another idea to try but wasn't able to get the functionality. This is my idea below, I can explain it better in code.. this below code will not compile, its just to get my point across.</p>\n\n<pre><code>Dim board As Storyboard = New Storyboard\nboard = DirectCast(TryFindResource(\"Animation1\"), Storyboard)\nIf board IsNot Nothing Then\n board.Begin(Me)\n While board.GetCurrentState(Me) = ClockState.Active\n 'Wait until Animation1 ends\n End While\n 'Start Animation2\n board = DirectCast(TryFindResource(\"Animation2\"), Storyboard)\n If board IsNot Nothing Then\n board.Begin(Me)\n End If\nEnd If\n</code></pre>\n\n<p>Thanks for your help.. and if anyone else has another answer or more insight please don't hesitate to post, I'm not abandoning this idea completely yet.</p>\n" }, { "answer_id": 206436, "author": "ScottN", "author_id": 27494, "author_profile": "https://Stackoverflow.com/users/27494", "pm_score": 1, "selected": true, "text": "<p>Well I came up with a solution. I just spawned a new thread to wait for 3 seconds and then did an Invoke call to run the storyboard from that thread.</p>\n\n<pre><code> Dim board As Storyboard = New Storyboard\n board = DirectCast(TryFindResource(\"DoSplit\"), Storyboard)\n If board IsNot Nothing Then\n board.Begin(Me, True)\n\n Dim t As Thread\n t = New Thread(AddressOf Me.WaitToHidePanel)\n t.SetApartmentState(ApartmentState.STA)\n t.Start()\n\n End If\n</code></pre>\n\n<p>Do your thread safe delegates and functions and you'll have it working. It's a ugly hack in my opinion, but it works for now.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27494/" ]
I have a storyboard(1) that does some basic animations in 2 seconds. I want the storyboard(1) to do all the property animations I have set it up to do (this all works fine). But at 3 seconds into the storyboard(1) I want to begin storyboard(2) and exit storyboard(1) without user interaction at all. Only thing I've seen that allows me to do this is when the user clicks on something. I want this to be automatic based on the position of the current storyboard(1) timeline. I hope this makes enough sense. Please let me know if you need me to explain something in more detail. Thanks. Edit: Please post the answer in XAML or VB.net language. :)
Well I came up with a solution. I just spawned a new thread to wait for 3 seconds and then did an Invoke call to run the storyboard from that thread. ``` Dim board As Storyboard = New Storyboard board = DirectCast(TryFindResource("DoSplit"), Storyboard) If board IsNot Nothing Then board.Begin(Me, True) Dim t As Thread t = New Thread(AddressOf Me.WaitToHidePanel) t.SetApartmentState(ApartmentState.STA) t.Start() End If ``` Do your thread safe delegates and functions and you'll have it working. It's a ugly hack in my opinion, but it works for now.
202,962
<p>How do I connect to a MSSQL database using Perl's DBI module in Windows?</p>
[ { "answer_id": 202973, "author": "culix", "author_id": 28037, "author_profile": "https://Stackoverflow.com/users/28037", "pm_score": 3, "selected": false, "text": "<p>Couldn't find this anywhere reliable. Use Perl code similar to</p>\n\n<pre><code>use DBI;\nmy $dbs = \"dbi:ODBC:DRIVER={SQL Server};SERVER={ServerName}\";\nmy ($username, $password) = ('username', 'password');\n\nmy $dbh = DBI-&gt;connect($dbs, $username, $password);\n\nif (defined($dbh))\n{\n #write code here\n $dbh-&gt;disconnect;\n}\nelse\n{\n print \"Error connecting to database: Error $DBI::err - $DBI::errstr\\n\";\n}\n</code></pre>\n" }, { "answer_id": 203095, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 5, "selected": true, "text": "<p>Use DBD::ODBC. If you just create a data source with the Control Panel -> System Management -> ODBC Data Sources -> System Data Source or User Data Source (those are the names as I remember them, but my XP isn't in English, so I can't check), then all you have to do is use the name of that data source in the DBI connect string.</p>\n\n<pre><code>my $dbh = DBI-&gt;connect(\"dbi:ODBC:$dsn\", $user, $pwd, \\%attr);\n</code></pre>\n\n<p>The difference between User and System data source is that the latter is usable by any user.</p>\n\n<p>See also: <a href=\"http://support.microsoft.com/kb/305599\" rel=\"noreferrer\">HOW TO: Create a System Data Source Name in Windows XP</a></p>\n" }, { "answer_id": 203224, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 2, "selected": false, "text": "<p>Checking <a href=\"http://www.perlmonks.org/index.pl?node_id=669089\" rel=\"nofollow noreferrer\" title=\"Perlmonks\">Perlmonks</a>, I see the suggestion to actually use the Sybase DBI driver for connecting to MS SQL. Which makes sense, given that MS SQL has its origins in the Sybase code. ODBC works, too, of course.</p>\n" }, { "answer_id": 37714262, "author": "Neil McGuigan", "author_id": 223478, "author_profile": "https://Stackoverflow.com/users/223478", "pm_score": 0, "selected": false, "text": "<p>Using OLEDB with Integrated Security (Windows Authentication):</p>\n\n<p><code>DBI:ADO:Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=localhost;Initial Catalog=$dbName;</code></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28037/" ]
How do I connect to a MSSQL database using Perl's DBI module in Windows?
Use DBD::ODBC. If you just create a data source with the Control Panel -> System Management -> ODBC Data Sources -> System Data Source or User Data Source (those are the names as I remember them, but my XP isn't in English, so I can't check), then all you have to do is use the name of that data source in the DBI connect string. ``` my $dbh = DBI->connect("dbi:ODBC:$dsn", $user, $pwd, \%attr); ``` The difference between User and System data source is that the latter is usable by any user. See also: [HOW TO: Create a System Data Source Name in Windows XP](http://support.microsoft.com/kb/305599)
202,971
<p>I've built a simple application that applies grid-lines to an image or just simple colors for use as desktop wallpaper. The idea is that the desktop icons can be arranged within the grid. The problem is that depending on more things than I understand the actual spacing in pixels seems to be different from system to system. I've learned that at least these things play a factor:</p> <ul> <li>Resolution (duh)</li> <li>Taskbar size and placement</li> <li>Fonts</li> </ul> <p>There has to be more than this. Maybe there's some api call that I don't know about?</p>
[ { "answer_id": 202992, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>They might also be a size problem due to scaling algorithm if the requested size of the icon is not available.<br>\n(since an icon file is actually a collection of icons, as explained in this thread about <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/08/20/8880062.aspx\" rel=\"nofollow noreferrer\">Icons and cursors know where they came from</a>, from the <a href=\"http://blogs.msdn.com/oldnewthing/default.aspx\" rel=\"nofollow noreferrer\">The Old New Thing</a>)</p>\n" }, { "answer_id": 202997, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 3, "selected": true, "text": "<p>there are a 1001 ways to get/set this (but I only know 2) :-D</p>\n\n<p>Windows Register:</p>\n\n<pre>HKEY_CURRENT_USER\\Control Panel\\Desktop\\WindowMetrics</pre>\n\n<p>values are <strong>IconSpacing</strong> and <strong>IconVerticalSpacing</strong></p>\n\n<p>by code:</p>\n\n<p><code>using System.Management; </p>\n\n<p>public string GetWinIconSpace()</p>\n\n<p>{</p>\n\n<pre><code>ManagementObjectSearcher searcher = new ManagementObjectSearcher(\"root\\\\CIMV2\",\"SELECT * FROM Win32_Desktop\"); \n\nforeach (ManagementObject wmi in searcher.Get())\n{\n try\n {\n\n return \"Desktop Icon Spacing: \" + wmi.GetPropertyValue(\"IconSpacing\").ToString();\n\n }\n\n catch { }\n\n}\n\nreturn \"Desktop Icon Spacing: Unknown\";\n</code></pre>\n\n<p>} \n</code></p>\n\n<p>and the 3rd that I never tried you can <a href=\"http://www.codeguru.com/vb/controls/vb_shell/article.php/c3055/\" rel=\"nofollow noreferrer\">find it here</a></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16260/" ]
I've built a simple application that applies grid-lines to an image or just simple colors for use as desktop wallpaper. The idea is that the desktop icons can be arranged within the grid. The problem is that depending on more things than I understand the actual spacing in pixels seems to be different from system to system. I've learned that at least these things play a factor: * Resolution (duh) * Taskbar size and placement * Fonts There has to be more than this. Maybe there's some api call that I don't know about?
there are a 1001 ways to get/set this (but I only know 2) :-D Windows Register: ``` HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics ``` values are **IconSpacing** and **IconVerticalSpacing** by code: `using System.Management;` public string GetWinIconSpace() { ``` ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2","SELECT * FROM Win32_Desktop"); foreach (ManagementObject wmi in searcher.Get()) { try { return "Desktop Icon Spacing: " + wmi.GetPropertyValue("IconSpacing").ToString(); } catch { } } return "Desktop Icon Spacing: Unknown"; ``` } and the 3rd that I never tried you can [find it here](http://www.codeguru.com/vb/controls/vb_shell/article.php/c3055/)
202,990
<p>Suppose I have a dataset with those two immortal tables: Employee &amp; Order <br/> <strong>Emp</strong> -> ID, Name <br/> <strong>Ord</strong> -> Something, Anotherthing, EmpID <br/> And relation <strong>Rel</strong>: Ord (EmpID) -> Emp (ID) <br/></p> <p>It works great in standard master/detail scenario <br/> (show employees, follow down the relation, show related orders), <br/> but what when I wan't to go the opposite way (show Ord table with Emp.Name)? <br/></p> <p>Something like this:<br/></p> <pre><code>&lt;stackpanel&gt; // with datacontext set from code to dataset.tables["ord"] &lt;TextBox Text="{Binding Something}"/&gt; &lt;TextBox Text="{Binding Anotherthing}"/&gt; &lt;TextBox Text="{Binding ???}"/&gt; // that's my problem, how to show related Emp.Name &lt;/stackpanel&gt; </code></pre> <p>Any ideas? I can create value converter, but if I wan't to use dataset instance which I get from parent module it gets tricky.</p>
[ { "answer_id": 207805, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 0, "selected": false, "text": "<p>Assuming that you are using a strongly-typed DataSet, in order to bind the TextBox to the 'EmpRow.Name' property, you will probably have to expose it as a property on the 'OrdDataTable' class.<br/></p>\n\n<p>Since Visual Studio generates the typed DataSet code with partial classes, you could add the property to the 'OrdDataTable' class this way:</p>\n\n<pre><code>using System.Data;\n\npublic partial class OrdDataTable : DataTable\n{\n public string EmpName\n {\n get { return this.EmpRow.Name; }\n }\n}\n</code></pre>\n\n<p>Then you would be able to bind to the 'EmpName' property of the 'OrdDataTable' object in the data context.</p>\n" }, { "answer_id": 221226, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 0, "selected": false, "text": "<p>What is the DataContext for the two TextBox controls?<br/>For the second binding to work the <strong>DataContext</strong> must be set to an instance of the 'USERSDataTable'. Since these are contained in an array in the DataSet, you have to explicitly tell which table you want to bind to. Something like:</p>\n\n<pre><code>&lt;StackPanel&gt;\n &lt;StackPanel.Resources&gt;\n &lt;ObjectDataProvider x:Key=\"ds\" ObjectType=\"{x:Type mynamespace:MyDataSet}\" /&gt;\n &lt;/StackPanel.Resources&gt;\n\n &lt;!-- Notice we set the data context to the first item in the array of tables --&gt;\n &lt;StackPanel DataContext=\"{Binding Source={StaticResource ds}, Path=USERS[0]}\"&gt;\n &lt;TextBox Text=\"{Binding NAME}\"/&gt;\n &lt;TextBox Text=\"{Binding COUNTRIESRow.NAME}\"/&gt;\n &lt;/StackPanel&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n" }, { "answer_id": 232876, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 2, "selected": true, "text": "<p>If you want to synchronize the contents of multiple controls, you will need to have them share the same binding source through the <strong>DataContext</strong> set on a common parent control. Here is an example:</p>\n\n<pre><code>&lt;StackPanel&gt;\n &lt;StackPanel.Resources&gt;\n &lt;ObjectDataProvider x:Key=\"ds\" ObjectType=\"{x:Type mynamespace:MyDataSet}\" /&gt;\n &lt;/StackPanel.Resources&gt;\n\n &lt;!-- We set the data context to the collection of rows in the table --&gt;\n &lt;StackPanel DataContext=\"{Binding Source={StaticResource ds}, Path=USERS.Rows}\"&gt;\n &lt;ListBox ItemsSource=\"{Binding}\"\n DisplayMemberPath=\"NAME\"\n IsSynchronizedWithCurrentItem=\"True\" /&gt;\n &lt;TextBox Text=\"{Binding Path=NAME}\"/&gt;\n &lt;TextBox Text=\"{Binding Path=COUNTRIESRow.NAME}\"/&gt;\n &lt;/StackPanel&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n\n<p>Setting the <strong>IsSynchronizedWithCurrentItem</strong> property to 'True' will cause the <strong>ListBox.SelectedItem</strong> property to be automatically synchronized with the <strong>CollectionView.CurrentItem</strong> of the binding source, that is the collection of rows set at the <strong>DataContext</strong>. This means that the currently selected row in the ListBox becomes the binding source for the two TextBox controls.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/202990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27956/" ]
Suppose I have a dataset with those two immortal tables: Employee & Order **Emp** -> ID, Name **Ord** -> Something, Anotherthing, EmpID And relation **Rel**: Ord (EmpID) -> Emp (ID) It works great in standard master/detail scenario (show employees, follow down the relation, show related orders), but what when I wan't to go the opposite way (show Ord table with Emp.Name)? Something like this: ``` <stackpanel> // with datacontext set from code to dataset.tables["ord"] <TextBox Text="{Binding Something}"/> <TextBox Text="{Binding Anotherthing}"/> <TextBox Text="{Binding ???}"/> // that's my problem, how to show related Emp.Name </stackpanel> ``` Any ideas? I can create value converter, but if I wan't to use dataset instance which I get from parent module it gets tricky.
If you want to synchronize the contents of multiple controls, you will need to have them share the same binding source through the **DataContext** set on a common parent control. Here is an example: ``` <StackPanel> <StackPanel.Resources> <ObjectDataProvider x:Key="ds" ObjectType="{x:Type mynamespace:MyDataSet}" /> </StackPanel.Resources> <!-- We set the data context to the collection of rows in the table --> <StackPanel DataContext="{Binding Source={StaticResource ds}, Path=USERS.Rows}"> <ListBox ItemsSource="{Binding}" DisplayMemberPath="NAME" IsSynchronizedWithCurrentItem="True" /> <TextBox Text="{Binding Path=NAME}"/> <TextBox Text="{Binding Path=COUNTRIESRow.NAME}"/> </StackPanel> </StackPanel> ``` Setting the **IsSynchronizedWithCurrentItem** property to 'True' will cause the **ListBox.SelectedItem** property to be automatically synchronized with the **CollectionView.CurrentItem** of the binding source, that is the collection of rows set at the **DataContext**. This means that the currently selected row in the ListBox becomes the binding source for the two TextBox controls.
203,030
<p>I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.</p> <p>Edit: My current solution, as suggested, is to use an anonymous Comparator:</p> <pre><code>File[] files = directory.listFiles(); Arrays.sort(files, new Comparator&lt;File&gt;(){ public int compare(File f1, File f2) { return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); } }); </code></pre>
[ { "answer_id": 203057, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 8, "selected": true, "text": "<p>I think your solution is the only sensible way. The only way to get the list of files is to use <a href=\"http://java.sun.com/javase/6/docs/api/java/io/File.html#listFiles()\" rel=\"noreferrer\">File.listFiles()</a> and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Comparator.html\" rel=\"noreferrer\">Comparator</a> that uses <a href=\"http://java.sun.com/javase/6/docs/api/java/io/File.html#lastModified()\" rel=\"noreferrer\">File.lastModified()</a> and pass this, along with the array of files, to <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#sort(T[],%20java.util.Comparator)\" rel=\"noreferrer\">Arrays.sort()</a>.</p>\n" }, { "answer_id": 203088, "author": "user17163", "author_id": 17163, "author_profile": "https://Stackoverflow.com/users/17163", "pm_score": 5, "selected": false, "text": "<p>You might also look at <a href=\"http://commons.apache.org/io/\" rel=\"noreferrer\">apache commons IO</a>, it has a built in <a href=\"http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/comparator/LastModifiedFileComparator.html\" rel=\"noreferrer\">last modified comparator</a> and many other nice utilities for working with files.</p>\n" }, { "answer_id": 4248059, "author": "Jason Orendorff", "author_id": 94977, "author_profile": "https://Stackoverflow.com/users/94977", "pm_score": 6, "selected": false, "text": "<p>This might be faster if you have many files. This uses the decorate-sort-undecorate pattern so that the last-modified date of each file is fetched only <em>once</em> rather than every time the sort algorithm compares two files. This potentially reduces the number of I/O calls from O(n log n) to O(n).</p>\n\n<p>It's more code, though, so this should only be used if you're mainly concerned with speed and it is measurably faster in practice (which I haven't checked).</p>\n\n<pre><code>class Pair implements Comparable {\n public long t;\n public File f;\n\n public Pair(File file) {\n f = file;\n t = file.lastModified();\n }\n\n public int compareTo(Object o) {\n long u = ((Pair) o).t;\n return t &lt; u ? -1 : t == u ? 0 : 1;\n }\n};\n\n// Obtain the array of (file, timestamp) pairs.\nFile[] files = directory.listFiles();\nPair[] pairs = new Pair[files.length];\nfor (int i = 0; i &lt; files.length; i++)\n pairs[i] = new Pair(files[i]);\n\n// Sort them by timestamp.\nArrays.sort(pairs);\n\n// Take the sorted pairs and extract only the file part, discarding the timestamp.\nfor (int i = 0; i &lt; files.length; i++)\n files[i] = pairs[i].f;\n</code></pre>\n" }, { "answer_id": 9929956, "author": "Calvin Schultz", "author_id": 1301413, "author_profile": "https://Stackoverflow.com/users/1301413", "pm_score": 2, "selected": false, "text": "<pre><code>public String[] getDirectoryList(String path) {\n String[] dirListing = null;\n File dir = new File(path);\n dirListing = dir.list();\n\n Arrays.sort(dirListing, 0, dirListing.length);\n return dirListing;\n}\n</code></pre>\n" }, { "answer_id": 15455840, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 1, "selected": false, "text": "<p>You can try guava <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Ordering.html\" rel=\"nofollow\">Ordering</a>:</p>\n\n<pre><code>Function&lt;File, Long&gt; getLastModified = new Function&lt;File, Long&gt;() {\n public Long apply(File file) {\n return file.lastModified();\n }\n};\n\nList&lt;File&gt; orderedFiles = Ordering.natural().onResultOf(getLastModified).\n sortedCopy(files);\n</code></pre>\n" }, { "answer_id": 17625095, "author": "Matthew Madson", "author_id": 1028367, "author_profile": "https://Stackoverflow.com/users/1028367", "pm_score": 4, "selected": false, "text": "<h2>If the files you are sorting can be modified or updated at the same time the sort is being performed:</h2>\n\n<hr>\n\n<h2>Java 8+</h2>\n\n<pre><code>private static List&lt;Path&gt; listFilesOldestFirst(final String directoryPath) throws IOException {\n try (final Stream&lt;Path&gt; fileStream = Files.list(Paths.get(directoryPath))) {\n return fileStream\n .map(Path::toFile)\n .collect(Collectors.toMap(Function.identity(), File::lastModified))\n .entrySet()\n .stream()\n .sorted(Map.Entry.comparingByValue())\n// .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) // replace the previous line with this line if you would prefer files listed newest first\n .map(Map.Entry::getKey)\n .map(File::toPath) // remove this line if you would rather work with a List&lt;File&gt; instead of List&lt;Path&gt;\n .collect(Collectors.toList());\n }\n}\n</code></pre>\n\n<h2>Java 7</h2>\n\n<pre><code>private static List&lt;File&gt; listFilesOldestFirst(final String directoryPath) throws IOException {\n final List&lt;File&gt; files = Arrays.asList(new File(directoryPath).listFiles());\n final Map&lt;File, Long&gt; constantLastModifiedTimes = new HashMap&lt;File,Long&gt;();\n for (final File f : files) {\n constantLastModifiedTimes.put(f, f.lastModified());\n }\n Collections.sort(files, new Comparator&lt;File&gt;() {\n @Override\n public int compare(final File f1, final File f2) {\n return constantLastModifiedTimes.get(f1).compareTo(constantLastModifiedTimes.get(f2));\n }\n });\n return files;\n}\n</code></pre>\n\n<p><br>\nBoth of these solutions create a temporary map data structure to save off a constant last modified time for each file in the directory. The reason we need to do this is that if your files are being updated or modified while your sort is being performed then your comparator will be violating the transitivity requirement of the comparator interface's general contract because the last modified times may be changing during the comparison.</p>\n\n<p>If, on the other hand, you know the files will not be updated or modified during your sort, you can get away with pretty much any other answer submitted to this question, of which I'm partial to:</p>\n\n<h2>Java 8+ (No concurrent modifications during sort)</h2>\n\n<pre><code>private static List&lt;Path&gt; listFilesOldestFirst(final String directoryPath) throws IOException {\n try (final Stream&lt;Path&gt; fileStream = Files.list(Paths.get(directoryPath))) {\n return fileStream\n .map(Path::toFile)\n .sorted(Comparator.comparing(File::lastModified))\n .map(File::toPath) // remove this line if you would rather work with a List&lt;File&gt; instead of List&lt;Path&gt;\n .collect(Collectors.toList());\n }\n}\n</code></pre>\n\n<p>Note: I know you can avoid the translation to and from File objects in the above example by using <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/nio/file/Files.html#getLastModifiedTime(java.nio.file.Path,java.nio.file.LinkOption...)\" rel=\"noreferrer\">Files::getLastModifiedTime</a> api in the sorted stream operation, however, then you need to deal with checked IO exceptions inside your lambda which is always a pain. I'd say if performance is critical enough that the translation is unacceptable then I'd either deal with the checked IOException in the lambda by propagating it as an UncheckedIOException or I'd forego the Files api altogether and deal only with File objects:</p>\n\n<pre><code>final List&lt;File&gt; sorted = Arrays.asList(new File(directoryPathString).listFiles());\nsorted.sort(Comparator.comparing(File::lastModified));\n</code></pre>\n" }, { "answer_id": 21534151, "author": "PhannGor", "author_id": 1845885, "author_profile": "https://Stackoverflow.com/users/1845885", "pm_score": 5, "selected": false, "text": "<p>What's about similar approach, but without boxing to the Long objects:</p>\n\n<pre><code>File[] files = directory.listFiles();\n\nArrays.sort(files, new Comparator&lt;File&gt;() {\n public int compare(File f1, File f2) {\n return Long.compare(f1.lastModified(), f2.lastModified());\n }\n});\n</code></pre>\n" }, { "answer_id": 24159031, "author": "Vikas", "author_id": 3711592, "author_profile": "https://Stackoverflow.com/users/3711592", "pm_score": 1, "selected": false, "text": "<p>You can use Apache <a href=\"http://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/comparator/LastModifiedFileComparator.html\" rel=\"nofollow\">LastModifiedFileComparator</a> library</p>\n\n<pre><code> import org.apache.commons.io.comparator.LastModifiedFileComparator; \n\n\nFile[] files = directory.listFiles();\n Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);\n for (File file : files) {\n Date lastMod = new Date(file.lastModified());\n System.out.println(\"File: \" + file.getName() + \", Date: \" + lastMod + \"\");\n }\n</code></pre>\n" }, { "answer_id": 25254566, "author": "Balaji Boggaram Ramanarayan", "author_id": 2101290, "author_profile": "https://Stackoverflow.com/users/2101290", "pm_score": 4, "selected": false, "text": "<p>Imports :</p>\n\n<pre><code>org.apache.commons.io.comparator.LastModifiedFileComparator\n</code></pre>\n\n<p><a href=\"http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/comparator/package-summary.html\" rel=\"noreferrer\">Apache Commons</a></p>\n\n<p>Code :</p>\n\n<pre><code>public static void main(String[] args) throws IOException {\n File directory = new File(\".\");\n // get just files, not directories\n File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);\n\n System.out.println(\"Default order\");\n displayFiles(files);\n\n Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);\n System.out.println(\"\\nLast Modified Ascending Order (LASTMODIFIED_COMPARATOR)\");\n displayFiles(files);\n\n Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);\n System.out.println(\"\\nLast Modified Descending Order (LASTMODIFIED_REVERSE)\");\n displayFiles(files);\n\n }\n</code></pre>\n" }, { "answer_id": 32955978, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 4, "selected": false, "text": "<p>In Java 8:</p>\n\n<p><code>Arrays.sort(files, (a, b) -&gt; Long.compare(a.lastModified(), b.lastModified()));</code></p>\n" }, { "answer_id": 33951175, "author": "Hirdesh Vishwdewa", "author_id": 1479735, "author_profile": "https://Stackoverflow.com/users/1479735", "pm_score": 0, "selected": false, "text": "<p>I came to this post when i was searching for the same issue but in <code>android</code>.\nI don't say this is the best way to get sorted files by last modified date, but its the easiest way I found yet.</p>\n\n<p>Below code may be helpful to someone-</p>\n\n<pre><code>File downloadDir = new File(\"mypath\"); \nFile[] list = downloadDir.listFiles();\n for (int i = list.length-1; i &gt;=0 ; i--) {\n //use list.getName to get the name of the file\n }\n</code></pre>\n\n<p>Thanks</p>\n" }, { "answer_id": 38729275, "author": "Jaydev", "author_id": 4269615, "author_profile": "https://Stackoverflow.com/users/4269615", "pm_score": 1, "selected": false, "text": "<pre><code>private static List&lt;File&gt; sortByLastModified(String dirPath) {\n List&lt;File&gt; files = listFilesRec(dirPath);\n Collections.sort(files, new Comparator&lt;File&gt;() {\n public int compare(File o1, File o2) {\n return Long.compare(o1.lastModified(), o2.lastModified());\n }\n });\n return files;\n}\n</code></pre>\n" }, { "answer_id": 44445813, "author": "viniciussss", "author_id": 4077150, "author_profile": "https://Stackoverflow.com/users/4077150", "pm_score": 6, "selected": false, "text": "<p><strong>Elegant solution since Java 8:</strong></p>\n\n<pre><code>File[] files = directory.listFiles();\nArrays.sort(files, Comparator.comparingLong(File::lastModified));\n</code></pre>\n\n<hr>\n\n<p><strong>Or, if you want it in descending order, just reverse it:</strong></p>\n\n<pre><code>File[] files = directory.listFiles();\nArrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());\n</code></pre>\n" }, { "answer_id": 49572642, "author": "Anand Savjani", "author_id": 4749098, "author_profile": "https://Stackoverflow.com/users/4749098", "pm_score": 2, "selected": false, "text": "<pre><code>Collections.sort(listFiles, new Comparator&lt;File&gt;() {\n public int compare(File f1, File f2) {\n return Long.compare(f1.lastModified(), f2.lastModified());\n }\n });\n</code></pre>\n\n<p>where <code>listFiles</code> is the collection of all files in ArrayList</p>\n" }, { "answer_id": 51573553, "author": "user4378029", "author_id": 4378029, "author_profile": "https://Stackoverflow.com/users/4378029", "pm_score": -1, "selected": false, "text": "<p>There is also a completely different way which may be even easier, as we do not deal with large numbers. </p>\n\n<p>Instead of sorting the whole array after you retrieved all filenames and lastModified dates, you can just insert every single filename just after you retrieved it at the right position of the list.</p>\n\n<p>You can do it like this:</p>\n\n<pre><code>list.add(1, object1)\nlist.add(2, object3)\nlist.add(2, object2)\n</code></pre>\n\n<p>After you add object2 to position 2, it will move object3 to position 3. </p>\n" }, { "answer_id": 51590308, "author": "user4378029", "author_id": 4378029, "author_profile": "https://Stackoverflow.com/users/4378029", "pm_score": 0, "selected": false, "text": "<p>There is a very easy and convenient way to handle the problem without any extra comparator. Just code the modified date into the String with the filename, sort it, and later strip it off again.</p>\n\n<p>Use a String of fixed length 20, put the modified date (long) into it, and fill up with leading zeros. Then just append the filename to this string:</p>\n\n<pre><code>String modified_20_digits = (\"00000000000000000000\".concat(Long.toString(temp.lastModified()))).substring(Long.toString(temp.lastModified()).length()); \n\nresult_filenames.add(modified_20_digits+temp.getAbsoluteFile().toString());\n</code></pre>\n\n<p>What happens is this here:</p>\n\n<p>Filename1: C:\\data\\file1.html Last Modified:1532914451455 Last Modified 20 Digits:00000001532914451455</p>\n\n<p>Filename1: C:\\data\\file2.html Last Modified:1532918086822 Last Modified 20 Digits:00000001532918086822</p>\n\n<p>transforms filnames to:</p>\n\n<p>Filename1: 00000001532914451455C:\\data\\file1.html</p>\n\n<p>Filename2: 00000001532918086822C:\\data\\file2.html</p>\n\n<p>You can then just sort this list.</p>\n\n<p>All you need to do is to strip the 20 characters again later (in Java 8, you can strip it for the whole Array with just one line using the .replaceAll function)</p>\n" }, { "answer_id": 63954685, "author": "Ward", "author_id": 1649029, "author_profile": "https://Stackoverflow.com/users/1649029", "pm_score": 0, "selected": false, "text": "<p>A slightly more modernized version of the <a href=\"https://stackoverflow.com/a/4248059/1649029\">answer</a> of @jason-orendorf.</p>\n<p><strong>Note:</strong> this implementation keeps the original array <em>untouched</em>, and returns a <em>new</em> array. This might or might not be desirable.</p>\n<pre><code>files = Arrays.stream(files)\n .map(FileWithLastModified::ofFile)\n .sorted(comparingLong(FileWithLastModified::lastModified))\n .map(FileWithLastModified::file)\n .toArray(File[]::new);\n\nprivate static class FileWithLastModified {\n private final File file;\n private final long lastModified;\n\n private FileWithLastModified(File file, long lastModified) {\n this.file = file;\n this.lastModified = lastModified;\n }\n\n public static FileWithLastModified ofFile(File file) {\n return new FileWithLastModified(file, file.lastModified());\n }\n\n public File file() {\n return file;\n }\n\n public long lastModified() {\n return lastModified;\n }\n}\n</code></pre>\n<p>But again, all credits to @jason-orendorf for the <a href=\"https://stackoverflow.com/a/4248059/1649029\">idea</a>!</p>\n" }, { "answer_id": 68571076, "author": "NoviceCoder", "author_id": 2853499, "author_profile": "https://Stackoverflow.com/users/2853499", "pm_score": 2, "selected": false, "text": "<p>Here's the Kotlin way of doing it if any one is looking for it :</p>\n<pre><code>val filesList = directory.listFiles()\n\nfilesList?.let{ list -&gt;\n Arrays.sort(list) { \n f1, f2 -&gt; f2.lastModified().compareTo(f1.lastModified()) \n }\n}\n</code></pre>\n" }, { "answer_id": 70019349, "author": "shubham chouhan", "author_id": 9955950, "author_profile": "https://Stackoverflow.com/users/9955950", "pm_score": 2, "selected": false, "text": "<p>let array name -&gt; files.</p>\n<hr />\n<pre><code>Ascending -&gt; Arrays.sort(files, (o1, o2) -&gt; Long.compare(o1.lastModified(), o2.lastModified()));\n\nDescending -&gt; Arrays.sort(files, (o1, o2) -&gt; Long.compare(o2.lastModified(), o1.lastModified()));\n</code></pre>\n" }, { "answer_id": 70892622, "author": "josemerazo", "author_id": 18057080, "author_profile": "https://Stackoverflow.com/users/18057080", "pm_score": 0, "selected": false, "text": "<p>In java 6, the best way is:</p>\n<pre><code> File[] listaArchivos = folder.listFiles();\n Arrays.sort(listaArchivos, new Comparator&lt;File&gt;() {\n @Override\n public int compare(File f1, File f2) {\n return (f1.lastModified() &lt; f2.lastModified()) ? -1 : ((f1.lastModified() == f2.lastModified()) ? 0 : 1);\n }\n }); \n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4828/" ]
I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way. Edit: My current solution, as suggested, is to use an anonymous Comparator: ``` File[] files = directory.listFiles(); Arrays.sort(files, new Comparator<File>(){ public int compare(File f1, File f2) { return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); } }); ```
I think your solution is the only sensible way. The only way to get the list of files is to use [File.listFiles()](http://java.sun.com/javase/6/docs/api/java/io/File.html#listFiles()) and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a [Comparator](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) that uses [File.lastModified()](http://java.sun.com/javase/6/docs/api/java/io/File.html#lastModified()) and pass this, along with the array of files, to [Arrays.sort()](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#sort(T[],%20java.util.Comparator)).
203,058
<p>I have a C application that I've created in VS2008. I am creating a mock creation function that overrides function references in a struct. However if I try and do this in a straight forward fashion with something like:</p> <pre><code>void *ptr = &amp;(*env)-&gt;GetVersion; *ptr = &lt;address of new function&gt; </code></pre> <p>then I get a "error C2100: illegal indirection" error as *ptr, when ptr is a void * seems to be a banned construct. I can get around it by using a int/long pointer as well, mapping that to the same address and modifying the contents of the long pointer:</p> <pre><code>*structOffsetPointer = &amp;(*env)-&gt;GetVersion; functionPointer = thisGetVersion; structOffsetPointerAsLong = (long *)structOffsetPointer; *structOffsetPointerAsLong = (long)functionPointer; </code></pre> <p>but I am concerned that using long or int pointers will cause problems if I switch between 32 and 64 bit environments.</p> <p>So is there are easy way to disable this error? Assuming not, is either int or long 64 bits under win64?</p>
[ { "answer_id": 203074, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 1, "selected": false, "text": "<p>Last time I played with void* &amp; C under visual studio, VS didn't play nicely. \nHere are some information datapoints: </p>\n\n<p>A pointer is always the size of the system word(8/16/32/64)...(unless you have segmented memory, which I'm <em>assuming</em> you don't have). This is because it needs to point to anywhere in the memory space. For a <em>von Neumann</em> machine, a function pointer is going to be the same size as a data pointer, because data and code occupy the same memory space. This is not guaranteed under a <em>Harvard</em> architecture. I'm not familiar enough with Windows Vista to know if it programatically fakes out a Harvard architecture for security reasons. </p>\n\n<p>I personally would <em>not</em> disable this error, just for the sake of letting the compiler do its job. </p>\n" }, { "answer_id": 203077, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>As mentioned, to store the address of a function in a pointer you should simply not do the indirection.</p>\n\n<p>However, you also talk about being worried about the size of an int type that you might store a pointer into (which generally is not something you want to do unless you have a really good reason to).</p>\n\n<p>If you want to hold a pointer in an int type for some reason, then on Windows a <code>UINT_PTR</code> type (or <code>uintptr_t</code> from <code>stdint.h</code> if you have it) will hold most pointer types (I don't think it's necessarily large enough to hold some pointer-to-member types).</p>\n" }, { "answer_id": 203093, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 2, "selected": false, "text": "<p>When dereferencing a \"void *\", you are left with a \"void\" which is has no size (or really no type for that matter), so it doesn't know how to assign something to it. It is the same as:</p>\n\n<pre><code>void blah = 0xdeadbabe; // let's assume a 32-bit addressing system\n</code></pre>\n\n<p>To add to my own response and give a solution, I would give it the proper type of a pointer to a function of the type GetVersion is. If GetVersion that your \"env\" struct field is pointing to is:</p>\n\n<pre><code>int GetVersion();\n</code></pre>\n\n<p>then you want:</p>\n\n<pre><code>int (**ptr)() = &amp;(*env)-&gt;GetVersion;\n</code></pre>\n" }, { "answer_id": 203111, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 3, "selected": true, "text": "<p>Then how about:</p>\n\n<pre><code>void **ptr = (void **) &amp;(*env)-&gt;GetVersion;\n*ptr = &lt;address of new function&gt;\n</code></pre>\n\n<p>The right way to do this is to work with the type system, avoid all the casting and declare actual pointers to functions like:</p>\n\n<pre><code>typedef int (*fncPtr)(void);\nfncPtr *ptr = &amp;(*env)-&gt;GetVersion;\n*ptr = NewFunction;\n</code></pre>\n\n<p>The above assumes GetVersion is of type fncPtr and NewFunction is declared as\n int NewFunction(void);</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7122/" ]
I have a C application that I've created in VS2008. I am creating a mock creation function that overrides function references in a struct. However if I try and do this in a straight forward fashion with something like: ``` void *ptr = &(*env)->GetVersion; *ptr = <address of new function> ``` then I get a "error C2100: illegal indirection" error as \*ptr, when ptr is a void \* seems to be a banned construct. I can get around it by using a int/long pointer as well, mapping that to the same address and modifying the contents of the long pointer: ``` *structOffsetPointer = &(*env)->GetVersion; functionPointer = thisGetVersion; structOffsetPointerAsLong = (long *)structOffsetPointer; *structOffsetPointerAsLong = (long)functionPointer; ``` but I am concerned that using long or int pointers will cause problems if I switch between 32 and 64 bit environments. So is there are easy way to disable this error? Assuming not, is either int or long 64 bits under win64?
Then how about: ``` void **ptr = (void **) &(*env)->GetVersion; *ptr = <address of new function> ``` The right way to do this is to work with the type system, avoid all the casting and declare actual pointers to functions like: ``` typedef int (*fncPtr)(void); fncPtr *ptr = &(*env)->GetVersion; *ptr = NewFunction; ``` The above assumes GetVersion is of type fncPtr and NewFunction is declared as int NewFunction(void);
203,090
<p>Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using <code>date</code>. See @npocmaka's <a href="https://stackoverflow.com/a/19799236/8479">https://stackoverflow.com/a/19799236/8479</a></p> <hr> <p>What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?</p> <p>I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, <code>Code_2008-10-14_2257.zip</code>. Is there any easy way I can do this, independent of the regional settings of the machine?</p> <p>I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.</p> <p>So far I've got this, which on my machine gives me <code>Tue_10_14_2008_230050_91</code>:</p> <pre><code>rem Get the datetime in a format that can go in a filename. set _my_datetime=%date%_%time% set _my_datetime=%_my_datetime: =_% set _my_datetime=%_my_datetime::=% set _my_datetime=%_my_datetime:/=_% set _my_datetime=%_my_datetime:.=_% rem Now use the timestamp by in a new ZIP file name. "d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code </code></pre> <p>I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.</p> <p>I'm using Windows Server 2003 and Windows&nbsp;XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).</p>
[ { "answer_id": 203099, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 3, "selected": false, "text": "<p>This is what I've used:</p>\n\n<pre><code>::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like \"backup_04.15.08.7z\")\nSET DT=%date%\nSET DT=%DT:/=.%\nSET DT=%DT:-=.%\n</code></pre>\n\n<hr>\n\n<p>If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: <a href=\"http://wittman.org/ziparcy/\" rel=\"nofollow noreferrer\">http://wittman.org/ziparcy/</a></p>\n" }, { "answer_id": 203108, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 4, "selected": false, "text": "<p>This isn't really briefer but might be a more flexible way (<a href=\"http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/\" rel=\"nofollow noreferrer\">credit</a>):</p>\n\n<pre><code>FOR /F \"TOKENS=1* DELIMS= \" %%A IN ('DATE/T') DO SET CDATE=%%B\nFOR /F \"TOKENS=1,2 eol=/ DELIMS=/ \" %%A IN ('DATE/T') DO SET mm=%%B\nFOR /F \"TOKENS=1,2 DELIMS=/ eol=/\" %%A IN ('echo %CDATE%') DO SET dd=%%B\nFOR /F \"TOKENS=2,3 DELIMS=/ \" %%A IN ('echo %CDATE%') DO SET yyyy=%%B\nSET date=%mm%%dd%%yyyy%\n</code></pre>\n" }, { "answer_id": 203115, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 4, "selected": false, "text": "<p>Another way (<a href=\"http://weblogs.asp.net/whaggard/archive/2005/08/18/423029.aspx\" rel=\"noreferrer\">credit</a>):</p>\n\n<pre><code>@For /F \"tokens=2,3,4 delims=/ \" %%A in ('Date /t') do @( \n Set Month=%%A\n Set Day=%%B\n Set Year=%%C\n)\n\n@echo DAY = %Day%\n@echo Month = %Month%\n@echo Year = %Year%\n</code></pre>\n\n<p>Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.</p>\n" }, { "answer_id": 203116, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 11, "selected": true, "text": "<p>See <em><a href=\"http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/\" rel=\"noreferrer\">Windows Batch File (.bat) to get current date in MMDDYYYY format</a></em>:</p>\n\n<pre><code>@echo off\nFor /f \"tokens=2-4 delims=/ \" %%a in ('date /t') do (set mydate=%%c-%%a-%%b)\nFor /f \"tokens=1-2 delims=/:\" %%a in ('time /t') do (set mytime=%%a%%b)\necho %mydate%_%mytime%\n</code></pre>\n\n<p>If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:</p>\n\n<pre><code>For /f \"tokens=1-2 delims=/:\" %%a in (\"%TIME%\") do (set mytime=%%a%%b)\n</code></pre>\n\n<blockquote>\n <p>C:> .\\date.bat <br />\n 2008-10-14_0642</p>\n</blockquote>\n\n<p>If you want the date independently of the region day/month order, you can use \"WMIC os GET LocalDateTime\" as a source, since it's in ISO order:</p>\n\n<pre><code>@echo off\nfor /F \"usebackq tokens=1,2 delims==\" %%i in (`wmic os get LocalDateTime /VALUE 2^&gt;NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j\nset ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%\necho Local date is [%ldt%]\n</code></pre>\n\n<blockquote>\n <p>C:>test.cmd<br />\n Local date is [2012-06-19 10:23:47.048]</p>\n</blockquote>\n" }, { "answer_id": 203127, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "<p>Unfortunately this is not immune to regional settings, but it does what you want.</p>\n\n<pre><code>set hour=%time:~0,2%\nif \"%time:~0,1%\"==\" \" set hour=0%time:~1,1%\nset _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%\n</code></pre>\n\n<p>Amazing the stuff you can find on <a href=\"http://en.wikipedia.org/wiki/Environment_variable\" rel=\"noreferrer\">Wikipedia</a>.</p>\n" }, { "answer_id": 741748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>I use this (again not region independent (UK))</p>\n\n<pre><code>set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%\n</code></pre>\n" }, { "answer_id": 1849224, "author": "DigiP", "author_id": 225031, "author_profile": "https://Stackoverflow.com/users/225031", "pm_score": 4, "selected": false, "text": "<pre><code>\"d:\\Program Files\\7-Zip\\7z.exe\" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip\n</code></pre>\n" }, { "answer_id": 1951681, "author": "Uri Liebeskind", "author_id": 237474, "author_profile": "https://Stackoverflow.com/users/237474", "pm_score": 7, "selected": false, "text": "<h3>Regionally independent date time parsing</h3>\n\n<p>The output format of <code>%DATE%</code> and of the <code>dir</code> command is regionally dependent and thus neither robust nor smart. <a href=\"http://sourceforge.net/projects/unxutils/files/\" rel=\"noreferrer\">date.exe</a> (part of <a href=\"http://en.wikipedia.org/wiki/UnxUtils\" rel=\"noreferrer\">UnxUtils</a>) delivers any date and time information in any thinkable format. You may also extract the date/time information from any file with <code>date.exe</code>.</p>\n\n<h3>Examples: (in a cmd-script use %% instead of %)</h3>\n\n<p><code>date.exe +\"%Y-%m-%d\"</code><br>\n2009-12-22 </p>\n\n<p><code>date.exe +\"%T\"</code><br>\n18:55:03 </p>\n\n<p><code>date.exe +\"%Y%m%d %H%M%S: Any text\"</code><br>\n20091222 185503: Any text</p>\n\n<p><code>date.exe +\"Text: %y/%m/%d-any text-%H.%M\"</code><br>\nText: 09/12/22-any text-18.55</p>\n\n<p><code>Command: date.exe +\"%m-%d \"\"\"%H %M %S \"\"\"\"</code><br>\n07-22 \"18:55:03\"`</p>\n\n<p>The date/time information from a reference file:<br>\n<code>date.exe -r c:\\file.txt +\"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S\"</code></p>\n\n<p>Using it in a CMD script to get year, month, day, time information:</p>\n\n<pre><code>for /f \"tokens=1,2,3,4,5,6* delims=,\" %%i in ('C:\\Tools\\etc\\date.exe +\"%%y,%%m,%%d,%%H,%%M,%%S\"') do set yy=%%i&amp; set mo=%%j&amp; set dd=%%k&amp; set hh=%%l&amp; set mm=%%m&amp; set ss=%%n\n</code></pre>\n\n<p>Using it in a CMD script to get a timestamp in any required format:</p>\n\n<pre><code>for /f \"tokens=*\" %%i in ('C:\\Tools\\etc\\date.exe +\"%%y-%%m-%%d %%H:%%M:%%S\"') do set timestamp=%%i\n</code></pre>\n\n<p>Extracting the date/time information from any reference file.</p>\n\n<pre><code>for /f \"tokens=1,2,3,4,5,6* delims=,\" %%i in ('C:\\Tools\\etc\\date.exe -r file.txt +\"%%y,%%m,%%d,%%H,%%M,%%S\"') do set yy=%%i&amp; set mo=%%j&amp; set dd=%%k&amp; set hh=%%l&amp; set mm=%%m&amp; set ss=%%n\n</code></pre>\n\n<p>Adding to a file its date/time information:</p>\n\n<pre><code>for /f \"tokens=*\" %%i in ('C:\\Tools\\etc\\date.exe -r file.txt +\"%%y-%%m-%%d.%%H%%M%%S\"') do ren file.txt file.%%i.txt\n</code></pre>\n\n<p>date.exe is <a href=\"http://sourceforge.net/projects/unxutils/files/\" rel=\"noreferrer\">part of the free GNU tools</a> which need no installation.</p>\n\n<p>NOTE: Copying <code>date.exe</code> into any directory which is in the search path may cause other scripts to fail that use the Windows built-in <code>date</code> command.</p>\n" }, { "answer_id": 2854857, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 4, "selected": false, "text": "<p>Short answer : </p>\n\n<pre><code> :: Start - Run , type:\n cmd /c \"powershell get-date -format ^\"{yyyy-MM-dd HH:mm:ss}^\"|clip\"\n\n :: click into target media, Ctrl + V to paste the result \n</code></pre>\n\n<p>Long answer</p>\n\n<pre><code> @echo off\n :: START USAGE ==================================================================\n ::SET THE NICETIME \n :: SET NICETIME=BOO\n :: CALL GetNiceTime.cmd \n\n :: ECHO NICETIME IS %NICETIME%\n\n :: echo nice time is %NICETIME%\n :: END USAGE ==================================================================\n\n echo set hhmmsss\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=:\" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c \n ::DEBUG ECHO hhmmsss IS %hhmmsss%\n ::DEBUG PAUSE\n echo %yyyymmdd%\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=.\" %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D\n ::DEBUG ECHO yyyymmdd IS %yyyymmdd%\n ::DEBUG PAUSE\n\n\n set NICETIME=%yyyymmdd%_%hhmmsss%\n ::DEBUG echo THE NICETIME IS %NICETIME%\n\n ::DEBUG PAUSE\n</code></pre>\n" }, { "answer_id": 3202796, "author": "vMax", "author_id": 386539, "author_profile": "https://Stackoverflow.com/users/386539", "pm_score": 6, "selected": false, "text": "<p>Here's a variant from alt.msdos.batch.nt that works local-independently.</p>\n\n<p>Put this in a text file, e.g. getDate.cmd</p>\n\n<pre><code>-----------8&lt;------8&lt;------------ snip -- snip ----------8&lt;-------------\n :: Works on any NT/2k machine independent of regional date settings\n @ECHO off\n SETLOCAL ENABLEEXTENSIONS\n if \"%date%A\" LSS \"A\" (set toks=1-3) else (set toks=2-4)\n for /f \"tokens=2-4 delims=(-)\" %%a in ('echo:^|date') do (\n for /f \"tokens=%toks% delims=.-/ \" %%i in ('date/t') do (\n set '%%a'=%%i\n set '%%b'=%%j\n set '%%c'=%%k))\n if %'yy'% LSS 100 set 'yy'=20%'yy'%\n set Today=%'yy'%-%'mm'%-%'dd'% \n ENDLOCAL &amp; SET v_year=%'yy'%&amp; SET v_month=%'mm'%&amp; SET v_day=%'dd'%\n\n ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]\n\n :EOF\n-----------8&lt;------8&lt;------------ snip -- snip ----------8&lt;-------------\n</code></pre>\n\n<p>To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like \"set =20\" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.</p>\n\n<p>The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!</p>\n" }, { "answer_id": 3859042, "author": "Matthew Johnson", "author_id": 466219, "author_profile": "https://Stackoverflow.com/users/466219", "pm_score": 3, "selected": false, "text": "<p>Here's a way to get date time in a single line:</p>\n\n<pre><code>for /f \"tokens=2,3,4,5,6 usebackq delims=:/ \" %a in ('%date% %time%') do echo %c-%a-%b %d%e\n</code></pre>\n\n<p>In the US this will output \"yyyy-mm-dd hhmm\". Different regional settings will result in different %date% outputs, but you can modify the token order.</p>\n\n<p>If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.</p>\n" }, { "answer_id": 4061880, "author": "Sally", "author_id": 478885, "author_profile": "https://Stackoverflow.com/users/478885", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://sourceforge.net/projects/unxutils/files/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/unxutils/files/</a></p>\n\n<p>Look inside the ZIP file for something called \"Date.exe\" and rename it \"DateFormat.exe\" (to avoid conflicts).</p>\n\n<p>Put it in your Windows system32 folder.</p>\n\n<p>It has a lot of \"date output\" options.</p>\n\n<p>For help, use <code>DateFormat.exe --h</code></p>\n\n<p>I'm not sure how you would put its output into an environment variable... using SET.</p>\n" }, { "answer_id": 4584577, "author": "Jeroen Wiert Pluimers", "author_id": 29290, "author_profile": "https://Stackoverflow.com/users/29290", "pm_score": 3, "selected": false, "text": "<p>I changed <a href=\"https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi/3202796#3202796\">the answer</a> with the batch file from <a href=\"https://stackoverflow.com/users/386539/vmax\">vMax</a> so it works with the Dutch language too.<br>\nThe Dutch - persistent as we are - have a few changes in the <code>%date%</code>, <code>date/t</code>, and <code>date</code> that break the original batch-file.</p>\n\n<p>It would be nice if some people can check this against other Windows locales as well, and report back the results.<br>\nIf the batch-file fails at your location, then please include the output of these two statements on the command prompt:<br>\n<code>echo:^|date</code><br>\n<code>date/t</code> </p>\n\n<p>This is a sample of the output you should get from the batch-file:</p>\n\n<pre><code>C:\\temp&gt;set-date-cmd.bat\nToday is Year: [2011] Month: [01] Day: [03]\n20110103\n</code></pre>\n\n<p>Here is the revised code with comments on why:</p>\n\n<pre><code>:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi\n:: Works on any NT/2k machine independent of regional date settings\n::\n:: 20110103 - adapted by [email protected] for Dutch locale\n:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'\n:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date\n:: set '%%c'=%%k\n:: set 'yy'=%%k\n::\n:: In addition, date will display the current date before the input prompt using dashes\n:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch\n:: and one occurence in English.\n:: This skips the first iteration:\n:: if \"%%a\" GEQ \"A\"\n::\n:: echo:^|date\n:: Huidige datum: ma 03-01-2011\n:: Voer de nieuwe datum in: (dd-mm-jj)\n:: The current date is: Mon 01/03/2011\n:: Enter the new date: (mm-dd-yy)\n::\n:: date/t\n:: ma 03-01-2011\n:: Mon 01/03/2011\n::\n:: The assumption in this batch-file is that echo:^|date will return the date format\n:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.\n::\n:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.\n:: That will resolve the order of the tokens.\n::\n@ECHO off\n set v_day=\n set v_month=\n set v_year=\n\n SETLOCAL ENABLEEXTENSIONS\n if \"%date%A\" LSS \"A\" (set toks=1-3) else (set toks=2-4)\n::DEBUG echo toks=%toks%\n for /f \"tokens=2-4 delims=(-)\" %%a in ('echo:^|date') do (\n::DEBUG echo first token=%%a\n if \"%%a\" GEQ \"A\" (\n for /f \"tokens=%toks% delims=.-/ \" %%i in ('date/t') do (\n set '%%a'=%%i\n set '%%b'=%%j\n set 'yy'=%%k\n )\n )\n )\n if %'yy'% LSS 100 set 'yy'=20%'yy'%\n set Today=%'yy'%-%'mm'%-%'dd'%\n\n ENDLOCAL &amp; SET v_year=%'yy'%&amp; SET v_month=%'mm'%&amp; SET v_day=%'dd'%\n\n ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]\n set datestring=%V_Year%%V_Month%%V_Day%\n echo %datestring%\n\n :EOF\n</code></pre>\n\n<p>--jeroen</p>\n" }, { "answer_id": 4584820, "author": "Jeroen Wiert Pluimers", "author_id": 29290, "author_profile": "https://Stackoverflow.com/users/29290", "pm_score": 3, "selected": false, "text": "<p>And here is a similar batch-file for the time portion. </p>\n\n<pre><code>:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi\n:: Works on any NT/2k machine independent of regional time settings\n::\n:: Gets the time in ISO 8601 24-hour format\n::\n:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.\n:: Since ISO 8601 does not care about AM/PM, we use %time%\n::\n @ECHO off\n SETLOCAL ENABLEEXTENSIONS\n for /f \"tokens=1-4 delims=:,.-/ \" %%i in ('echo %time%') do (\n set 'hh'=%%i\n set 'mm'=%%j\n set 'ss'=%%k\n set 'ff'=%%l)\n ENDLOCAL &amp; SET v_Hour=%'hh'%&amp; SET v_Minute=%'mm'%&amp; SET v_Second=%'ss'%&amp; SET v_Fraction=%'ff'%\n\n ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]\n set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%\n echo %timestring%\n\n :EOF\n</code></pre>\n\n<p>--jeroen</p>\n" }, { "answer_id": 6348634, "author": "KChiki", "author_id": 798300, "author_profile": "https://Stackoverflow.com/users/798300", "pm_score": 3, "selected": false, "text": "<p>I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.</p>\n\n<p>I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.</p>\n\n<pre><code>for /f \"tokens=1-5 delims=/ \" %%d in (\"%date%\") do rename \"decrypted.txt\" %%g-%%e-%%f.txt\n</code></pre>\n\n<p>It worked perfectly (i.e., the filename comes out as \"2011-06-14.txt\").</p>\n\n<p><a href=\"http://www.computerhope.com/issues/ch000987.htm\" rel=\"nofollow\">(Source)</a></p>\n" }, { "answer_id": 6707326, "author": "sudipto roy", "author_id": 846495, "author_profile": "https://Stackoverflow.com/users/846495", "pm_score": 5, "selected": false, "text": "<p>Please use the following script to get the current day in the command line:</p>\n\n<pre><code>echo %Date:~0,3%day\n</code></pre>\n" }, { "answer_id": 7319693, "author": "V15I0N", "author_id": 930610, "author_profile": "https://Stackoverflow.com/users/930610", "pm_score": 2, "selected": false, "text": "<p>Regional independent solution generating the ISO date format:</p>\n\n<pre><code>rem save the existing format definition\nfor /f \"skip=2 tokens=3\" %%a in ('reg query \"HKCU\\Control Panel\\International\" /v sShortDate') do set FORMAT=%%a\nrem set ISO specific format definition\nreg add \"HKCU\\Control Panel\\International\" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1&gt;nul:\nrem query the date in the ISO specific format \nset ISODATE=%DATE%\nrem restore previous format definition\nreg add \"HKCU\\Control Panel\\International\" /v sShortDate /t REG_SZ /f /d %FORMAT% 1&gt;nul:\n</code></pre>\n\n<p>What could still be optimized:\nOther processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated</p>\n" }, { "answer_id": 16264795, "author": "John Langstaff", "author_id": 714326, "author_profile": "https://Stackoverflow.com/users/714326", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/3859042/2657515\"><strong>Matthew Johnson's</strong> one-liner solution</a> to get the one-liner date and time is <em>eloquent</em> and useful.</p>\n\n<p>It does however need a simple modification to work from within a batch file:</p>\n\n<pre><code>for /f \"tokens=2,3,4,5,6 usebackq delims=:/ \" %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e\n</code></pre>\n" }, { "answer_id": 19799236, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 7, "selected": false, "text": "<p>Two more ways that do not depend on the time settings (both taken from <a href=\"http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=4555\" rel=\"noreferrer\">:How get data/time independent from localization:</a>). And both also get the day of the week and none of them requires admin permissions!:</p>\n\n<ol>\n<li><p><strong>MAKECAB</strong> - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):</p>\n\n<pre><code>@echo off\npushd \"%temp%\"\nmakecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul &gt;nul\nfor /f \"tokens=3-7\" %%a in ('find /i \"makecab\"^&lt;~.rpt') do (\n set \"current-date=%%e-%%b-%%c\"\n set \"current-time=%%d\"\n set \"weekday=%%a\"\n)\ndel ~.*\npopd\necho %weekday% %current-date% %current-time%\npause\n</code></pre>\n\n<p><a href=\"http://ss64.com/ps/get-date.html\" rel=\"noreferrer\">More information about get-date function</a>.</p></li>\n<li><p><strong>ROBOCOPY</strong> - it's not native command for Windows&nbsp;XP and Windows Server 2003, but it can be <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=17657\" rel=\"noreferrer\">downloaded from microsoft site</a>. But is built-in in everything from Windows&nbsp;Vista and above:</p>\n\n<pre><code>@echo off\nsetlocal\nfor /f \"skip=8 tokens=2,3,4,5,6,7,8 delims=: \" %%D in ('robocopy /l * \\ \\ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (\n set \"dow=%%D\"\n set \"month=%%E\"\n set \"day=%%F\"\n set \"HH=%%G\"\n set \"MM=%%H\"\n set \"SS=%%I\"\n set \"year=%%J\"\n)\n\necho Day of the week: %dow%\necho Day of the month : %day%\necho Month : %month%\necho hour : %HH%\necho minutes : %MM%\necho seconds : %SS%\necho year : %year%\nendlocal\n</code></pre>\n\n<p>And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.</p></li>\n<li><p><strong>JScript/batch</strong> hybrid (need to be saved as <code>.bat</code>). JScript is available on every system form NT and above, as a part of <a href=\"http://en.wikipedia.org/wiki/Windows_Script_Host\" rel=\"noreferrer\">Windows Script Host</a> (<a href=\"http://technet.microsoft.com/en-us/library/ee198684.aspx\" rel=\"noreferrer\">though can be disabled through the registry it's a rare case</a>):</p>\n\n<pre><code>@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment\n\n@echo off\ncscript //E:JScript //nologo \"%~f0\"\nexit /b 0\n*------------------------------------------------------------------------------*/\n\nfunction GetCurrentDate() {\n // Today date time which will used to set as default date.\n var todayDate = new Date();\n todayDate = todayDate.getFullYear() + \"-\" +\n (\"0\" + (todayDate.getMonth() + 1)).slice(-2) + \"-\" +\n (\"0\" + todayDate.getDate()).slice(-2) + \" \" + (\"0\" + todayDate.getHours()).slice(-2) + \":\" +\n (\"0\" + todayDate.getMinutes()).slice(-2);\n\n return todayDate;\n }\n\nWScript.Echo(GetCurrentDate());\n</code></pre></li>\n<li><p><strong>VSCRIPT/BATCH</strong> hybrid (<em><a href=\"https://stackoverflow.com/questions/9074476/is-it-possible-to-embed-and-execute-vbscript-within-a-batch-file-without-using-a\">Is it possible to embed and execute VBScript within a batch file without using a temporary file?</a></em>) same case as JScript, but hybridization is not so perfect:</p>\n\n<pre><code>:sub echo(str) :end sub\necho off\n'&gt;nul 2&gt;&amp;1|| copy /Y %windir%\\System32\\doskey.exe %windir%\\System32\\'.exe &gt;nul\n'&amp; echo current date:\n'&amp; cscript /nologo /E:vbscript \"%~f0\"\n'&amp; exit /b\n\n'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.\n'1 = vbLongDate - Returns date: weekday, monthname, year\n'2 = vbShortDate - Returns date: mm/dd/yy\n'3 = vbLongTime - Returns time: hh:mm:ss PM/AM\n'4 = vbShortTime - Return time: hh:mm\n\nWScript.echo Replace(FormatDateTime(Date,1),\", \",\"-\")\n</code></pre></li>\n<li><p><strong>PowerShell</strong> - can be installed on every machine that has .NET - download from Microsoft (<a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=7217\" rel=\"noreferrer\">v1</a>, <a href=\"http://support.microsoft.com/kb/968929/bg\" rel=\"noreferrer\">v2</a>, <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=34595\" rel=\"noreferrer\">v3</a> (only for Windows&nbsp;7 and above)). It is installed by default on everything from Windows&nbsp;7/Windows Server 2008 and above:</p>\n\n<pre><code>C:\\&gt; powershell get-date -format \"{dd-MMM-yyyy HH:mm}\"\n</code></pre>\n\n<p>To use it from a batch file:</p>\n\n<pre><code>for /f \"delims=\" %%# in ('powershell get-date -format \"{dd-MMM-yyyy HH:mm}\"') do @set _date=%%#\n</code></pre></li>\n<li><p><strong>Self-compiled jscript.net/batch</strong> (never seen a Windows machine without .NET, so I think this is a pretty portable):</p>\n\n<pre><code>@if (@X)==(@Y) @end /****** silent line that start JScript comment ******\n\n@echo off\n::::::::::::::::::::::::::::::::::::\n::: Compile the script ::::\n::::::::::::::::::::::::::::::::::::\nsetlocal\nif exist \"%~n0.exe\" goto :skip_compilation\n\nset \"frm=%SystemRoot%\\Microsoft.NET\\Framework\\\"\n\n:: Searching the latest installed .NET framework\nfor /f \"tokens=* delims=\" %%v in ('dir /b /s /a:d /o:-n \"%SystemRoot%\\Microsoft.NET\\Framework\\v*\"') do (\n if exist \"%%v\\jsc.exe\" (\n rem :: the javascript.net compiler\n set \"jsc=%%~dpsnfxv\\jsc.exe\"\n goto :break_loop\n )\n)\necho jsc.exe not found &amp;&amp; exit /b 0\n:break_loop\n\n\ncall %jsc% /nologo /out:\"%~n0.exe\" \"%~dpsfnx0\"\n::::::::::::::::::::::::::::::::::::\n::: End of compilation ::::\n::::::::::::::::::::::::::::::::::::\n:skip_compilation\n\n\"%~n0.exe\"\n\nexit /b 0\n\n\n****** End of JScript comment ******/\nimport System;\nimport System.IO;\n\nvar dt=DateTime.Now;\nConsole.WriteLine(dt.ToString(\"yyyy-MM-dd hh:mm:ss\"));\n</code></pre></li>\n<li><p><strong>Logman</strong> This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows&nbsp;XP and above. It probably will be never used by anybody - including me - but is one more way...</p>\n\n<pre><code>@echo off\nsetlocal\ndel /q /f %temp%\\timestampfile_*\n\nLogman.exe stop ts-CPU 1&gt;nul 2&gt;&amp;1\nLogman.exe delete ts-CPU 1&gt;nul 2&gt;&amp;1\n\nLogman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c \"\\Processor(_Total)\\%% Processor Time\" -o %temp%\\timestampfile_ &gt;nul\nLogman.exe start ts-CPU 1&gt;nul 2&gt;&amp;1\n\nLogman.exe stop ts-CPU &gt;nul 2&gt;&amp;1\nLogman.exe delete ts-CPU &gt;nul 2&gt;&amp;1\nfor /f \"tokens=2 delims=_.\" %%t in ('dir /b %temp%\\timestampfile_*^&amp;del /q/f %temp%\\timestampfile_*') do set timestamp=%%t\n\necho %timestamp%\necho MM: %timestamp:~0,2%\necho dd: %timestamp:~2,2%\necho hh: %timestamp:~4,2%\necho mm: %timestamp:~6,2%\n\nendlocal\nexit /b 0\n</code></pre></li>\n<li><p>One more way with <strong>WMIC</strong> which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):</p>\n\n<pre><code>for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in (\"%%#\") do @set %%@\necho %day%\necho %DayOfWeek%\necho %hour%\necho %minute%\necho %month%\necho %quarter%\necho %second%\necho %weekinmonth%\necho %year%\n</code></pre></li>\n<li><p>Using <strong><a href=\"http://ss64.com/nt/typeperf.html\" rel=\"noreferrer\">TYPEPERF</a></strong> with some efforts to be fast and compatible with different language settings and as fast as possible:</p>\n\n<pre><code>@echo off\nsetlocal\n\n:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance\n::if defined USERDOMAIN_roamingprofile (set \"v=v4\") else (set \"v=\")\n\nfor /f \"tokens=4 delims=. \" %%# in ('ver') do if %%# GTR 5 (set \"v=v4\") else (\"v=\")\nset \"mon=\"\nfor /f \"skip=2 delims=,\" %%# in ('typeperf \"\\UDP%v%\\*\" -si 0 -sc 1') do (\n if not defined mon (\n for /f \"tokens=1-7 delims=.:/ \" %%a in (%%#) do (\n set mon=%%a\n set date=%%b\n set year=%%c\n set hour=%%d\n set minute=%%e\n set sec=%%f\n set ms=%%g\n )\n )\n)\necho %year%.%mon%.%date%\necho %hour%:%minute%:%sec%.%ms%\nendlocal\n</code></pre></li>\n<li><p><strong>MSHTA</strong> allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.</p>\n\n<pre><code>&lt;!-- : Batch portion\n\n@echo off\nsetlocal\n\nfor /f \"delims=\" %%I in ('mshta \"%~f0\"') do set \"now.%%~I\"\n\nrem Display all variables beginning with \"now.\"\nset now.\n\ngoto :EOF\n\nend batch / begin HTA --&gt;\n\n&lt;script&gt;\n resizeTo(0,0)\n var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),\n now = new Date(),\n props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',\n 'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',\n 'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',\n 'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',\n 'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],\n output = [];\n\n for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}\n close(fso.Write(output.join('\\n')));\n&lt;/script&gt;\n</code></pre></li>\n</ol>\n" }, { "answer_id": 21282321, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<p>A function that is based on <code>wmic</code>:</p>\n\n<pre><code>:Now -- Gets the current date and time into separate variables\n:: %~1: [out] Year\n:: %~2: [out] Month\n:: %~3: [out] Day\n:: %~4: [out] Hour\n:: %~5: [out] Minute\n:: %~6: [out] Second\n setlocal\n for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t\n endlocal &amp; (\n if \"%~1\" neq \"\" set %~1=%T:~0,4%\n if \"%~2\" neq \"\" set %~2=%T:~4,2%\n if \"%~3\" neq \"\" set %~3=%T:~6,2%\n if \"%~4\" neq \"\" set %~4=%T:~8,2%\n if \"%~5\" neq \"\" set %~5=%T:~10,2%\n if \"%~6\" neq \"\" set %~6=%T:~12,2%\n )\ngoto:eof\n</code></pre>\n\n<p><strong>Upside:</strong> Region independent. <strong>Downside:</strong> Only system administrators can run wmic.exe.</p>\n\n<p>Usage:</p>\n\n<pre><code>call:Now Y M D H N S\necho %Y%-%M%-%D% %H%:%N%:%S%\n</code></pre>\n\n<p>This echos a string like this:</p>\n\n<pre><code>2014-01-22 12:51:53\n</code></pre>\n\n<p>Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.</p>\n\n<p>All parameters are optional, so <code>call:Now Y M</code> is a valid call if you only want to get year and month.</p>\n" }, { "answer_id": 25714111, "author": "foxidrive", "author_id": 2299431, "author_profile": "https://Stackoverflow.com/users/2299431", "pm_score": 5, "selected": false, "text": "<p>The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows&nbsp;XP Professional and higher.</p>\n\n<pre><code>@echo off\nfor /f \"tokens=2 delims==\" %%a in ('wmic OS Get localdatetime /value') do set \"dt=%%a\"\nset \"YY=%dt:~2,2%\" &amp; set \"YYYY=%dt:~0,4%\" &amp; set \"MM=%dt:~4,2%\" &amp; set \"DD=%dt:~6,2%\"\nset \"HH=%dt:~8,2%\" &amp; set \"Min=%dt:~10,2%\" &amp; set \"Sec=%dt:~12,2%\"\n\nset \"datestamp=%YYYY%%MM%%DD%\" &amp; set \"timestamp=%HH%%Min%%Sec%\" &amp; set \"fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%\"\necho datestamp: \"%datestamp%\"\necho timestamp: \"%timestamp%\"\necho fullstamp: \"%fullstamp%\"\npause\n</code></pre>\n" }, { "answer_id": 27012486, "author": "gdelfino", "author_id": 93947, "author_profile": "https://Stackoverflow.com/users/93947", "pm_score": 3, "selected": false, "text": "<p>Just use this line:</p>\n\n<pre><code>PowerShell -Command \"get-date\"\n</code></pre>\n" }, { "answer_id": 38905219, "author": "bvj", "author_id": 241296, "author_profile": "https://Stackoverflow.com/users/241296", "pm_score": -1, "selected": false, "text": "<p>Given a known locality, for reference in functional form. The <code>ECHOTIMESTAMP</code> call shows how to get the timestamp into a variable (<code>DTS</code> in this example.)</p>\n\n<pre><code>@ECHO off\n\nCALL :ECHOTIMESTAMP\nGOTO END\n\n:TIMESTAMP\nSETLOCAL EnableDelayedExpansion\n SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!\n SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!\n SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!\nENDLOCAL &amp; SET \"%~1=%DTS%\"\nGOTO :EOF\n\n:ECHOTIMESTAMP\nSETLOCAL\n CALL :TIMESTAMP DTS\n ECHO %DTS%\nENDLOCAL\nGOTO :EOF\n\n:END\n\nEXIT /b 0\n</code></pre>\n\n<p>And saved to file, timestamp.bat, here's the output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/zc1ZI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zc1ZI.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 38958529, "author": "NotepadPlusPlus PRO", "author_id": 2920692, "author_profile": "https://Stackoverflow.com/users/2920692", "pm_score": -1, "selected": false, "text": "<p>I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>:: Check your local date format\necho %date%\n\n :: Output is Mon 08/15/2016\n\n:: get day (start index, number of characters)\n:: (index starts with zero)\nset myday=%DATE:~0,4%\necho %myday%\n :: output is Mon \n\n:: get month\nset mymonth=%DATE:~4,2%\necho %mymonth%\n :: output is 08\n\n:: get date \nset mydate=%DATE:~7,2% \necho %mydate%\n :: output is 15\n\n:: get year\nset myyear=%DATE:~10,4%\necho %myyear%\n :: output is 2016\n</code></pre>\n" }, { "answer_id": 38972828, "author": "Frizz1977", "author_id": 1794049, "author_profile": "https://Stackoverflow.com/users/1794049", "pm_score": -1, "selected": false, "text": "<p>With Windows 7, this code works for me:</p>\n\n<pre><code>SET DATE=%date%\nSET YEAR=%DATE:~0,4%\nSET MONTH=%DATE:~5,2%\nSET DAY=%DATE:~8,2%\nECHO %YEAR%\nECHO %MONTH%\nECHO %DAY%\n\nSET DATE_FRM=%YEAR%-%MONTH%-%DAY% \nECHO %DATE_FRM%\n</code></pre>\n" }, { "answer_id": 43903620, "author": "Adolfo", "author_id": 3075331, "author_profile": "https://Stackoverflow.com/users/3075331", "pm_score": 2, "selected": false, "text": "<pre><code>:: GetDate.cmd -&gt; Uses WMIC.exe to get current date and time in ISO 8601 format\n:: - Sets environment variables %_isotime% and %_now% to current time\n:: - On failure, clears these environment variables\n:: Inspired on -&gt; https://ss64.com/nt/syntax-getdate.html\n:: - (cX) 2017 [email protected]\n:: - http://stackoverflow.com/questions/203090\n@echo off\n\nset _isotime=\nset _now=\n\n:: Check that WMIC.exe is available\nWMIC.exe Alias /? &gt;NUL 2&gt;&amp;1 || goto _WMIC_MISSING_\n\nif not (%1)==() goto _help\nSetLocal EnableDelayedExpansion\n\n:: Use WMIC.exe to retrieve date and time\nFOR /F \"skip=1 tokens=1-6\" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (\n IF \"%%~L\"==\"\" goto _WMIC_done_\n set _yyyy=%%L\n set _mm=00%%J\n set _dd=00%%G\n set _hour=00%%H\n set _minute=00%%I\n set _second=00%%K\n)\n:_WMIC_done_\n\n:: 1 2 3 4 5 6\n:: %%G %%H %%I %%J %%K %%L\n:: Day Hour Minute Month Second Year\n:: 27 9 35 4 38 2017\n\n:: Remove excess leading zeroes\n set _mm=%_mm:~-2%\n set _dd=%_dd:~-2%\n set _hour=%_hour:~-2%\n set _minute=%_minute:~-2%\n set _second=%_second:~-2%\n:: Syntax -&gt; %variable:~num_chars_to_skip,num_chars_to_keep%\n\n:: Set date/time in ISO 8601 format:\n Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%\n:: -&gt; http://google.com/search?num=100&amp;q=ISO+8601+format\n\nif 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am\nif 1%_hour% LSS 112 goto _skip_12_\n set /a _hour=1%_hour%-12\n set _hour=%_hour:~-2%\n set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm\n :: -&gt; https://ss64.com/nt/if.html\n :: -&gt; http://google.com/search?num=100&amp;q=SetLocal+EndLocal+Windows\n :: 'if () else ()' will NOT set %_now% correctly !?\n:_skip_12_\n\nEndLocal &amp; set _isotime=%_isotime% &amp; set _now=%_now%\ngoto _out\n\n:_WMIC_MISSING_\necho.\necho WMIC.exe command not available\necho - WMIC.exe needs Administrator privileges to run in Windows\necho - Usually the path to WMIC.exe is \"%windir%\\System32\\wbem\\WMIC.exe\"\n\n:_help\necho.\necho GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format\necho.\necho %%_now%% environment variable set to current date and time\necho %%_isotime%% environment variable to current time in ISO format\necho set _today=%%_isotime:~0,10%%\necho.\n\n:_out\n:: EOF: GetDate.cmd\n</code></pre>\n" }, { "answer_id": 53649000, "author": "Ed999", "author_id": 1863462, "author_profile": "https://Stackoverflow.com/users/1863462", "pm_score": -1, "selected": false, "text": "<p>I note that the o/p did <strong>not</strong> ask for a region-independent solution. My solution is for the UK though.</p>\n<p>This is the simplest possible solution, a 1-line solution, for use in a Batch file:</p>\n<pre><code>FOR /F &quot;tokens=1-3 delims=/&quot; %%A IN (&quot;%date%&quot;) DO (SET today=%%C-%%B-%%A)\necho %today%\n</code></pre>\n<p>This solution can be varied, by altering the order of the variables %%A %%B and %%C in the output statement, to provide any date format desired (e.g. YY-MM-DD or DD-MM-YY).</p>\n<p>My intention - my <strong>ONLY</strong> intention - in posting this answer is to demonstrate that this can be done on the <strong>command line</strong>, by using a <em>single</em> line of code to achieve it.</p>\n<p>And that it is redundant to post answers running to 35 lines of code, as others have done, because the o/p specifically asked for a <strong>command line</strong> solution in the question. Therefore the o/p specifically sought a single-line solution.</p>\n" }, { "answer_id": 62874781, "author": "Gerhard", "author_id": 7818749, "author_profile": "https://Stackoverflow.com/users/7818749", "pm_score": 2, "selected": false, "text": "<p>Combine <code>Powershell</code> into a batch file and use the meta variables to assign each:</p>\n<pre><code>@echo off\nfor /f &quot;tokens=1-6 delims=-&quot; %%a in ('PowerShell -Command &quot;&amp; {Get-Date -format &quot;yyyy-MM-dd-HH-mm-ss&quot;}&quot;') do (\n echo year: %%a\n echo month: %%b\n echo day: %%c\n echo hour: %%d\n echo minute: %%e\n echo second: %%f\n)\n</code></pre>\n<p>You can also change the the format if you prefer name of the month <code>MMM</code> or <code>MMMM</code> and 12 hour to 24 hour formats <code>hh</code> or <code>HH</code></p>\n" }, { "answer_id": 65943831, "author": "om-ha", "author_id": 10830091, "author_profile": "https://Stackoverflow.com/users/10830091", "pm_score": 0, "selected": false, "text": "<ul>\n<li><p>I used <code>date.exe</code>, and renamed it to <code>date_unxutils.exe</code> to avoid conflicts.</p>\n</li>\n<li><p>Put it inside <code>bin</code> folder next to the batch script.</p>\n</li>\n</ul>\n<h2>Code</h2>\n<pre><code>:: Add binaries to temp path\nIF EXIST bin SET PATH=%PATH%;bin\n\n:: Create UTC Timestamp string in a custom format\n:: Example: 20210128172058\nset timestamp_command='date_unxutils.exe -u +&quot;%%Y%%m%%d%%H%%M%%S&quot;'\nFOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i\necho %timestamp%\n</code></pre>\n<h2>Download UnxUtils</h2>\n<ul>\n<li><a href=\"http://sourceforge.net/projects/unxutils/files/unxutils/current/UnxUtils.zip/download\" rel=\"nofollow noreferrer\">Link</a>.</li>\n</ul>\n<h2>References</h2>\n<ul>\n<li>This <a href=\"https://stackoverflow.com/a/1951681/10830091\">awesome</a> answer that I build upon.</li>\n</ul>\n" }, { "answer_id": 69833816, "author": "Brendan Harris", "author_id": 9688181, "author_profile": "https://Stackoverflow.com/users/9688181", "pm_score": 0, "selected": false, "text": "<p>PowerShell\nTry the code below.\nIt will create the file or folder varible with the date as ddmmyyhhmm in 24hour time</p>\n<pre><code>[int] $day = Get-Date -UFormat %d\n[int] $month = Get-Date -UFormat %m\n[int] $year = Get-Date -UFormat %y\n[String] $date = &quot;$($day)$($month)$($year)&quot;\n$time = Get-Date -UFormat %R\n$time -replace ‘[:]’,”&quot;\n$fileFolderName = $date + time\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using `date`. See @npocmaka's <https://stackoverflow.com/a/19799236/8479> --- What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename? I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, `Code_2008-10-14_2257.zip`. Is there any easy way I can do this, independent of the regional settings of the machine? I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine. So far I've got this, which on my machine gives me `Tue_10_14_2008_230050_91`: ``` rem Get the datetime in a format that can go in a filename. set _my_datetime=%date%_%time% set _my_datetime=%_my_datetime: =_% set _my_datetime=%_my_datetime::=% set _my_datetime=%_my_datetime:/=_% set _my_datetime=%_my_datetime:.=_% rem Now use the timestamp by in a new ZIP file name. "d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code ``` I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier. I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).
See *[Windows Batch File (.bat) to get current date in MMDDYYYY format](http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/)*: ``` @echo off For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b) For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b) echo %mydate%_%mytime% ``` If you prefer the time in 24 hour/military format, you can replace the second FOR line with this: ``` For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b) ``` > > C:> .\date.bat > > 2008-10-14\_0642 > > > If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order: ``` @echo off for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6% echo Local date is [%ldt%] ``` > > C:>test.cmd > > Local date is [2012-06-19 10:23:47.048] > > >
203,096
<p>I created an Interop user control in VS2005. When the user control is shown inside VB6, it does not pickup/use the XP styles (The buttons and the tabs look like VB6 buttons/tabs). </p> <p>How do I get the XP styles to work with my control while it is in VB6?</p>
[ { "answer_id": 203099, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 3, "selected": false, "text": "<p>This is what I've used:</p>\n\n<pre><code>::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like \"backup_04.15.08.7z\")\nSET DT=%date%\nSET DT=%DT:/=.%\nSET DT=%DT:-=.%\n</code></pre>\n\n<hr>\n\n<p>If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: <a href=\"http://wittman.org/ziparcy/\" rel=\"nofollow noreferrer\">http://wittman.org/ziparcy/</a></p>\n" }, { "answer_id": 203108, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 4, "selected": false, "text": "<p>This isn't really briefer but might be a more flexible way (<a href=\"http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/\" rel=\"nofollow noreferrer\">credit</a>):</p>\n\n<pre><code>FOR /F \"TOKENS=1* DELIMS= \" %%A IN ('DATE/T') DO SET CDATE=%%B\nFOR /F \"TOKENS=1,2 eol=/ DELIMS=/ \" %%A IN ('DATE/T') DO SET mm=%%B\nFOR /F \"TOKENS=1,2 DELIMS=/ eol=/\" %%A IN ('echo %CDATE%') DO SET dd=%%B\nFOR /F \"TOKENS=2,3 DELIMS=/ \" %%A IN ('echo %CDATE%') DO SET yyyy=%%B\nSET date=%mm%%dd%%yyyy%\n</code></pre>\n" }, { "answer_id": 203115, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 4, "selected": false, "text": "<p>Another way (<a href=\"http://weblogs.asp.net/whaggard/archive/2005/08/18/423029.aspx\" rel=\"noreferrer\">credit</a>):</p>\n\n<pre><code>@For /F \"tokens=2,3,4 delims=/ \" %%A in ('Date /t') do @( \n Set Month=%%A\n Set Day=%%B\n Set Year=%%C\n)\n\n@echo DAY = %Day%\n@echo Month = %Month%\n@echo Year = %Year%\n</code></pre>\n\n<p>Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.</p>\n" }, { "answer_id": 203116, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 11, "selected": true, "text": "<p>See <em><a href=\"http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/\" rel=\"noreferrer\">Windows Batch File (.bat) to get current date in MMDDYYYY format</a></em>:</p>\n\n<pre><code>@echo off\nFor /f \"tokens=2-4 delims=/ \" %%a in ('date /t') do (set mydate=%%c-%%a-%%b)\nFor /f \"tokens=1-2 delims=/:\" %%a in ('time /t') do (set mytime=%%a%%b)\necho %mydate%_%mytime%\n</code></pre>\n\n<p>If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:</p>\n\n<pre><code>For /f \"tokens=1-2 delims=/:\" %%a in (\"%TIME%\") do (set mytime=%%a%%b)\n</code></pre>\n\n<blockquote>\n <p>C:> .\\date.bat <br />\n 2008-10-14_0642</p>\n</blockquote>\n\n<p>If you want the date independently of the region day/month order, you can use \"WMIC os GET LocalDateTime\" as a source, since it's in ISO order:</p>\n\n<pre><code>@echo off\nfor /F \"usebackq tokens=1,2 delims==\" %%i in (`wmic os get LocalDateTime /VALUE 2^&gt;NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j\nset ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%\necho Local date is [%ldt%]\n</code></pre>\n\n<blockquote>\n <p>C:>test.cmd<br />\n Local date is [2012-06-19 10:23:47.048]</p>\n</blockquote>\n" }, { "answer_id": 203127, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "<p>Unfortunately this is not immune to regional settings, but it does what you want.</p>\n\n<pre><code>set hour=%time:~0,2%\nif \"%time:~0,1%\"==\" \" set hour=0%time:~1,1%\nset _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%\n</code></pre>\n\n<p>Amazing the stuff you can find on <a href=\"http://en.wikipedia.org/wiki/Environment_variable\" rel=\"noreferrer\">Wikipedia</a>.</p>\n" }, { "answer_id": 741748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>I use this (again not region independent (UK))</p>\n\n<pre><code>set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%\n</code></pre>\n" }, { "answer_id": 1849224, "author": "DigiP", "author_id": 225031, "author_profile": "https://Stackoverflow.com/users/225031", "pm_score": 4, "selected": false, "text": "<pre><code>\"d:\\Program Files\\7-Zip\\7z.exe\" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip\n</code></pre>\n" }, { "answer_id": 1951681, "author": "Uri Liebeskind", "author_id": 237474, "author_profile": "https://Stackoverflow.com/users/237474", "pm_score": 7, "selected": false, "text": "<h3>Regionally independent date time parsing</h3>\n\n<p>The output format of <code>%DATE%</code> and of the <code>dir</code> command is regionally dependent and thus neither robust nor smart. <a href=\"http://sourceforge.net/projects/unxutils/files/\" rel=\"noreferrer\">date.exe</a> (part of <a href=\"http://en.wikipedia.org/wiki/UnxUtils\" rel=\"noreferrer\">UnxUtils</a>) delivers any date and time information in any thinkable format. You may also extract the date/time information from any file with <code>date.exe</code>.</p>\n\n<h3>Examples: (in a cmd-script use %% instead of %)</h3>\n\n<p><code>date.exe +\"%Y-%m-%d\"</code><br>\n2009-12-22 </p>\n\n<p><code>date.exe +\"%T\"</code><br>\n18:55:03 </p>\n\n<p><code>date.exe +\"%Y%m%d %H%M%S: Any text\"</code><br>\n20091222 185503: Any text</p>\n\n<p><code>date.exe +\"Text: %y/%m/%d-any text-%H.%M\"</code><br>\nText: 09/12/22-any text-18.55</p>\n\n<p><code>Command: date.exe +\"%m-%d \"\"\"%H %M %S \"\"\"\"</code><br>\n07-22 \"18:55:03\"`</p>\n\n<p>The date/time information from a reference file:<br>\n<code>date.exe -r c:\\file.txt +\"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S\"</code></p>\n\n<p>Using it in a CMD script to get year, month, day, time information:</p>\n\n<pre><code>for /f \"tokens=1,2,3,4,5,6* delims=,\" %%i in ('C:\\Tools\\etc\\date.exe +\"%%y,%%m,%%d,%%H,%%M,%%S\"') do set yy=%%i&amp; set mo=%%j&amp; set dd=%%k&amp; set hh=%%l&amp; set mm=%%m&amp; set ss=%%n\n</code></pre>\n\n<p>Using it in a CMD script to get a timestamp in any required format:</p>\n\n<pre><code>for /f \"tokens=*\" %%i in ('C:\\Tools\\etc\\date.exe +\"%%y-%%m-%%d %%H:%%M:%%S\"') do set timestamp=%%i\n</code></pre>\n\n<p>Extracting the date/time information from any reference file.</p>\n\n<pre><code>for /f \"tokens=1,2,3,4,5,6* delims=,\" %%i in ('C:\\Tools\\etc\\date.exe -r file.txt +\"%%y,%%m,%%d,%%H,%%M,%%S\"') do set yy=%%i&amp; set mo=%%j&amp; set dd=%%k&amp; set hh=%%l&amp; set mm=%%m&amp; set ss=%%n\n</code></pre>\n\n<p>Adding to a file its date/time information:</p>\n\n<pre><code>for /f \"tokens=*\" %%i in ('C:\\Tools\\etc\\date.exe -r file.txt +\"%%y-%%m-%%d.%%H%%M%%S\"') do ren file.txt file.%%i.txt\n</code></pre>\n\n<p>date.exe is <a href=\"http://sourceforge.net/projects/unxutils/files/\" rel=\"noreferrer\">part of the free GNU tools</a> which need no installation.</p>\n\n<p>NOTE: Copying <code>date.exe</code> into any directory which is in the search path may cause other scripts to fail that use the Windows built-in <code>date</code> command.</p>\n" }, { "answer_id": 2854857, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 4, "selected": false, "text": "<p>Short answer : </p>\n\n<pre><code> :: Start - Run , type:\n cmd /c \"powershell get-date -format ^\"{yyyy-MM-dd HH:mm:ss}^\"|clip\"\n\n :: click into target media, Ctrl + V to paste the result \n</code></pre>\n\n<p>Long answer</p>\n\n<pre><code> @echo off\n :: START USAGE ==================================================================\n ::SET THE NICETIME \n :: SET NICETIME=BOO\n :: CALL GetNiceTime.cmd \n\n :: ECHO NICETIME IS %NICETIME%\n\n :: echo nice time is %NICETIME%\n :: END USAGE ==================================================================\n\n echo set hhmmsss\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=:\" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c \n ::DEBUG ECHO hhmmsss IS %hhmmsss%\n ::DEBUG PAUSE\n echo %yyyymmdd%\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=.\" %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D\n ::DEBUG ECHO yyyymmdd IS %yyyymmdd%\n ::DEBUG PAUSE\n\n\n set NICETIME=%yyyymmdd%_%hhmmsss%\n ::DEBUG echo THE NICETIME IS %NICETIME%\n\n ::DEBUG PAUSE\n</code></pre>\n" }, { "answer_id": 3202796, "author": "vMax", "author_id": 386539, "author_profile": "https://Stackoverflow.com/users/386539", "pm_score": 6, "selected": false, "text": "<p>Here's a variant from alt.msdos.batch.nt that works local-independently.</p>\n\n<p>Put this in a text file, e.g. getDate.cmd</p>\n\n<pre><code>-----------8&lt;------8&lt;------------ snip -- snip ----------8&lt;-------------\n :: Works on any NT/2k machine independent of regional date settings\n @ECHO off\n SETLOCAL ENABLEEXTENSIONS\n if \"%date%A\" LSS \"A\" (set toks=1-3) else (set toks=2-4)\n for /f \"tokens=2-4 delims=(-)\" %%a in ('echo:^|date') do (\n for /f \"tokens=%toks% delims=.-/ \" %%i in ('date/t') do (\n set '%%a'=%%i\n set '%%b'=%%j\n set '%%c'=%%k))\n if %'yy'% LSS 100 set 'yy'=20%'yy'%\n set Today=%'yy'%-%'mm'%-%'dd'% \n ENDLOCAL &amp; SET v_year=%'yy'%&amp; SET v_month=%'mm'%&amp; SET v_day=%'dd'%\n\n ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]\n\n :EOF\n-----------8&lt;------8&lt;------------ snip -- snip ----------8&lt;-------------\n</code></pre>\n\n<p>To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like \"set =20\" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.</p>\n\n<p>The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!</p>\n" }, { "answer_id": 3859042, "author": "Matthew Johnson", "author_id": 466219, "author_profile": "https://Stackoverflow.com/users/466219", "pm_score": 3, "selected": false, "text": "<p>Here's a way to get date time in a single line:</p>\n\n<pre><code>for /f \"tokens=2,3,4,5,6 usebackq delims=:/ \" %a in ('%date% %time%') do echo %c-%a-%b %d%e\n</code></pre>\n\n<p>In the US this will output \"yyyy-mm-dd hhmm\". Different regional settings will result in different %date% outputs, but you can modify the token order.</p>\n\n<p>If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.</p>\n" }, { "answer_id": 4061880, "author": "Sally", "author_id": 478885, "author_profile": "https://Stackoverflow.com/users/478885", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://sourceforge.net/projects/unxutils/files/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/unxutils/files/</a></p>\n\n<p>Look inside the ZIP file for something called \"Date.exe\" and rename it \"DateFormat.exe\" (to avoid conflicts).</p>\n\n<p>Put it in your Windows system32 folder.</p>\n\n<p>It has a lot of \"date output\" options.</p>\n\n<p>For help, use <code>DateFormat.exe --h</code></p>\n\n<p>I'm not sure how you would put its output into an environment variable... using SET.</p>\n" }, { "answer_id": 4584577, "author": "Jeroen Wiert Pluimers", "author_id": 29290, "author_profile": "https://Stackoverflow.com/users/29290", "pm_score": 3, "selected": false, "text": "<p>I changed <a href=\"https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi/3202796#3202796\">the answer</a> with the batch file from <a href=\"https://stackoverflow.com/users/386539/vmax\">vMax</a> so it works with the Dutch language too.<br>\nThe Dutch - persistent as we are - have a few changes in the <code>%date%</code>, <code>date/t</code>, and <code>date</code> that break the original batch-file.</p>\n\n<p>It would be nice if some people can check this against other Windows locales as well, and report back the results.<br>\nIf the batch-file fails at your location, then please include the output of these two statements on the command prompt:<br>\n<code>echo:^|date</code><br>\n<code>date/t</code> </p>\n\n<p>This is a sample of the output you should get from the batch-file:</p>\n\n<pre><code>C:\\temp&gt;set-date-cmd.bat\nToday is Year: [2011] Month: [01] Day: [03]\n20110103\n</code></pre>\n\n<p>Here is the revised code with comments on why:</p>\n\n<pre><code>:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi\n:: Works on any NT/2k machine independent of regional date settings\n::\n:: 20110103 - adapted by [email protected] for Dutch locale\n:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'\n:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date\n:: set '%%c'=%%k\n:: set 'yy'=%%k\n::\n:: In addition, date will display the current date before the input prompt using dashes\n:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch\n:: and one occurence in English.\n:: This skips the first iteration:\n:: if \"%%a\" GEQ \"A\"\n::\n:: echo:^|date\n:: Huidige datum: ma 03-01-2011\n:: Voer de nieuwe datum in: (dd-mm-jj)\n:: The current date is: Mon 01/03/2011\n:: Enter the new date: (mm-dd-yy)\n::\n:: date/t\n:: ma 03-01-2011\n:: Mon 01/03/2011\n::\n:: The assumption in this batch-file is that echo:^|date will return the date format\n:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.\n::\n:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.\n:: That will resolve the order of the tokens.\n::\n@ECHO off\n set v_day=\n set v_month=\n set v_year=\n\n SETLOCAL ENABLEEXTENSIONS\n if \"%date%A\" LSS \"A\" (set toks=1-3) else (set toks=2-4)\n::DEBUG echo toks=%toks%\n for /f \"tokens=2-4 delims=(-)\" %%a in ('echo:^|date') do (\n::DEBUG echo first token=%%a\n if \"%%a\" GEQ \"A\" (\n for /f \"tokens=%toks% delims=.-/ \" %%i in ('date/t') do (\n set '%%a'=%%i\n set '%%b'=%%j\n set 'yy'=%%k\n )\n )\n )\n if %'yy'% LSS 100 set 'yy'=20%'yy'%\n set Today=%'yy'%-%'mm'%-%'dd'%\n\n ENDLOCAL &amp; SET v_year=%'yy'%&amp; SET v_month=%'mm'%&amp; SET v_day=%'dd'%\n\n ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]\n set datestring=%V_Year%%V_Month%%V_Day%\n echo %datestring%\n\n :EOF\n</code></pre>\n\n<p>--jeroen</p>\n" }, { "answer_id": 4584820, "author": "Jeroen Wiert Pluimers", "author_id": 29290, "author_profile": "https://Stackoverflow.com/users/29290", "pm_score": 3, "selected": false, "text": "<p>And here is a similar batch-file for the time portion. </p>\n\n<pre><code>:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi\n:: Works on any NT/2k machine independent of regional time settings\n::\n:: Gets the time in ISO 8601 24-hour format\n::\n:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.\n:: Since ISO 8601 does not care about AM/PM, we use %time%\n::\n @ECHO off\n SETLOCAL ENABLEEXTENSIONS\n for /f \"tokens=1-4 delims=:,.-/ \" %%i in ('echo %time%') do (\n set 'hh'=%%i\n set 'mm'=%%j\n set 'ss'=%%k\n set 'ff'=%%l)\n ENDLOCAL &amp; SET v_Hour=%'hh'%&amp; SET v_Minute=%'mm'%&amp; SET v_Second=%'ss'%&amp; SET v_Fraction=%'ff'%\n\n ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]\n set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%\n echo %timestring%\n\n :EOF\n</code></pre>\n\n<p>--jeroen</p>\n" }, { "answer_id": 6348634, "author": "KChiki", "author_id": 798300, "author_profile": "https://Stackoverflow.com/users/798300", "pm_score": 3, "selected": false, "text": "<p>I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.</p>\n\n<p>I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.</p>\n\n<pre><code>for /f \"tokens=1-5 delims=/ \" %%d in (\"%date%\") do rename \"decrypted.txt\" %%g-%%e-%%f.txt\n</code></pre>\n\n<p>It worked perfectly (i.e., the filename comes out as \"2011-06-14.txt\").</p>\n\n<p><a href=\"http://www.computerhope.com/issues/ch000987.htm\" rel=\"nofollow\">(Source)</a></p>\n" }, { "answer_id": 6707326, "author": "sudipto roy", "author_id": 846495, "author_profile": "https://Stackoverflow.com/users/846495", "pm_score": 5, "selected": false, "text": "<p>Please use the following script to get the current day in the command line:</p>\n\n<pre><code>echo %Date:~0,3%day\n</code></pre>\n" }, { "answer_id": 7319693, "author": "V15I0N", "author_id": 930610, "author_profile": "https://Stackoverflow.com/users/930610", "pm_score": 2, "selected": false, "text": "<p>Regional independent solution generating the ISO date format:</p>\n\n<pre><code>rem save the existing format definition\nfor /f \"skip=2 tokens=3\" %%a in ('reg query \"HKCU\\Control Panel\\International\" /v sShortDate') do set FORMAT=%%a\nrem set ISO specific format definition\nreg add \"HKCU\\Control Panel\\International\" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1&gt;nul:\nrem query the date in the ISO specific format \nset ISODATE=%DATE%\nrem restore previous format definition\nreg add \"HKCU\\Control Panel\\International\" /v sShortDate /t REG_SZ /f /d %FORMAT% 1&gt;nul:\n</code></pre>\n\n<p>What could still be optimized:\nOther processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated</p>\n" }, { "answer_id": 16264795, "author": "John Langstaff", "author_id": 714326, "author_profile": "https://Stackoverflow.com/users/714326", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/3859042/2657515\"><strong>Matthew Johnson's</strong> one-liner solution</a> to get the one-liner date and time is <em>eloquent</em> and useful.</p>\n\n<p>It does however need a simple modification to work from within a batch file:</p>\n\n<pre><code>for /f \"tokens=2,3,4,5,6 usebackq delims=:/ \" %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e\n</code></pre>\n" }, { "answer_id": 19799236, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 7, "selected": false, "text": "<p>Two more ways that do not depend on the time settings (both taken from <a href=\"http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=4555\" rel=\"noreferrer\">:How get data/time independent from localization:</a>). And both also get the day of the week and none of them requires admin permissions!:</p>\n\n<ol>\n<li><p><strong>MAKECAB</strong> - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):</p>\n\n<pre><code>@echo off\npushd \"%temp%\"\nmakecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul &gt;nul\nfor /f \"tokens=3-7\" %%a in ('find /i \"makecab\"^&lt;~.rpt') do (\n set \"current-date=%%e-%%b-%%c\"\n set \"current-time=%%d\"\n set \"weekday=%%a\"\n)\ndel ~.*\npopd\necho %weekday% %current-date% %current-time%\npause\n</code></pre>\n\n<p><a href=\"http://ss64.com/ps/get-date.html\" rel=\"noreferrer\">More information about get-date function</a>.</p></li>\n<li><p><strong>ROBOCOPY</strong> - it's not native command for Windows&nbsp;XP and Windows Server 2003, but it can be <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=17657\" rel=\"noreferrer\">downloaded from microsoft site</a>. But is built-in in everything from Windows&nbsp;Vista and above:</p>\n\n<pre><code>@echo off\nsetlocal\nfor /f \"skip=8 tokens=2,3,4,5,6,7,8 delims=: \" %%D in ('robocopy /l * \\ \\ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (\n set \"dow=%%D\"\n set \"month=%%E\"\n set \"day=%%F\"\n set \"HH=%%G\"\n set \"MM=%%H\"\n set \"SS=%%I\"\n set \"year=%%J\"\n)\n\necho Day of the week: %dow%\necho Day of the month : %day%\necho Month : %month%\necho hour : %HH%\necho minutes : %MM%\necho seconds : %SS%\necho year : %year%\nendlocal\n</code></pre>\n\n<p>And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.</p></li>\n<li><p><strong>JScript/batch</strong> hybrid (need to be saved as <code>.bat</code>). JScript is available on every system form NT and above, as a part of <a href=\"http://en.wikipedia.org/wiki/Windows_Script_Host\" rel=\"noreferrer\">Windows Script Host</a> (<a href=\"http://technet.microsoft.com/en-us/library/ee198684.aspx\" rel=\"noreferrer\">though can be disabled through the registry it's a rare case</a>):</p>\n\n<pre><code>@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment\n\n@echo off\ncscript //E:JScript //nologo \"%~f0\"\nexit /b 0\n*------------------------------------------------------------------------------*/\n\nfunction GetCurrentDate() {\n // Today date time which will used to set as default date.\n var todayDate = new Date();\n todayDate = todayDate.getFullYear() + \"-\" +\n (\"0\" + (todayDate.getMonth() + 1)).slice(-2) + \"-\" +\n (\"0\" + todayDate.getDate()).slice(-2) + \" \" + (\"0\" + todayDate.getHours()).slice(-2) + \":\" +\n (\"0\" + todayDate.getMinutes()).slice(-2);\n\n return todayDate;\n }\n\nWScript.Echo(GetCurrentDate());\n</code></pre></li>\n<li><p><strong>VSCRIPT/BATCH</strong> hybrid (<em><a href=\"https://stackoverflow.com/questions/9074476/is-it-possible-to-embed-and-execute-vbscript-within-a-batch-file-without-using-a\">Is it possible to embed and execute VBScript within a batch file without using a temporary file?</a></em>) same case as JScript, but hybridization is not so perfect:</p>\n\n<pre><code>:sub echo(str) :end sub\necho off\n'&gt;nul 2&gt;&amp;1|| copy /Y %windir%\\System32\\doskey.exe %windir%\\System32\\'.exe &gt;nul\n'&amp; echo current date:\n'&amp; cscript /nologo /E:vbscript \"%~f0\"\n'&amp; exit /b\n\n'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.\n'1 = vbLongDate - Returns date: weekday, monthname, year\n'2 = vbShortDate - Returns date: mm/dd/yy\n'3 = vbLongTime - Returns time: hh:mm:ss PM/AM\n'4 = vbShortTime - Return time: hh:mm\n\nWScript.echo Replace(FormatDateTime(Date,1),\", \",\"-\")\n</code></pre></li>\n<li><p><strong>PowerShell</strong> - can be installed on every machine that has .NET - download from Microsoft (<a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=7217\" rel=\"noreferrer\">v1</a>, <a href=\"http://support.microsoft.com/kb/968929/bg\" rel=\"noreferrer\">v2</a>, <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=34595\" rel=\"noreferrer\">v3</a> (only for Windows&nbsp;7 and above)). It is installed by default on everything from Windows&nbsp;7/Windows Server 2008 and above:</p>\n\n<pre><code>C:\\&gt; powershell get-date -format \"{dd-MMM-yyyy HH:mm}\"\n</code></pre>\n\n<p>To use it from a batch file:</p>\n\n<pre><code>for /f \"delims=\" %%# in ('powershell get-date -format \"{dd-MMM-yyyy HH:mm}\"') do @set _date=%%#\n</code></pre></li>\n<li><p><strong>Self-compiled jscript.net/batch</strong> (never seen a Windows machine without .NET, so I think this is a pretty portable):</p>\n\n<pre><code>@if (@X)==(@Y) @end /****** silent line that start JScript comment ******\n\n@echo off\n::::::::::::::::::::::::::::::::::::\n::: Compile the script ::::\n::::::::::::::::::::::::::::::::::::\nsetlocal\nif exist \"%~n0.exe\" goto :skip_compilation\n\nset \"frm=%SystemRoot%\\Microsoft.NET\\Framework\\\"\n\n:: Searching the latest installed .NET framework\nfor /f \"tokens=* delims=\" %%v in ('dir /b /s /a:d /o:-n \"%SystemRoot%\\Microsoft.NET\\Framework\\v*\"') do (\n if exist \"%%v\\jsc.exe\" (\n rem :: the javascript.net compiler\n set \"jsc=%%~dpsnfxv\\jsc.exe\"\n goto :break_loop\n )\n)\necho jsc.exe not found &amp;&amp; exit /b 0\n:break_loop\n\n\ncall %jsc% /nologo /out:\"%~n0.exe\" \"%~dpsfnx0\"\n::::::::::::::::::::::::::::::::::::\n::: End of compilation ::::\n::::::::::::::::::::::::::::::::::::\n:skip_compilation\n\n\"%~n0.exe\"\n\nexit /b 0\n\n\n****** End of JScript comment ******/\nimport System;\nimport System.IO;\n\nvar dt=DateTime.Now;\nConsole.WriteLine(dt.ToString(\"yyyy-MM-dd hh:mm:ss\"));\n</code></pre></li>\n<li><p><strong>Logman</strong> This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows&nbsp;XP and above. It probably will be never used by anybody - including me - but is one more way...</p>\n\n<pre><code>@echo off\nsetlocal\ndel /q /f %temp%\\timestampfile_*\n\nLogman.exe stop ts-CPU 1&gt;nul 2&gt;&amp;1\nLogman.exe delete ts-CPU 1&gt;nul 2&gt;&amp;1\n\nLogman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c \"\\Processor(_Total)\\%% Processor Time\" -o %temp%\\timestampfile_ &gt;nul\nLogman.exe start ts-CPU 1&gt;nul 2&gt;&amp;1\n\nLogman.exe stop ts-CPU &gt;nul 2&gt;&amp;1\nLogman.exe delete ts-CPU &gt;nul 2&gt;&amp;1\nfor /f \"tokens=2 delims=_.\" %%t in ('dir /b %temp%\\timestampfile_*^&amp;del /q/f %temp%\\timestampfile_*') do set timestamp=%%t\n\necho %timestamp%\necho MM: %timestamp:~0,2%\necho dd: %timestamp:~2,2%\necho hh: %timestamp:~4,2%\necho mm: %timestamp:~6,2%\n\nendlocal\nexit /b 0\n</code></pre></li>\n<li><p>One more way with <strong>WMIC</strong> which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):</p>\n\n<pre><code>for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in (\"%%#\") do @set %%@\necho %day%\necho %DayOfWeek%\necho %hour%\necho %minute%\necho %month%\necho %quarter%\necho %second%\necho %weekinmonth%\necho %year%\n</code></pre></li>\n<li><p>Using <strong><a href=\"http://ss64.com/nt/typeperf.html\" rel=\"noreferrer\">TYPEPERF</a></strong> with some efforts to be fast and compatible with different language settings and as fast as possible:</p>\n\n<pre><code>@echo off\nsetlocal\n\n:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance\n::if defined USERDOMAIN_roamingprofile (set \"v=v4\") else (set \"v=\")\n\nfor /f \"tokens=4 delims=. \" %%# in ('ver') do if %%# GTR 5 (set \"v=v4\") else (\"v=\")\nset \"mon=\"\nfor /f \"skip=2 delims=,\" %%# in ('typeperf \"\\UDP%v%\\*\" -si 0 -sc 1') do (\n if not defined mon (\n for /f \"tokens=1-7 delims=.:/ \" %%a in (%%#) do (\n set mon=%%a\n set date=%%b\n set year=%%c\n set hour=%%d\n set minute=%%e\n set sec=%%f\n set ms=%%g\n )\n )\n)\necho %year%.%mon%.%date%\necho %hour%:%minute%:%sec%.%ms%\nendlocal\n</code></pre></li>\n<li><p><strong>MSHTA</strong> allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.</p>\n\n<pre><code>&lt;!-- : Batch portion\n\n@echo off\nsetlocal\n\nfor /f \"delims=\" %%I in ('mshta \"%~f0\"') do set \"now.%%~I\"\n\nrem Display all variables beginning with \"now.\"\nset now.\n\ngoto :EOF\n\nend batch / begin HTA --&gt;\n\n&lt;script&gt;\n resizeTo(0,0)\n var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),\n now = new Date(),\n props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',\n 'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',\n 'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',\n 'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',\n 'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],\n output = [];\n\n for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}\n close(fso.Write(output.join('\\n')));\n&lt;/script&gt;\n</code></pre></li>\n</ol>\n" }, { "answer_id": 21282321, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<p>A function that is based on <code>wmic</code>:</p>\n\n<pre><code>:Now -- Gets the current date and time into separate variables\n:: %~1: [out] Year\n:: %~2: [out] Month\n:: %~3: [out] Day\n:: %~4: [out] Hour\n:: %~5: [out] Minute\n:: %~6: [out] Second\n setlocal\n for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t\n endlocal &amp; (\n if \"%~1\" neq \"\" set %~1=%T:~0,4%\n if \"%~2\" neq \"\" set %~2=%T:~4,2%\n if \"%~3\" neq \"\" set %~3=%T:~6,2%\n if \"%~4\" neq \"\" set %~4=%T:~8,2%\n if \"%~5\" neq \"\" set %~5=%T:~10,2%\n if \"%~6\" neq \"\" set %~6=%T:~12,2%\n )\ngoto:eof\n</code></pre>\n\n<p><strong>Upside:</strong> Region independent. <strong>Downside:</strong> Only system administrators can run wmic.exe.</p>\n\n<p>Usage:</p>\n\n<pre><code>call:Now Y M D H N S\necho %Y%-%M%-%D% %H%:%N%:%S%\n</code></pre>\n\n<p>This echos a string like this:</p>\n\n<pre><code>2014-01-22 12:51:53\n</code></pre>\n\n<p>Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.</p>\n\n<p>All parameters are optional, so <code>call:Now Y M</code> is a valid call if you only want to get year and month.</p>\n" }, { "answer_id": 25714111, "author": "foxidrive", "author_id": 2299431, "author_profile": "https://Stackoverflow.com/users/2299431", "pm_score": 5, "selected": false, "text": "<p>The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows&nbsp;XP Professional and higher.</p>\n\n<pre><code>@echo off\nfor /f \"tokens=2 delims==\" %%a in ('wmic OS Get localdatetime /value') do set \"dt=%%a\"\nset \"YY=%dt:~2,2%\" &amp; set \"YYYY=%dt:~0,4%\" &amp; set \"MM=%dt:~4,2%\" &amp; set \"DD=%dt:~6,2%\"\nset \"HH=%dt:~8,2%\" &amp; set \"Min=%dt:~10,2%\" &amp; set \"Sec=%dt:~12,2%\"\n\nset \"datestamp=%YYYY%%MM%%DD%\" &amp; set \"timestamp=%HH%%Min%%Sec%\" &amp; set \"fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%\"\necho datestamp: \"%datestamp%\"\necho timestamp: \"%timestamp%\"\necho fullstamp: \"%fullstamp%\"\npause\n</code></pre>\n" }, { "answer_id": 27012486, "author": "gdelfino", "author_id": 93947, "author_profile": "https://Stackoverflow.com/users/93947", "pm_score": 3, "selected": false, "text": "<p>Just use this line:</p>\n\n<pre><code>PowerShell -Command \"get-date\"\n</code></pre>\n" }, { "answer_id": 38905219, "author": "bvj", "author_id": 241296, "author_profile": "https://Stackoverflow.com/users/241296", "pm_score": -1, "selected": false, "text": "<p>Given a known locality, for reference in functional form. The <code>ECHOTIMESTAMP</code> call shows how to get the timestamp into a variable (<code>DTS</code> in this example.)</p>\n\n<pre><code>@ECHO off\n\nCALL :ECHOTIMESTAMP\nGOTO END\n\n:TIMESTAMP\nSETLOCAL EnableDelayedExpansion\n SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!\n SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!\n SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!\nENDLOCAL &amp; SET \"%~1=%DTS%\"\nGOTO :EOF\n\n:ECHOTIMESTAMP\nSETLOCAL\n CALL :TIMESTAMP DTS\n ECHO %DTS%\nENDLOCAL\nGOTO :EOF\n\n:END\n\nEXIT /b 0\n</code></pre>\n\n<p>And saved to file, timestamp.bat, here's the output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/zc1ZI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zc1ZI.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 38958529, "author": "NotepadPlusPlus PRO", "author_id": 2920692, "author_profile": "https://Stackoverflow.com/users/2920692", "pm_score": -1, "selected": false, "text": "<p>I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>:: Check your local date format\necho %date%\n\n :: Output is Mon 08/15/2016\n\n:: get day (start index, number of characters)\n:: (index starts with zero)\nset myday=%DATE:~0,4%\necho %myday%\n :: output is Mon \n\n:: get month\nset mymonth=%DATE:~4,2%\necho %mymonth%\n :: output is 08\n\n:: get date \nset mydate=%DATE:~7,2% \necho %mydate%\n :: output is 15\n\n:: get year\nset myyear=%DATE:~10,4%\necho %myyear%\n :: output is 2016\n</code></pre>\n" }, { "answer_id": 38972828, "author": "Frizz1977", "author_id": 1794049, "author_profile": "https://Stackoverflow.com/users/1794049", "pm_score": -1, "selected": false, "text": "<p>With Windows 7, this code works for me:</p>\n\n<pre><code>SET DATE=%date%\nSET YEAR=%DATE:~0,4%\nSET MONTH=%DATE:~5,2%\nSET DAY=%DATE:~8,2%\nECHO %YEAR%\nECHO %MONTH%\nECHO %DAY%\n\nSET DATE_FRM=%YEAR%-%MONTH%-%DAY% \nECHO %DATE_FRM%\n</code></pre>\n" }, { "answer_id": 43903620, "author": "Adolfo", "author_id": 3075331, "author_profile": "https://Stackoverflow.com/users/3075331", "pm_score": 2, "selected": false, "text": "<pre><code>:: GetDate.cmd -&gt; Uses WMIC.exe to get current date and time in ISO 8601 format\n:: - Sets environment variables %_isotime% and %_now% to current time\n:: - On failure, clears these environment variables\n:: Inspired on -&gt; https://ss64.com/nt/syntax-getdate.html\n:: - (cX) 2017 [email protected]\n:: - http://stackoverflow.com/questions/203090\n@echo off\n\nset _isotime=\nset _now=\n\n:: Check that WMIC.exe is available\nWMIC.exe Alias /? &gt;NUL 2&gt;&amp;1 || goto _WMIC_MISSING_\n\nif not (%1)==() goto _help\nSetLocal EnableDelayedExpansion\n\n:: Use WMIC.exe to retrieve date and time\nFOR /F \"skip=1 tokens=1-6\" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (\n IF \"%%~L\"==\"\" goto _WMIC_done_\n set _yyyy=%%L\n set _mm=00%%J\n set _dd=00%%G\n set _hour=00%%H\n set _minute=00%%I\n set _second=00%%K\n)\n:_WMIC_done_\n\n:: 1 2 3 4 5 6\n:: %%G %%H %%I %%J %%K %%L\n:: Day Hour Minute Month Second Year\n:: 27 9 35 4 38 2017\n\n:: Remove excess leading zeroes\n set _mm=%_mm:~-2%\n set _dd=%_dd:~-2%\n set _hour=%_hour:~-2%\n set _minute=%_minute:~-2%\n set _second=%_second:~-2%\n:: Syntax -&gt; %variable:~num_chars_to_skip,num_chars_to_keep%\n\n:: Set date/time in ISO 8601 format:\n Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%\n:: -&gt; http://google.com/search?num=100&amp;q=ISO+8601+format\n\nif 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am\nif 1%_hour% LSS 112 goto _skip_12_\n set /a _hour=1%_hour%-12\n set _hour=%_hour:~-2%\n set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm\n :: -&gt; https://ss64.com/nt/if.html\n :: -&gt; http://google.com/search?num=100&amp;q=SetLocal+EndLocal+Windows\n :: 'if () else ()' will NOT set %_now% correctly !?\n:_skip_12_\n\nEndLocal &amp; set _isotime=%_isotime% &amp; set _now=%_now%\ngoto _out\n\n:_WMIC_MISSING_\necho.\necho WMIC.exe command not available\necho - WMIC.exe needs Administrator privileges to run in Windows\necho - Usually the path to WMIC.exe is \"%windir%\\System32\\wbem\\WMIC.exe\"\n\n:_help\necho.\necho GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format\necho.\necho %%_now%% environment variable set to current date and time\necho %%_isotime%% environment variable to current time in ISO format\necho set _today=%%_isotime:~0,10%%\necho.\n\n:_out\n:: EOF: GetDate.cmd\n</code></pre>\n" }, { "answer_id": 53649000, "author": "Ed999", "author_id": 1863462, "author_profile": "https://Stackoverflow.com/users/1863462", "pm_score": -1, "selected": false, "text": "<p>I note that the o/p did <strong>not</strong> ask for a region-independent solution. My solution is for the UK though.</p>\n<p>This is the simplest possible solution, a 1-line solution, for use in a Batch file:</p>\n<pre><code>FOR /F &quot;tokens=1-3 delims=/&quot; %%A IN (&quot;%date%&quot;) DO (SET today=%%C-%%B-%%A)\necho %today%\n</code></pre>\n<p>This solution can be varied, by altering the order of the variables %%A %%B and %%C in the output statement, to provide any date format desired (e.g. YY-MM-DD or DD-MM-YY).</p>\n<p>My intention - my <strong>ONLY</strong> intention - in posting this answer is to demonstrate that this can be done on the <strong>command line</strong>, by using a <em>single</em> line of code to achieve it.</p>\n<p>And that it is redundant to post answers running to 35 lines of code, as others have done, because the o/p specifically asked for a <strong>command line</strong> solution in the question. Therefore the o/p specifically sought a single-line solution.</p>\n" }, { "answer_id": 62874781, "author": "Gerhard", "author_id": 7818749, "author_profile": "https://Stackoverflow.com/users/7818749", "pm_score": 2, "selected": false, "text": "<p>Combine <code>Powershell</code> into a batch file and use the meta variables to assign each:</p>\n<pre><code>@echo off\nfor /f &quot;tokens=1-6 delims=-&quot; %%a in ('PowerShell -Command &quot;&amp; {Get-Date -format &quot;yyyy-MM-dd-HH-mm-ss&quot;}&quot;') do (\n echo year: %%a\n echo month: %%b\n echo day: %%c\n echo hour: %%d\n echo minute: %%e\n echo second: %%f\n)\n</code></pre>\n<p>You can also change the the format if you prefer name of the month <code>MMM</code> or <code>MMMM</code> and 12 hour to 24 hour formats <code>hh</code> or <code>HH</code></p>\n" }, { "answer_id": 65943831, "author": "om-ha", "author_id": 10830091, "author_profile": "https://Stackoverflow.com/users/10830091", "pm_score": 0, "selected": false, "text": "<ul>\n<li><p>I used <code>date.exe</code>, and renamed it to <code>date_unxutils.exe</code> to avoid conflicts.</p>\n</li>\n<li><p>Put it inside <code>bin</code> folder next to the batch script.</p>\n</li>\n</ul>\n<h2>Code</h2>\n<pre><code>:: Add binaries to temp path\nIF EXIST bin SET PATH=%PATH%;bin\n\n:: Create UTC Timestamp string in a custom format\n:: Example: 20210128172058\nset timestamp_command='date_unxutils.exe -u +&quot;%%Y%%m%%d%%H%%M%%S&quot;'\nFOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i\necho %timestamp%\n</code></pre>\n<h2>Download UnxUtils</h2>\n<ul>\n<li><a href=\"http://sourceforge.net/projects/unxutils/files/unxutils/current/UnxUtils.zip/download\" rel=\"nofollow noreferrer\">Link</a>.</li>\n</ul>\n<h2>References</h2>\n<ul>\n<li>This <a href=\"https://stackoverflow.com/a/1951681/10830091\">awesome</a> answer that I build upon.</li>\n</ul>\n" }, { "answer_id": 69833816, "author": "Brendan Harris", "author_id": 9688181, "author_profile": "https://Stackoverflow.com/users/9688181", "pm_score": 0, "selected": false, "text": "<p>PowerShell\nTry the code below.\nIt will create the file or folder varible with the date as ddmmyyhhmm in 24hour time</p>\n<pre><code>[int] $day = Get-Date -UFormat %d\n[int] $month = Get-Date -UFormat %m\n[int] $year = Get-Date -UFormat %y\n[String] $date = &quot;$($day)$($month)$($year)&quot;\n$time = Get-Date -UFormat %R\n$time -replace ‘[:]’,”&quot;\n$fileFolderName = $date + time\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
I created an Interop user control in VS2005. When the user control is shown inside VB6, it does not pickup/use the XP styles (The buttons and the tabs look like VB6 buttons/tabs). How do I get the XP styles to work with my control while it is in VB6?
See *[Windows Batch File (.bat) to get current date in MMDDYYYY format](http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/)*: ``` @echo off For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b) For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b) echo %mydate%_%mytime% ``` If you prefer the time in 24 hour/military format, you can replace the second FOR line with this: ``` For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b) ``` > > C:> .\date.bat > > 2008-10-14\_0642 > > > If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order: ``` @echo off for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6% echo Local date is [%ldt%] ``` > > C:>test.cmd > > Local date is [2012-06-19 10:23:47.048] > > >
203,113
<p>I have a JS function that may occasionally get used on some pages. It is dependent on another JS file (swfObject.js), but I'd like to avoid having to include this file all over the place, as thats a wasted request most of the time.</p> <p>Instead, I'd like to create a generic function that can inject a script reference into the page DOM as needed, so if this function is called, it would check for the script, and if it does not exist, load it in.</p> <p>I'm fairly sure this is possible (and I'm not going to use document.write), but before I venture off into uncharted territory, has anyone done this before, and if so, any pointers?</p> <p>EDIT: Ok, I tried it, and it works in IE6 and FF, I haven't tested other browsers yet.</p> <p>Here is my code (Rev 2.0, now with optional callbacks):</p> <pre><code>function loadJSInclude(scriptPath, callback) { var scriptNode = document.createElement('SCRIPT'); scriptNode.type = 'text/javascript'; scriptNode.src = scriptPath; var headNode = document.getElementsByTagName('HEAD'); if (headNode[0] != null) headNode[0].appendChild(scriptNode); if (callback != null) { scriptNode.onreadystagechange = callback; scriptNode.onload = callback; } } </code></pre> <p>and in the method with a dependency:</p> <pre><code>var callbackMethod = function () { // Code to do after loading swfObject } // Include SWFObject if its needed if (typeof(SWFObject) == 'undefined') loadJSInclude('/js/swfObject.js', callbackMethod); else calbackMethod(); </code></pre> <p>Any suggestions?</p>
[ { "answer_id": 203134, "author": "Jim Fiorato", "author_id": 650, "author_profile": "https://Stackoverflow.com/users/650", "pm_score": 0, "selected": false, "text": "<p>Checkout the YUI Loader utility. It's super handy, unobtrusive javascript for loading scripts on-demand.</p>\n\n<p>Here's a link to an example using non-YUI scripts:</p>\n\n<p><a href=\"http://developer.yahoo.com/yui/examples/yuiloader/yl-addmodule.html\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/yui/examples/yuiloader/yl-addmodule.html</a></p>\n" }, { "answer_id": 203139, "author": "abahgat", "author_id": 27565, "author_profile": "https://Stackoverflow.com/users/27565", "pm_score": 2, "selected": false, "text": "<p>If you're using a higher level framework such as JQuery, you could check out the <code>$.getScript(url, callback)</code> function.</p>\n" }, { "answer_id": 204100, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 2, "selected": false, "text": "<p>If you want your code on the very next line and like to write something like: </p>\n\n<pre><code>if (iNeedSomeMore){\n Script.load(\"myBigCodeLibrary.js\"); // includes code for myFancyMethod();\n myFancyMethod(); // cool, no need for callbacks!\n}\n</code></pre>\n\n<p>There is a smart way to inject script dependencies <em>without the need of callbacks</em>. You simply have to pull the script via a <em>synchronous AJAX request</em> and eval the script on global level. </p>\n\n<p>If you use Prototype the Script.load method looks like this:</p>\n\n<pre><code>var Script = {\n _loadedScripts: [],\n include: function(script){\n // include script only once\n if (this._loadedScripts.include(script)){\n return false;\n }\n // request file synchronous\n var code = new Ajax.Request(script, {\n asynchronous: false, method: \"GET\",\n evalJS: false, evalJSON: false\n }).transport.responseText;\n // eval code on global level\n if (Prototype.Browser.IE) {\n window.execScript(code);\n } else if (Prototype.Browser.WebKit){\n $$(\"head\").first().insert(Object.extend(\n new Element(\"script\", {type: \"text/javascript\"}), {text: code}\n ));\n } else {\n window.eval(code);\n }\n // remember included script\n this._loadedScripts.push(script);\n }\n};\n</code></pre>\n" }, { "answer_id": 1469125, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>None of these methods, including document.writing a script tag, work if the script itself has a document.write in it.</p>\n" }, { "answer_id": 15978307, "author": "stamat", "author_id": 1909864, "author_profile": "https://Stackoverflow.com/users/1909864", "pm_score": 0, "selected": false, "text": "<p>I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: <a href=\"http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/\" rel=\"nofollow\">http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/</a></p>\n\n<pre><code>// ----- USAGE -----\n\nrequire('ivar.util.string');\nrequire('ivar.net.*');\nrequire('ivar/util/array.js');\nrequire('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');\n\nready(function(){\n //do something when required scripts are loaded\n});\n\n //--------------------\n\nvar _rmod = _rmod || {}; //require module namespace\n_rmod.LOADED = false;\n_rmod.on_ready_fn_stack = [];\n_rmod.libpath = '';\n_rmod.imported = {};\n_rmod.loading = {\n scripts: {},\n length: 0\n};\n\n_rmod.findScriptPath = function(script_name) {\n var script_elems = document.getElementsByTagName('script');\n for (var i = 0; i &lt; script_elems.length; i++) {\n if (script_elems[i].src.endsWith(script_name)) {\n var href = window.location.href;\n href = href.substring(0, href.lastIndexOf('/'));\n var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);\n return url.substring(href.length+1, url.length);\n }\n }\n return '';\n};\n\n_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library\n\n\n_rmod.injectScript = function(script_name, uri, callback, prepare) {\n\n if(!prepare)\n prepare(script_name, uri);\n\n var script_elem = document.createElement('script');\n script_elem.type = 'text/javascript';\n script_elem.title = script_name;\n script_elem.src = uri;\n script_elem.async = true;\n script_elem.defer = false;\n\n if(!callback)\n script_elem.onload = function() {\n callback(script_name, uri);\n };\n\n document.getElementsByTagName('head')[0].appendChild(script_elem);\n};\n\n_rmod.requirePrepare = function(script_name, uri) {\n _rmod.loading.scripts[script_name] = uri;\n _rmod.loading.length++;\n};\n\n_rmod.requireCallback = function(script_name, uri) {\n _rmod.loading.length--;\n delete _rmod.loading.scripts[script_name];\n _rmod.imported[script_name] = uri;\n\n if(_rmod.loading.length == 0)\n _rmod.onReady();\n};\n\n_rmod.onReady = function() {\n if (!_rmod.LOADED) {\n for (var i = 0; i &lt; _rmod.on_ready_fn_stack.length; i++){\n _rmod.on_ready_fn_stack[i]();\n });\n _rmod.LOADED = true;\n }\n};\n\n_.rmod = namespaceToUri = function(script_name, url) {\n var np = script_name.split('.');\n if (np.getLast() === '*') {\n np.pop();\n np.push('_all');\n }\n\n if(!url)\n url = '';\n\n script_name = np.join('.');\n return url + np.join('/')+'.js';\n};\n\n//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.\nvar require = function(script_name) {\n var uri = '';\n if (script_name.indexOf('/') &gt; -1) {\n uri = script_name;\n var lastSlash = uri.lastIndexOf('/');\n script_name = uri.substring(lastSlash+1, uri.length);\n } else {\n uri = _rmod.namespaceToUri(script_name, ivar._private.libpath);\n }\n\n if (!_rmod.loading.scripts.hasOwnProperty(script_name) \n &amp;&amp; !_rmod.imported.hasOwnProperty(script_name)) {\n _rmod.injectScript(script_name, uri, \n _rmod.requireCallback, \n _rmod.requirePrepare);\n }\n};\n\nvar ready = function(fn) {\n _rmod.on_ready_fn_stack.push(fn);\n};\n</code></pre>\n" }, { "answer_id": 18819017, "author": "Aditya M P", "author_id": 443219, "author_profile": "https://Stackoverflow.com/users/443219", "pm_score": 0, "selected": false, "text": "<p>Consider using <a href=\"http://requirejs.org/\" rel=\"nofollow\">require.js</a>. This might need some rework of your frontend framework, but it's totally worth it. With require, you could just do the following in your <code>fileUsedOccasionally.js</code>:</p>\n\n<pre>\ndefine(['swfObject', 'someOtherDependency'], function (swfObject, someOtherDependency) {\n // you can now use swfObject as a JS object! you can call it whatever you want\n // you'll have to write a swfObject.js to wrap it with require\n // but that's trivial\n});\n</pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I have a JS function that may occasionally get used on some pages. It is dependent on another JS file (swfObject.js), but I'd like to avoid having to include this file all over the place, as thats a wasted request most of the time. Instead, I'd like to create a generic function that can inject a script reference into the page DOM as needed, so if this function is called, it would check for the script, and if it does not exist, load it in. I'm fairly sure this is possible (and I'm not going to use document.write), but before I venture off into uncharted territory, has anyone done this before, and if so, any pointers? EDIT: Ok, I tried it, and it works in IE6 and FF, I haven't tested other browsers yet. Here is my code (Rev 2.0, now with optional callbacks): ``` function loadJSInclude(scriptPath, callback) { var scriptNode = document.createElement('SCRIPT'); scriptNode.type = 'text/javascript'; scriptNode.src = scriptPath; var headNode = document.getElementsByTagName('HEAD'); if (headNode[0] != null) headNode[0].appendChild(scriptNode); if (callback != null) { scriptNode.onreadystagechange = callback; scriptNode.onload = callback; } } ``` and in the method with a dependency: ``` var callbackMethod = function () { // Code to do after loading swfObject } // Include SWFObject if its needed if (typeof(SWFObject) == 'undefined') loadJSInclude('/js/swfObject.js', callbackMethod); else calbackMethod(); ``` Any suggestions?
If you're using a higher level framework such as JQuery, you could check out the `$.getScript(url, callback)` function.
203,126
<p>Here is an example of polymorphism from <a href="http://www.cplusplus.com/doc/tutorial/polymorphism.html" rel="noreferrer">http://www.cplusplus.com/doc/tutorial/polymorphism.html</a> (edited for readability):</p> <pre><code>// abstract base class #include &lt;iostream&gt; using namespace std; class Polygon { protected: int width; int height; public: void set_values(int a, int b) { width = a; height = b; } virtual int area(void) =0; }; class Rectangle: public Polygon { public: int area(void) { return width * height; } }; class Triangle: public Polygon { public: int area(void) { return width * height / 2; } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &amp;rect; Polygon * ppoly2 = &amp;trgl; ppoly1-&gt;set_values (4,5); ppoly2-&gt;set_values (4,5); cout &lt;&lt; ppoly1-&gt;area() &lt;&lt; endl; // outputs 20 cout &lt;&lt; ppoly2-&gt;area() &lt;&lt; endl; // outputs 10 return 0; } </code></pre> <p>My question is how does the compiler know that ppoly1 is a Rectangle and that ppoly2 is a Triangle, so that it can call the correct area() function? It could find that out by looking at the "Polygon * ppoly1 = &rect;" line and knowing that rect is a Rectangle, but that wouldn't work in all cases, would it? What if you did something like this?</p> <pre><code>cout &lt;&lt; ((Polygon *)0x12345678)-&gt;area() &lt;&lt; endl; </code></pre> <p>Assuming that you're allowed to access that random area of memory.</p> <p>I would test this out but I can't on the computer I'm on at the moment.</p> <p>(I hope I'm not missing something obvious...)</p>
[ { "answer_id": 203135, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "<p>Disregarding aspects of binding, it's not actually the compiler that determines this.</p>\n\n<p>It is the C++ runtime that evaluates, via vtables and vpointers, what the derived object actually is at runtime.</p>\n\n<p>I highly recommend Scott Meyer's book Effective C++ for good descriptions on how this is done.</p>\n\n<p>Even covers how default parameters in a method in a derived class are ignored and any default parameters in a base class are still taken! That's binding.</p>\n" }, { "answer_id": 203136, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "<p>Each object (that belongs to a class with at least one virtual function) has a pointer, called a <code>vptr</code>. It points to the <code>vtbl</code> of its actual class (which each class with virtual functions has at least one of; possibly more than one for some multiple-inheritance scenarios).</p>\n\n<p>The <code>vtbl</code> contains a bunch of pointers, one for each virtual function. So at runtime, the code just uses the object's <code>vptr</code> to locate the <code>vtbl</code>, and from there the address of the actual overridden function.</p>\n\n<p>In your specific case, <code>Polygon</code>, <code>Rectangle</code>, and <code>Triangle</code> each has a <code>vtbl</code>, each with one entry pointing to its relevant <code>area</code> method. Your <code>ppoly1</code> will have a <code>vptr</code> pointing to <code>Rectangle</code>'s <code>vtbl</code>, and <code>ppoly2</code> similarly with <code>Triangle</code>'s <code>vtbl</code>. Hope this helps!</p>\n" }, { "answer_id": 203143, "author": "Zach Snow", "author_id": 25381, "author_profile": "https://Stackoverflow.com/users/25381", "pm_score": 1, "selected": false, "text": "<p>To answer the second part of your question: that address probably won't have a v-table in the right place, and madness will ensue. Also, it's undefined according to the standard.</p>\n" }, { "answer_id": 203149, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/203126/how-does-the-c-compiler-know-which-implementation-of-a-virtual-function-to-call#203136\">Chris Jester-Young</a> gives the basic answer to this question.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Virtual_table\" rel=\"nofollow noreferrer\">Wikipedia</a> has a more in depth treatment.</p>\n\n<p>If you want to know the full details for how this type of thing works (and for all type of inheritance, including multiple and virtual inheritance), one of the best resources is Stan Lippman's \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/0201834545\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Inside the C++ Object Model</a>\".</p>\n" }, { "answer_id": 203167, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "<pre><code>cout &lt;&lt; ((Polygon *)0x12345678)-&gt;area() &lt;&lt; endl;\n</code></pre>\n\n<p>This code is a disaster waiting to happen. The compiler will compile it all right but when it comes to run time, you will not be pointing to a valid v-table and if you are lucky the program will just crash.</p>\n\n<p>In C++, you shouldn't use old C-style casts like this, you should use <strong>dynamic_cast</strong> like so:</p>\n\n<pre><code>Polygon *obj = dynamic_cast&lt;Polygon *&gt;(0x12345678)-&gt;area();\nASSERT(obj != NULL);\n\ncout &lt;&lt; obj-&gt;area() &lt;&lt; endl;\n</code></pre>\n\n<p>dynamic_cast will return NULL if the given pointer is not a valid Polygon object so it will be trapped by the ASSERT.</p>\n" }, { "answer_id": 203169, "author": "Paul Sonier", "author_id": 28053, "author_profile": "https://Stackoverflow.com/users/28053", "pm_score": 1, "selected": false, "text": "<p>Virtual function tables. To wit, both of your Polygon-derived objects have a virtual function table that contains function pointers to the implementations of all their (non-static) functions; and when you instantiate a Triangle, the virtual function pointer for the area() function points to the Triangle::area() function; when you instantiate a Rectangle, the area() function points to the Rectangle::area() function. Because virtual function pointers are stored along with the data for an object in memory, every time you reference that object as a Polygon, the appropriate area() for that object will be used.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
Here is an example of polymorphism from <http://www.cplusplus.com/doc/tutorial/polymorphism.html> (edited for readability): ``` // abstract base class #include <iostream> using namespace std; class Polygon { protected: int width; int height; public: void set_values(int a, int b) { width = a; height = b; } virtual int area(void) =0; }; class Rectangle: public Polygon { public: int area(void) { return width * height; } }; class Triangle: public Polygon { public: int area(void) { return width * height / 2; } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << endl; // outputs 20 cout << ppoly2->area() << endl; // outputs 10 return 0; } ``` My question is how does the compiler know that ppoly1 is a Rectangle and that ppoly2 is a Triangle, so that it can call the correct area() function? It could find that out by looking at the "Polygon \* ppoly1 = ▭" line and knowing that rect is a Rectangle, but that wouldn't work in all cases, would it? What if you did something like this? ``` cout << ((Polygon *)0x12345678)->area() << endl; ``` Assuming that you're allowed to access that random area of memory. I would test this out but I can't on the computer I'm on at the moment. (I hope I'm not missing something obvious...)
Each object (that belongs to a class with at least one virtual function) has a pointer, called a `vptr`. It points to the `vtbl` of its actual class (which each class with virtual functions has at least one of; possibly more than one for some multiple-inheritance scenarios). The `vtbl` contains a bunch of pointers, one for each virtual function. So at runtime, the code just uses the object's `vptr` to locate the `vtbl`, and from there the address of the actual overridden function. In your specific case, `Polygon`, `Rectangle`, and `Triangle` each has a `vtbl`, each with one entry pointing to its relevant `area` method. Your `ppoly1` will have a `vptr` pointing to `Rectangle`'s `vtbl`, and `ppoly2` similarly with `Triangle`'s `vtbl`. Hope this helps!
203,147
<p>Here's another C#/.NET question based merely on curiousity more than an immediate <em>need</em> ...</p> <p>If you had a <code>Socket</code> instance and you wanted to wrap it in the higher-level <code>TcpClient</code> class, is that possible and how would you do it?</p> <p>Conversely if you have an instance of <code>TcpClient</code>, is it possible to get the underlying <code>Socket</code>?</p>
[ { "answer_id": 203153, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 2, "selected": false, "text": "<p>From TcpClient to Socket is very easy. <code>tcpClientInstance.Client</code> is the underlying Socket instance.</p>\n" }, { "answer_id": 203160, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": true, "text": "<blockquote>\n <p>If you had a Socket instance and you\n wanted to wrap it in the higher-level\n TcpClient class, is that possible and\n how would you do it?</p>\n</blockquote>\n\n<pre><code>Socket socket = ...;\nTcpClient client = new TcpClient();\nclient.Client = socket;\n</code></pre>\n\n<blockquote>\n <p>Conversely if you have an instance of\n TcpClient, is it possible to get the\n underlying Socket?</p>\n</blockquote>\n\n<p>Get the underlying Socket using <a href=\"http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.client.aspx\" rel=\"noreferrer\">TcpClient.Client</a> property.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
Here's another C#/.NET question based merely on curiousity more than an immediate *need* ... If you had a `Socket` instance and you wanted to wrap it in the higher-level `TcpClient` class, is that possible and how would you do it? Conversely if you have an instance of `TcpClient`, is it possible to get the underlying `Socket`?
> > If you had a Socket instance and you > wanted to wrap it in the higher-level > TcpClient class, is that possible and > how would you do it? > > > ``` Socket socket = ...; TcpClient client = new TcpClient(); client.Client = socket; ``` > > Conversely if you have an instance of > TcpClient, is it possible to get the > underlying Socket? > > > Get the underlying Socket using [TcpClient.Client](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.client.aspx) property.
203,151
<p>I have a report that uses a TChart that I am maintaining. One of the TLineSeries that gets added automatically gets assigned the color clWhite, which is too close to the background (clBtnFace). </p> <p>If I change it, then the next series that gets added takes clWhite. So short of going back and changing it after all the other series are created, is there some way to tell the TChart that I don't want any of my series to be clWhite?</p> <p>When a series is added to the TChart the TChart assigns it a color. I want it to not assign clWhite.</p>
[ { "answer_id": 203236, "author": "Anya Shenanigans", "author_id": 17833, "author_profile": "https://Stackoverflow.com/users/17833", "pm_score": 2, "selected": false, "text": "<p>Near as I can tell from the TeeCharts module; no you can't specify a color that it should not be as it ships.<br>\nYou can programatically walk through all the TLineSeries entries making sure at run-time that they don't use clWhite. \nSay you have an array of acceptable colors clArray, you can use the following code to set the colors of each of the tLineSeries entries at run time. </p>\n\n<pre><code>procedure TForm1.setColors(aChart: TChart; aColorArray: array of TColor);\nvar\n chi : Integer;\n coi : Integer;\nbegin\n coi := low(aColorArray);\n for chi := 0 to aChart.SeriesList.Count - 1 do begin\n aChart.SeriesList[chi].Color := aColorArray[coi];\n inc(coi);\n if coi &gt; high(aColorArray) then\n coi := low(aColorArray);\n end;\nend;\n\nprocedure TForm1.FormShow(Sender: TObject);\nvar\n ca : array of TColor;\nbegin\n setLength(ca, 3);\n ca[0] := clRed;\n ca[1] := clBlue;\n ca[2] := clGreen;\n setColors(Chart1, ca);\nend;\n</code></pre>\n" }, { "answer_id": 203365, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 4, "selected": true, "text": "<p>OK not one to give up easily, I did some more searching. There is a unit variable called <strong>ColorPalette</strong> of type <em>TColorArray</em> in the <em>TeeProcs</em> unit. If I find and replace white with a different color that fixes it. There may be an instance copy of it. I'll keep looking since that would be preferred.</p>\n\n<p>To revert the <strong>ColorPalette</strong> back just call the unit method <strong>SetDefaultColorPalette</strong> in the same unit.</p>\n\n<pre><code>SetDefaultColorPalette; // Make sure we start with the default\nColorPalette[4] := $007FFF; // Change White to Orange\ntry\n // add series to the chart\nfinally\n SetDefaultColorPalette; // Set it back to Default\nend;\n</code></pre>\n\n<p>BTW, I can't <strong>accept as answer</strong> because I asked the question too, but I tested it and it works.</p>\n" }, { "answer_id": 203396, "author": "Argalatyr", "author_id": 18484, "author_profile": "https://Stackoverflow.com/users/18484", "pm_score": 0, "selected": false, "text": "<p>You can use the series methods ClearPalette then AddPalette to create your custom palette.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/255/" ]
I have a report that uses a TChart that I am maintaining. One of the TLineSeries that gets added automatically gets assigned the color clWhite, which is too close to the background (clBtnFace). If I change it, then the next series that gets added takes clWhite. So short of going back and changing it after all the other series are created, is there some way to tell the TChart that I don't want any of my series to be clWhite? When a series is added to the TChart the TChart assigns it a color. I want it to not assign clWhite.
OK not one to give up easily, I did some more searching. There is a unit variable called **ColorPalette** of type *TColorArray* in the *TeeProcs* unit. If I find and replace white with a different color that fixes it. There may be an instance copy of it. I'll keep looking since that would be preferred. To revert the **ColorPalette** back just call the unit method **SetDefaultColorPalette** in the same unit. ``` SetDefaultColorPalette; // Make sure we start with the default ColorPalette[4] := $007FFF; // Change White to Orange try // add series to the chart finally SetDefaultColorPalette; // Set it back to Default end; ``` BTW, I can't **accept as answer** because I asked the question too, but I tested it and it works.
203,161
<p>Im just writing a small Ajax framework for re-usability in small projects and i've hit a problem. Basically i get a '<code>NS_ERROR_ILLEGAL_VALUE</code>' error while sending the request and i've no idea what is happening.</p> <p>The HTML Page (trimmed but shows the error)</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;Ajax Test&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script type="text/javascript"&gt; var COMPLETE = 4; var OK = 200; function GetXMLHttpRequestObject() { var XMLHttpRequestObject = false; if(window.XMLHttpRequest) { if(typeof XMLHttpRequest != 'undefined') { try { XMLHttpRequestObject = new XMLHttpRequest(); } catch (e) { XMLHttpRequestObject = false; } } } else if (window.ActiveXObject) { try { XMLHttpRequestObject = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { XMLHttpRequestObject = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { XMLHttpRequestObject = false; } } } else { XMLHttpRequestObject = false; } return XMLHttpRequestObject; } //The Main Ajax Object function AjaxRequest(p_RequestMethod, p_DestinationURL) { this.XMLHttpRequestObject = GetXMLHttpRequestObject(); this.RequestedMethod = p_RequestMethod; this.DestinationURL = p_DestinationURL; this.XMLHttpRequestObject.open(this.RequestMethod, this.DestinationURL); this.OnStateChange = function(Callback) { this.XMLHttpRequestObject.onreadystatechange = Callback; } this.Send = function(p_Content) { this.XMLHttpRequestObject.send(p_Content); } this.GetState() { return this.XMLHttpRequestObject.readyState; } this.GetResponseText = function() { return this.XMLHttpRequestObject.responseText; } this.GetResponseStatus = function() { return this.XMLHttpRequestObject.status; } this.GetResponseStatusText = function() { return this.XMLHttpRequestObject.statusText; } } var Request; function GetData() { Request = new AjaxRequest('POST', 'http://www.kalekold.net/ajax/Ajax.php'); Request.OnStateChange = StateChange; Request.Send(); } function StateChange() { window.alert("State: " + Request.GetState()); window.alert("Response: " + Request.GetResponseStatus()); window.alert("Response Text: " + Request.GetResponseStatusText()); if(Request.GetState() == COMPLETE &amp;&amp; Request.GetResponseStatus() == OK) { Result = Request.GetResponseText(); window.alert(Result); } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;textarea name="TextArea" rows="10" cols="80"&gt;&lt;/textarea&gt;&lt;br /&gt; &lt;input type="button" value="Load" onClick="GetData();"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The PHP File:</p> <pre><code>&lt;?php $XML = &lt;&lt;&lt; PROLOG &lt;?xml version="1.0" encoding="iso-8859-1"?&gt; PROLOG; $XML .= "&lt;results&gt;"; $XML .= "&lt;result&gt;"; $XML .= "&lt;FirstName&gt;Gary&lt;/FirstName&gt;"; $XML .= "&lt;SecondName&gt;Willoughby&lt;/SecondName&gt;"; $XML .= "&lt;Age&gt;35&lt;/Age&gt;"; $XML .= "&lt;/result&gt;"; $XML .= "&lt;result&gt;"; $XML .= "&lt;FirstName&gt;Sara&lt;/FirstName&gt;"; $XML .= "&lt;SecondName&gt;Gostick&lt;/SecondName&gt;"; $XML .= "&lt;Age&gt;35&lt;/Age&gt;"; $XML .= "&lt;/result&gt;"; $XML .= "&lt;/results&gt;"; header("Content-Type: text/xml"); echo $XML; ?&gt; </code></pre> <p>The full error:</p> <pre><code>uncaught exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXMLHttpRequest.open]" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: http://www.kalekold.net/ajax/ :: AjaxRequest :: line 63" data: no] Line 0 </code></pre> <p>I just can't see where it's going wrong, any ideas?</p>
[ { "answer_id": 204039, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 4, "selected": true, "text": "<p>The exception \"Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE)\" is caused by an illegal value being passed into the call of open method.</p>\n\n<p>Looking through your code I found misspelling:</p>\n\n<pre>\nthis.RequestedMethod = p_RequestMethod;\nthis.DestinationURL = p_DestinationURL;\n\nthis.XMLHttpRequestObject.open(this.RequestMethod, this.DestinationURL);\n</pre>\n\n<p>See this.RequestedMethod property set to p_RequestMethod and this.RequestMethod being passed into the call of \"open\" method.</p>\n\n<p>Also, instead of creating your own wrapper, I would recommend using open-source <a href=\"http://code.google.com/p/xmlhttprequest/\" rel=\"nofollow noreferrer\">XMLHttpRequest.js</a> - Standard-compliant cross-browser XMLHttpRequest object implementation, that also fixes some 20 bugs of browser's native XMLHttpRequest object implementations.</p>\n" }, { "answer_id": 204048, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "<p>This error message is one of the 'quirks' of FireFox's XMLHttpRequest object. The same issue in IE will have different symptoms.</p>\n\n<p>You don't want to deal with all these quirks yourself now that there's lots of good libraries out there. </p>\n\n<p>For instance in Netscape and FX calling <code>XMLHttpRequestObject.responseText</code> or <code>XMLHttpRequestObject.status</code> throws an \"NS_...\" error for any connection problems. IE will returns the OS network error code instead - no error thrown. If you handle this yourself you will have to build in the error handling for both.</p>\n\n<p>I would recommend <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>. <a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">Prototype</a> is also excellent.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
Im just writing a small Ajax framework for re-usability in small projects and i've hit a problem. Basically i get a '`NS_ERROR_ILLEGAL_VALUE`' error while sending the request and i've no idea what is happening. The HTML Page (trimmed but shows the error) ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Ajax Test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> var COMPLETE = 4; var OK = 200; function GetXMLHttpRequestObject() { var XMLHttpRequestObject = false; if(window.XMLHttpRequest) { if(typeof XMLHttpRequest != 'undefined') { try { XMLHttpRequestObject = new XMLHttpRequest(); } catch (e) { XMLHttpRequestObject = false; } } } else if (window.ActiveXObject) { try { XMLHttpRequestObject = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { XMLHttpRequestObject = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { XMLHttpRequestObject = false; } } } else { XMLHttpRequestObject = false; } return XMLHttpRequestObject; } //The Main Ajax Object function AjaxRequest(p_RequestMethod, p_DestinationURL) { this.XMLHttpRequestObject = GetXMLHttpRequestObject(); this.RequestedMethod = p_RequestMethod; this.DestinationURL = p_DestinationURL; this.XMLHttpRequestObject.open(this.RequestMethod, this.DestinationURL); this.OnStateChange = function(Callback) { this.XMLHttpRequestObject.onreadystatechange = Callback; } this.Send = function(p_Content) { this.XMLHttpRequestObject.send(p_Content); } this.GetState() { return this.XMLHttpRequestObject.readyState; } this.GetResponseText = function() { return this.XMLHttpRequestObject.responseText; } this.GetResponseStatus = function() { return this.XMLHttpRequestObject.status; } this.GetResponseStatusText = function() { return this.XMLHttpRequestObject.statusText; } } var Request; function GetData() { Request = new AjaxRequest('POST', 'http://www.kalekold.net/ajax/Ajax.php'); Request.OnStateChange = StateChange; Request.Send(); } function StateChange() { window.alert("State: " + Request.GetState()); window.alert("Response: " + Request.GetResponseStatus()); window.alert("Response Text: " + Request.GetResponseStatusText()); if(Request.GetState() == COMPLETE && Request.GetResponseStatus() == OK) { Result = Request.GetResponseText(); window.alert(Result); } } </script> </head> <body> <form> <textarea name="TextArea" rows="10" cols="80"></textarea><br /> <input type="button" value="Load" onClick="GetData();"> </form> </body> </html> ``` The PHP File: ``` <?php $XML = <<< PROLOG <?xml version="1.0" encoding="iso-8859-1"?> PROLOG; $XML .= "<results>"; $XML .= "<result>"; $XML .= "<FirstName>Gary</FirstName>"; $XML .= "<SecondName>Willoughby</SecondName>"; $XML .= "<Age>35</Age>"; $XML .= "</result>"; $XML .= "<result>"; $XML .= "<FirstName>Sara</FirstName>"; $XML .= "<SecondName>Gostick</SecondName>"; $XML .= "<Age>35</Age>"; $XML .= "</result>"; $XML .= "</results>"; header("Content-Type: text/xml"); echo $XML; ?> ``` The full error: ``` uncaught exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXMLHttpRequest.open]" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: http://www.kalekold.net/ajax/ :: AjaxRequest :: line 63" data: no] Line 0 ``` I just can't see where it's going wrong, any ideas?
The exception "Component returned failure code: 0x80070057 (NS\_ERROR\_ILLEGAL\_VALUE)" is caused by an illegal value being passed into the call of open method. Looking through your code I found misspelling: ``` this.RequestedMethod = p_RequestMethod; this.DestinationURL = p_DestinationURL; this.XMLHttpRequestObject.open(this.RequestMethod, this.DestinationURL); ``` See this.RequestedMethod property set to p\_RequestMethod and this.RequestMethod being passed into the call of "open" method. Also, instead of creating your own wrapper, I would recommend using open-source [XMLHttpRequest.js](http://code.google.com/p/xmlhttprequest/) - Standard-compliant cross-browser XMLHttpRequest object implementation, that also fixes some 20 bugs of browser's native XMLHttpRequest object implementations.
203,171
<p>How can I include a bookmarklet in a Markdown parsed document? Is there any "tag" for markdown that basically says "don't parse this"??</p> <p>For example you could have something like:</p> <pre><code>&lt;a href="javascript:function my_bookmarklet() {alert('Hello World');} my_bookmarklet();"&gt;Hello&lt;/a&gt; </code></pre> <p>But if I try to past the javascript from that into a link in markdown like this: </p> <pre><code>[Hello World!](javascript:function my_bookmarklet(){alert('Hello World');}my_bookmarklet();) </code></pre> <p>You get a messed up link, like below.</p> <p>[Hello World!](javascript:function my_bookmarklet(){alert('Hello World');}my_bookmarklet();)</p> <p>Is there anyway around this?</p> <p>And no, I'm not trying to put malicious bookmarklets in SO or anything, but I want to use markdown for my site and would like to post some bookmarklets I wrote.</p> <p>Edit: I thought I had the answer...but now it seems I don't quite have it.</p> <p>This seems to work great in WMD and showdown, but in the Markdown.php editor, it does not. Anyone have experience with Markdown.php specifically?</p>
[ { "answer_id": 203179, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 4, "selected": true, "text": "<p>Markdown will leave any HTML alone, so you can just enter</p>\n\n<pre><code>&lt;a href=\"javascript:function my_bookmarklet()\n {alert('Hello World');}\n my_bookmarklet();\"&gt;Hello&lt;/a&gt;\n</code></pre>\n\n<p><del>and get Hello.</del> <em>Edit: No longer works on SO, which is a good thing</em></p>\n\n<p>You can also escape special characters with a backslash (in this case it's seeing the \")\"s in your Javascript as the end of the URL) and the link syntax will work:</p>\n\n<pre><code>[Hello](javascript:function my_bookmarklet(\\){alert('Hello World'\\);}my_bookmarklet(\\);)\n</code></pre>\n\n<p><del>gives [Hello](javascript:function my_bookmarklet(){alert('Hello World');}my_bookmarklet();)</del></p>\n" }, { "answer_id": 8686841, "author": "Zombo", "author_id": 1002260, "author_profile": "https://Stackoverflow.com/users/1002260", "pm_score": 3, "selected": false, "text": "<pre><code>[Hello World!][1]\n[1]:javascript:alert('Hello World')\n</code></pre>\n" }, { "answer_id": 49807294, "author": "Michael S", "author_id": 4904320, "author_profile": "https://Stackoverflow.com/users/4904320", "pm_score": 2, "selected": false, "text": "<p>I know this is a very old question, but (in case someone else finds their way here, as I did), if you url-encode your script, it will work.</p>\n\n<p>For example:</p>\n\n<pre><code> [Hello World](javascript:%28function%28%29%7Balert%28%22Hello%20World%22%29%7D%29%28%29%3B)\n</code></pre>\n\n<p>And of course, as mentioned above, it does not work here, on SO.</p>\n\n<p>Note: Some url-encoders will replace space (\" \") with a \"+\", which works fine for regular urls, but not js code, spaces should be replaced with \"%20\"</p>\n\n<p><strong>EDIT</strong>: This doesn't seem to be universally true. I suppose the specific markdown parser makes the final call here. But this works for me in more places where markdown is used.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
How can I include a bookmarklet in a Markdown parsed document? Is there any "tag" for markdown that basically says "don't parse this"?? For example you could have something like: ``` <a href="javascript:function my_bookmarklet() {alert('Hello World');} my_bookmarklet();">Hello</a> ``` But if I try to past the javascript from that into a link in markdown like this: ``` [Hello World!](javascript:function my_bookmarklet(){alert('Hello World');}my_bookmarklet();) ``` You get a messed up link, like below. [Hello World!](javascript:function my\_bookmarklet(){alert('Hello World');}my\_bookmarklet();) Is there anyway around this? And no, I'm not trying to put malicious bookmarklets in SO or anything, but I want to use markdown for my site and would like to post some bookmarklets I wrote. Edit: I thought I had the answer...but now it seems I don't quite have it. This seems to work great in WMD and showdown, but in the Markdown.php editor, it does not. Anyone have experience with Markdown.php specifically?
Markdown will leave any HTML alone, so you can just enter ``` <a href="javascript:function my_bookmarklet() {alert('Hello World');} my_bookmarklet();">Hello</a> ``` ~~and get Hello.~~ *Edit: No longer works on SO, which is a good thing* You can also escape special characters with a backslash (in this case it's seeing the ")"s in your Javascript as the end of the URL) and the link syntax will work: ``` [Hello](javascript:function my_bookmarklet(\){alert('Hello World'\);}my_bookmarklet(\);) ``` ~~gives [Hello](javascript:function my\_bookmarklet(){alert('Hello World');}my\_bookmarklet();)~~
203,180
<p>Say I have my sources in my src/ tree (and possibly in my test/ tree). Say I would like to compile only <em>part</em> of that tree. The reasons why I might want to do that are various. Just as an example, I might want to create the smallest possible jar (without including certain classes), or I might want the fastest compile time for what I am compiling. I absolutely want to compile all the dependencies, though!</p> <p>This can be easily achieved from the command line with:</p> <pre><code>javac -d build/ -cp whatever -sourcepath src src/path/to/MyClass.java </code></pre> <p>Now, how can you do that with ant? The javac ant <a href="http://ant.apache.org/manual/Tasks/javac.html" rel="noreferrer">task compiles everything</a>:</p> <blockquote> <p>The source and destination directory will be recursively scanned for Java source files to compile.</p> </blockquote> <p>One can use the <code>excludes</code> and <code>includes</code> parameters, but they are problematic for this purpose. In fact, it seems that one has to explicitly setup all the <code>includes</code> (not automatic dependency lookup), and <strong>even worst</strong> that <a href="http://ant.apache.org/manual/dirtasks.html#patternset" rel="noreferrer">excludes has priority on includes</a>:</p> <blockquote> <p>When both inclusion and exclusion are used, only files/directories that match at least one of the include patterns and don't match <em>any</em> of the exclude patterns are used.</p> </blockquote> <p>Thus, you cannot use </p> <pre><code>&lt;javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" excludes="**/*.java" includes="src/path/to/MyClass.java" /&gt; </code></pre> <p>Because it will not compile anything :-(</p> <p>Is there any way of achieving that simple command line <code>javac</code> with ant?</p> <hr> <p>EDITED: Thank you for your answer, Sadie, I'm accepting it, because it does work in the way I was wondering in this question. But I have a couple of comments (too long to be in the comment field of your answer):</p> <p>1) I did read the documentation (see links above), but it's unclear that with just <code>includes</code> you are actually also excluding everything else</p> <p>2) When you just <code>includes</code> ant logs something like</p> <pre><code>[javac] Compiling 1 source file to /my/path/to/build </code></pre> <p>even if the dependencies make it compiling (much) more than just one source file.</p>
[ { "answer_id": 203472, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 0, "selected": false, "text": "<p>Actually, ant only <em>checks</em> everything, if you run a compile twice in a row you will notice the second is much quicker. Actually, it can be easily persuaded to miss things.</p>\n\n<p>If you don't even want it to consider everything, you're going to have to break it down into smaller modules/projects/source trees so that you're explicitly telling ant what to compile.</p>\n" }, { "answer_id": 203552, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 5, "selected": true, "text": "<p>Why are you excluding as well as including? If you have at least one include, then files are only compiled if they're explicitly included. So this should work:</p>\n\n<pre><code>&lt;javac srcdir=\"${src.dir}\" destdir=\"${build.dir}\" classpathref=\"classpath\"\n includes=\"src/path/to/MyClass.java\" /&gt;\n</code></pre>\n\n<p>Or more flexibly:</p>\n\n<pre><code>&lt;javac srcdir=\"${src.dir}\" destdir=\"${build.dir}\" classpathref=\"classpath\"&gt;\n &lt;include name=\"src/path/to/MyClass.java\"/&gt;\n &lt;include name=\"src/path/to/AnotherClass.java\"/&gt;\n&lt;/javac&gt;\n</code></pre>\n\n<p>To include only certain packages or classes in a jar, use a fileset attribute</p>\n\n<pre><code>&lt;jar jarfile=\"${outlib}/something.jar\"&gt;\n &lt;fileset dir=\"${build.dir}\"&gt;\n &lt;include name='src/path/to/classes' /&gt;\n &lt;/fileset&gt;\n&lt;/jar&gt;\n</code></pre>\n\n<p>Again, you can use multiple includes to combine separate packages. Experiment with includes and <a href=\"http://ant.apache.org/manual/\" rel=\"noreferrer\">read the documentation</a> and you're sure to find the answer you need.</p>\n" }, { "answer_id": 17261455, "author": "Ankit", "author_id": 2513729, "author_profile": "https://Stackoverflow.com/users/2513729", "pm_score": 0, "selected": false, "text": "<p>Just give only the comma seperated list of files that you want to build. Lets say example</p>\n\n<pre><code>&lt;property name=\"includeFileList\" value=\"&lt;name of java class&gt;.java\"/&gt;\n\n&lt;javac srcdir=\"${src.dir}\" destdir=\"${build.dir}\"\n target=\"1.6\" debug=\"true\" includes=\"${includeFileList}\"/&gt;\n</code></pre>\n\n<p>It will work.</p>\n" }, { "answer_id": 31367984, "author": "Tor P", "author_id": 1218054, "author_profile": "https://Stackoverflow.com/users/1218054", "pm_score": 2, "selected": false, "text": "<p>Old question, but I was struggling with the same problem and found a a more elegant solution. So here it is, for future reference:</p>\n\n<p>According to the ant docs the <code>&lt;javac&gt;</code> element is an implicit <code>&lt;fileset&gt;</code> and as such can take <a href=\"https://ant.apache.org/manual/Types/selectors.html\" rel=\"nofollow\" title=\"Selectors\">Selectors</a> like <code>&lt;filename name=\"**/MyClass.java\"/&gt;</code>, so this would only compile MyClass.java:</p>\n\n<pre><code>&lt;javac srcdir=\"${src.dir}\" destdir=\"${build.dir}\" classpathref=\"classpath\"&gt;\n &lt;filename name=\"**/path/to/MyClass.java\"/&gt;\n&lt;/javac&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25891/" ]
Say I have my sources in my src/ tree (and possibly in my test/ tree). Say I would like to compile only *part* of that tree. The reasons why I might want to do that are various. Just as an example, I might want to create the smallest possible jar (without including certain classes), or I might want the fastest compile time for what I am compiling. I absolutely want to compile all the dependencies, though! This can be easily achieved from the command line with: ``` javac -d build/ -cp whatever -sourcepath src src/path/to/MyClass.java ``` Now, how can you do that with ant? The javac ant [task compiles everything](http://ant.apache.org/manual/Tasks/javac.html): > > The source and destination directory > will be recursively scanned for Java > source files to compile. > > > One can use the `excludes` and `includes` parameters, but they are problematic for this purpose. In fact, it seems that one has to explicitly setup all the `includes` (not automatic dependency lookup), and **even worst** that [excludes has priority on includes](http://ant.apache.org/manual/dirtasks.html#patternset): > > When both inclusion and exclusion are > used, only files/directories that > match at least one of the include > patterns and don't match *any* of the > exclude patterns are used. > > > Thus, you cannot use ``` <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" excludes="**/*.java" includes="src/path/to/MyClass.java" /> ``` Because it will not compile anything :-( Is there any way of achieving that simple command line `javac` with ant? --- EDITED: Thank you for your answer, Sadie, I'm accepting it, because it does work in the way I was wondering in this question. But I have a couple of comments (too long to be in the comment field of your answer): 1) I did read the documentation (see links above), but it's unclear that with just `includes` you are actually also excluding everything else 2) When you just `includes` ant logs something like ``` [javac] Compiling 1 source file to /my/path/to/build ``` even if the dependencies make it compiling (much) more than just one source file.
Why are you excluding as well as including? If you have at least one include, then files are only compiled if they're explicitly included. So this should work: ``` <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includes="src/path/to/MyClass.java" /> ``` Or more flexibly: ``` <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"> <include name="src/path/to/MyClass.java"/> <include name="src/path/to/AnotherClass.java"/> </javac> ``` To include only certain packages or classes in a jar, use a fileset attribute ``` <jar jarfile="${outlib}/something.jar"> <fileset dir="${build.dir}"> <include name='src/path/to/classes' /> </fileset> </jar> ``` Again, you can use multiple includes to combine separate packages. Experiment with includes and [read the documentation](http://ant.apache.org/manual/) and you're sure to find the answer you need.
203,189
<p>I am intercepting Win32 API calls a native dll or exe is doing from C# using some kind of hooking. In this particular case I am interested in DrawText() in user32.dll. It is declared like this in Win32 API:</p> <pre><code>INT WINAPI DrawTextW(HDC hdc, LPCWSTR str, INT count, LPRECT rect, UINT flags) </code></pre> <p>The LPRECT struct has the following signature (also in Win32 API):</p> <pre><code>typedef struct tagRECT { LONG left; LONG top; LONG right; LONG bottom; } RECT LPRECT; </code></pre> <p>LONG is a typedef for 32bit integers on 32bit systems (don't know about 64bit systems, it is irrelevant at this point because I am on 32bit Windows). To be able to access the members of this struct I declared it in my C# code...</p> <pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RECT { public Int32 left; public Int32 top; public Int32 right; public Int32 bottom; } </code></pre> <p>... and wrote the signature of P/Invoke using this RECT struct:</p> <pre><code>[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.StdCall)] static extern IntPtr DrawText(IntPtr HDC, String str, Int32 count, ref RECT rect, UInt32 flags, IntPtr dtp); </code></pre> <p>Since structs are value types in C# as opposed to being reference types like in C/C++, the ref modifier is necessary here.</p> <p>However when I use <code>rect.top rect.left</code> etc, they almost always return 0. I know for a fact that this is incorrect. But after googling countless hours and trying a lot of different things, I couldn't make this simple stuff work.</p> <p>Things I've tried:</p> <ul> <li>Using different primitives for RECT members (int, long, short, UInt32...). Actually it is kinda obvious that this is not a type problem because in any case I should see some garbled numbers, not 0.</li> <li>Removing ref modifier. This is also stupid (desperate times, desperate measures) because rect.left correctly returns the pointer to rect instead of its value.</li> <li>Tried <code>unsafe</code> code blocks. Didn't work but I may have made a mistake in the implementation (I don't remember what I've done). Besides this approach is generally reserved for tricky pointer situations in COM and Win32, it is overkill for my case anyway.</li> <li>Tried adding <code>[MarshallAs]</code> before the members of RECT. Made no difference.</li> <li>Played around with <code>Pack</code> values. No difference.</li> </ul> <p>I am fairly sure that I'm missing something very easy and straightforward but I have no idea what it is...</p> <p>Any help is appreciated. Thank you.</p>
[ { "answer_id": 203233, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.pinvoke.net/default.aspx/user32.DrawText\" rel=\"noreferrer\">http://www.pinvoke.net/default.aspx/user32.DrawText</a></p>\n" }, { "answer_id": 203239, "author": "Werg38", "author_id": 27569, "author_profile": "https://Stackoverflow.com/users/27569", "pm_score": 2, "selected": false, "text": "<p>I notice you say you have tried <code>[MarshallAs]</code> but have you tried <code>[MarshalAs(UnmanagedType.Struct)]</code>?</p>\n" }, { "answer_id": 203999, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 1, "selected": false, "text": "<p>Part of the problem is the use of String where a StringBuilder should be used. </p>\n\n<p>Try this signature (Generated with <a href=\"http://codeplex.com/clrinterop\" rel=\"nofollow noreferrer\">PInvoke Interop Assistant</a>)</p>\n\n<pre><code>\n[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\npublic struct tagRECT {\n\n /// LONG->int\n public int left;\n\n /// LONG->int\n public int top;\n\n /// LONG->int\n public int right;\n\n /// LONG->int\n public int bottom;\n}\n\npublic partial class NativeMethods {\n\n /// Return Type: int\n ///hdc: HDC->HDC__*\n ///lpchText: LPCWSTR->WCHAR*\n ///cchText: int\n ///lprc: LPRECT->tagRECT*\n ///format: UINT->unsigned int\n [System.Runtime.InteropServices.DllImportAttribute(\"user32.dll\", EntryPoint=\"DrawTextW\")]\npublic static extern int DrawTextW([System.Runtime.InteropServices.InAttribute()] System.IntPtr hdc, [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] System.Text.StringBuilder lpchText, int cchText, ref tagRECT lprc, uint format) ;\n\n}\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am intercepting Win32 API calls a native dll or exe is doing from C# using some kind of hooking. In this particular case I am interested in DrawText() in user32.dll. It is declared like this in Win32 API: ``` INT WINAPI DrawTextW(HDC hdc, LPCWSTR str, INT count, LPRECT rect, UINT flags) ``` The LPRECT struct has the following signature (also in Win32 API): ``` typedef struct tagRECT { LONG left; LONG top; LONG right; LONG bottom; } RECT LPRECT; ``` LONG is a typedef for 32bit integers on 32bit systems (don't know about 64bit systems, it is irrelevant at this point because I am on 32bit Windows). To be able to access the members of this struct I declared it in my C# code... ``` [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RECT { public Int32 left; public Int32 top; public Int32 right; public Int32 bottom; } ``` ... and wrote the signature of P/Invoke using this RECT struct: ``` [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.StdCall)] static extern IntPtr DrawText(IntPtr HDC, String str, Int32 count, ref RECT rect, UInt32 flags, IntPtr dtp); ``` Since structs are value types in C# as opposed to being reference types like in C/C++, the ref modifier is necessary here. However when I use `rect.top rect.left` etc, they almost always return 0. I know for a fact that this is incorrect. But after googling countless hours and trying a lot of different things, I couldn't make this simple stuff work. Things I've tried: * Using different primitives for RECT members (int, long, short, UInt32...). Actually it is kinda obvious that this is not a type problem because in any case I should see some garbled numbers, not 0. * Removing ref modifier. This is also stupid (desperate times, desperate measures) because rect.left correctly returns the pointer to rect instead of its value. * Tried `unsafe` code blocks. Didn't work but I may have made a mistake in the implementation (I don't remember what I've done). Besides this approach is generally reserved for tricky pointer situations in COM and Win32, it is overkill for my case anyway. * Tried adding `[MarshallAs]` before the members of RECT. Made no difference. * Played around with `Pack` values. No difference. I am fairly sure that I'm missing something very easy and straightforward but I have no idea what it is... Any help is appreciated. Thank you.
<http://www.pinvoke.net/default.aspx/user32.DrawText>
203,194
<p>I'm trying to access the Facebook API Admin.getMetrics method via jQuery. I'm correctly composing the request url on the server side (in order to keep my app secret secret). I'm then sending the url over to the browser to be request using <code>jQuery.getJSON()</code>.</p> <p>Facebook requires that I send a copy of all of my request params hashed with my application secret along with the request in order to verify my authenticity. The problem is that jQuery wants to generate the name of the callback function itself in order to match the name it gives to the anonymous function you pass in to be called when the data returns. Therefore, the name of the function is not available until <code>jQuery.getJSON()</code> executes and Facebook considers my request to be inauthentic due to a mismatched signature (the signature I send along does not include the correct callback param because that was not generated until <code>jQuery.getJSON()</code> ran).</p> <p>The only way I can think of out of this problem is to somehow specify the name of my function to <code>jQuery.getJSON()</code> instead of allowing it to remain anonymous. But I cannot find any option for doing so in the jQuery AP.</p>
[ { "answer_id": 203247, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 2, "selected": false, "text": "<p>You can pass the JSONP option to $.ajaxSetup that will allow you to fix the function name that gets called, the docs read as follows:</p>\n\n<p><strong>jsonp String</strong><br>\nOverride the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url for a GET or the data for a POST. So {jsonp:'onJsonPLoad'} would result in 'onJsonPLoad=?' passed to the server. </p>\n\n<p>See here <a href=\"http://docs.jquery.com/Ajax/jQuery.ajax#options\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Ajax/jQuery.ajax#options</a> for more details</p>\n" }, { "answer_id": 205164, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 0, "selected": false, "text": "<p>This is a better solution with a fixed callback:</p>\n\n<pre><code>window.fixed_callback = function(data){\n alert(data.title);\n};\n\n$(function() {\n $.getScript(\"http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&amp;tagmode=any&amp;format=json&amp;jsoncallback=fixed_callback\", function(data) {\n alert('done'); } );\n});\n</code></pre>\n\n<p>The problem with this callback is you can only handle one kind of request at a time as the function is globally registered. The callback function would probably have to turn into a dispatcher for the different kinds of data that it could retrieve and call the appropriate function.</p>\n" }, { "answer_id": 205350, "author": "Greg Borenstein", "author_id": 10419, "author_profile": "https://Stackoverflow.com/users/10419", "pm_score": 3, "selected": true, "text": "<p>The use of <code>jQuery.getScript</code> turned out to be close to -- but not quite -- the answer. Using getScript eliminates jQuery's need to add the dynamically named anonymous function to the request params (though it will still do that if you go ahead and pass it an anonymous function as in the above code). However, the default in <code>jQuery.getScript</code>, as in all the other calls in jQuery's Ajax library, is to append a further additional argument <code>_=12344567</code> (where 1234567 is really a time stamp). jQuery does this to prevent the browser from caching the response. However, this additional breaks my signing of the request just like the auto-named callback function. </p>\n\n<p>With some help on #jquery, I learned that the only way to get jQuery not to mess at all with your params is to make the request using the base <code>jQuery.Ajax</code> method with the following arguments:</p>\n\n<pre><code>jQuery.ajax({\n url: fbookUrl,\n dataType: \"script\",\n type: \"GET\",\n cache: true,\n callback: null,\n data: null\n});\n</code></pre>\n\n<p>(where <code>fbookUrl</code> is the Facebook API url I'm trying to request with its full params including the signature and the <code>callback=myFunction</code>). The <code>dataType: \"script\"</code> arg specifies that the resulting JSONP should be stuffed into a script tag on the page for execution, <code>cache: true</code> tells jQuery to allow the browser to cache the response, i.e. to skip the addition of the time stamp parameter.</p>\n" }, { "answer_id": 6044685, "author": "eloycm", "author_id": 467923, "author_profile": "https://Stackoverflow.com/users/467923", "pm_score": 2, "selected": false, "text": "<p>The only thing that did the work for me were the following settings</p>\n\n<p><code>jQuery.ajax({\n url: fbookUrl,\n dataType: \"jsonp\",\n type: \"GET\",\n cache: true,\n jsonp: false,\n jsonpCallback: \"MyFunctionName\" //insert here your function name\n});</code></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10419/" ]
I'm trying to access the Facebook API Admin.getMetrics method via jQuery. I'm correctly composing the request url on the server side (in order to keep my app secret secret). I'm then sending the url over to the browser to be request using `jQuery.getJSON()`. Facebook requires that I send a copy of all of my request params hashed with my application secret along with the request in order to verify my authenticity. The problem is that jQuery wants to generate the name of the callback function itself in order to match the name it gives to the anonymous function you pass in to be called when the data returns. Therefore, the name of the function is not available until `jQuery.getJSON()` executes and Facebook considers my request to be inauthentic due to a mismatched signature (the signature I send along does not include the correct callback param because that was not generated until `jQuery.getJSON()` ran). The only way I can think of out of this problem is to somehow specify the name of my function to `jQuery.getJSON()` instead of allowing it to remain anonymous. But I cannot find any option for doing so in the jQuery AP.
The use of `jQuery.getScript` turned out to be close to -- but not quite -- the answer. Using getScript eliminates jQuery's need to add the dynamically named anonymous function to the request params (though it will still do that if you go ahead and pass it an anonymous function as in the above code). However, the default in `jQuery.getScript`, as in all the other calls in jQuery's Ajax library, is to append a further additional argument `_=12344567` (where 1234567 is really a time stamp). jQuery does this to prevent the browser from caching the response. However, this additional breaks my signing of the request just like the auto-named callback function. With some help on #jquery, I learned that the only way to get jQuery not to mess at all with your params is to make the request using the base `jQuery.Ajax` method with the following arguments: ``` jQuery.ajax({ url: fbookUrl, dataType: "script", type: "GET", cache: true, callback: null, data: null }); ``` (where `fbookUrl` is the Facebook API url I'm trying to request with its full params including the signature and the `callback=myFunction`). The `dataType: "script"` arg specifies that the resulting JSONP should be stuffed into a script tag on the page for execution, `cache: true` tells jQuery to allow the browser to cache the response, i.e. to skip the addition of the time stamp parameter.
203,198
<p>I have a bit of code where I am looping through all the select boxes on a page and binding a <code>.hover</code> event to them to do a bit of twiddling with their width on <code>mouse on/off</code>.</p> <p>This happens on page ready and works just fine.</p> <p>The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.</p> <p>I have found this plugin (<a href="http://brandonaaron.net/docs/livequery/#getting-started" rel="noreferrer">jQuery Live Query Plugin</a>), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.</p>
[ { "answer_id": 203220, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 6, "selected": false, "text": "<p>You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.</p>\n\n<pre><code>var mouseOverHandler = function() {\n // Do stuff\n};\nvar mouseOutHandler = function () {\n // Do stuff\n};\n\n$(function() {\n // On the document load, apply to existing elements\n $('select').hover(mouseOverHandler, mouseOutHandler);\n});\n\n// This next part would be in the callback from your Ajax call\n$(\"&lt;select&gt;&lt;/select&gt;\")\n .append( /* Your &lt;option&gt;s */ )\n .hover(mouseOverHandler, mouseOutHandler)\n .appendTo( /* Wherever you need the select box */ )\n;\n</code></pre>\n" }, { "answer_id": 203227, "author": "Greg Borenstein", "author_id": 10419, "author_profile": "https://Stackoverflow.com/users/10419", "pm_score": 6, "selected": false, "text": "<p>You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:</p>\n\n<pre><code>function addCallbacks(eles){\n eles.hover(function(){alert(\"gotcha!\")});\n}\n\n$(document).ready(function(){\n addCallbacks($(\".myEles\"))\n});\n\n// ... add elements ...\naddCallbacks($(\".myNewElements\"))\n</code></pre>\n" }, { "answer_id": 1207393, "author": "dev.e.loper", "author_id": 37759, "author_profile": "https://Stackoverflow.com/users/37759", "pm_score": 12, "selected": true, "text": "<p><strong>As of jQuery 1.7</strong> you should use <a href=\"https://api.jquery.com/on/#on-events-selector-data-handler\" rel=\"noreferrer\"><code>jQuery.fn.on</code></a> with the selector parameter filled:</p>\n<pre><code>$(staticAncestors).on(eventName, dynamicChild, function() {});\n</code></pre>\n<p><em>Explanation:</em></p>\n<p>This is called event delegation and works as followed. The event is attached to a static parent (<code>staticAncestors</code>) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (<code>dynamicChild</code>). When there is a match then your custom handler function is executed.</p>\n<hr />\n<p><strong>Prior to this</strong>, the recommended approach was to use <a href=\"http://api.jquery.com/live\" rel=\"noreferrer\"><code>live()</code></a>:</p>\n<pre><code>$(selector).live( eventName, function(){} );\n</code></pre>\n<p>However, <code>live()</code> was deprecated in 1.7 in favour of <code>on()</code>, and completely removed in 1.9. The <code>live()</code> signature:</p>\n<pre><code>$(selector).live( eventName, function(){} );\n</code></pre>\n<p>... can be replaced with the following <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\"><code>on()</code></a> signature:</p>\n<pre><code>$(document).on( eventName, selector, function(){} );\n</code></pre>\n<hr />\n<p>For example, if your page was dynamically creating elements with the class name <code>dosomething</code> you would bind the event to <strong>a parent which already exists</strong> (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is <code>document</code>. Though bear in mind <a href=\"https://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document\"><code>document</code> may not be the most efficient option</a>.</p>\n<pre><code>$(document).on('mouseover mouseout', '.dosomething', function(){\n // what you want to happen when mouseover and mouseout \n // occurs on elements that match '.dosomething'\n});\n</code></pre>\n<p>Any parent that exists at the time the event is bound is fine. For example</p>\n<pre><code>$('.buttons').on('click', 'button', function(){\n // do something here\n});\n</code></pre>\n<p>would apply to</p>\n<pre><code>&lt;div class=&quot;buttons&quot;&gt;\n &lt;!-- &lt;button&gt;s that are generated dynamically and added here --&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 5384561, "author": "user670265", "author_id": 670265, "author_profile": "https://Stackoverflow.com/users/670265", "pm_score": 5, "selected": false, "text": "<p>Try to use <code>.live()</code> instead of <code>.bind()</code>; the <code>.live()</code> will bind <code>.hover</code> to your checkbox after the Ajax request executes.</p>\n" }, { "answer_id": 8586344, "author": "Fazi", "author_id": 1063991, "author_profile": "https://Stackoverflow.com/users/1063991", "pm_score": 5, "selected": false, "text": "<p>You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.</p>\n\n<p>Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n &lt;head&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /&gt;\n &lt;title&gt;Untitled Document&lt;/title&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n &lt;script src=\"http://code.jquery.com/jquery-latest.js\"&gt;&lt;/script&gt;\n &lt;script src=\"http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js\"&gt;&lt;/script&gt;\n\n &lt;input type=\"button\" id=\"theButton\" value=\"Click\" /&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function()\n {\n $('.FOO').live(\"click\", function (){alert(\"It Works!\")});\n var $dialog = $('&lt;div&gt;&lt;/div&gt;').html('&lt;div id=\"container\"&gt;&lt;input type =\"button\" id=\"CUSTOM\" value=\"click\"/&gt;This dialog will show every time!&lt;/div&gt;').dialog({\n autoOpen: false,\n tite: 'Basic Dialog'\n });\n $('#theButton').click(function()\n {\n $dialog.dialog('open');\n return('false');\n });\n $('#CUSTOM').click(function(){\n //$('#container').append('&lt;input type=\"button\" value=\"clickmee\" class=\"FOO\" /&gt;&lt;/br&gt;');\n var button = document.createElement(\"input\");\n button.setAttribute('class','FOO');\n button.setAttribute('type','button');\n button.setAttribute('value','CLICKMEE');\n $('#container').append(button);\n });\n /* $('#FOO').click(function(){\n alert(\"It Works!\");\n }); */\n });\n &lt;/script&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 18144022, "author": "Ronen Rabinovici", "author_id": 1806956, "author_profile": "https://Stackoverflow.com/users/1806956", "pm_score": 9, "selected": false, "text": "<p>There is a good explanation in the documentation of <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\"><code>jQuery.fn.on</code></a>.</p>\n\n<p>In short:</p>\n\n<blockquote>\n <p>Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to <code>.on()</code>.</p>\n</blockquote>\n\n<p>Thus in the following example <code>#dataTable tbody tr</code> must exist before the code is generated.</p>\n\n<pre><code>$(\"#dataTable tbody tr\").on(\"click\", function(event){\n console.log($(this).text());\n});\n</code></pre>\n\n<p>If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.</p>\n\n<p><strong>Delegated events</strong> have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:</p>\n\n<pre><code>$(\"#dataTable tbody\").on(\"click\", \"tr\", function(event){\n console.log($(this).text());\n});\n</code></pre>\n\n<p>In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its <code>tbody</code>, the first code example attaches a handler to 1,000 elements.</p>\n\n<p>A delegated-events approach (the second code example) attaches an event handler to only one element, the <code>tbody</code>, and the event only needs to bubble up one level (from the clicked <code>tr</code> to <code>tbody</code>).</p>\n\n<p><strong>Note:</strong> Delegated events do not work for <a href=\"http://en.wikipedia.org/wiki/Scalable_Vector_Graphics\" rel=\"noreferrer\">SVG</a>.</p>\n" }, { "answer_id": 27373951, "author": "Ram Patra", "author_id": 1385441, "author_profile": "https://Stackoverflow.com/users/1385441", "pm_score": 8, "selected": false, "text": "<p>This is a <strong>pure JavaScript</strong> solution without any libraries or plugins:</p>\n<pre><code>document.addEventListener('click', function (e) {\n if (hasClass(e.target, 'bu')) {\n // .bu clicked\n // Do your thing\n } else if (hasClass(e.target, 'test')) {\n // .test clicked\n // Do your other thing\n }\n}, false);\n</code></pre>\n<p>where <code>hasClass</code> is</p>\n<pre><code>function hasClass(elem, className) {\n return elem.className.split(' ').indexOf(className) &gt; -1;\n}\n</code></pre>\n<p><kbd><strong><a href=\"http://jsfiddle.net/ramswaroop/Nrxp5/28/\" rel=\"noreferrer\">Live demo</a></strong></kbd></p>\n<p><em>Credit goes to Dave and Sime Vidas</em></p>\n<p>Using more modern JS, <code>hasClass</code> can be implemented as:</p>\n<pre><code>function hasClass(elem, className) {\n return elem.classList.contains(className);\n}\n</code></pre>\n<hr />\n<p>The same jsfiddle Live demo embeded below:</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 hasClass(elem, className) {\n return elem.classList.contains(className);\n}\n\ndocument.addEventListener('click', function(e) {\n if (hasClass(e.target, 'bu')) {\n alert('bu');\n document.querySelector('.bu').innerHTML = '&lt;div class=\"bu\"&gt;Bu&lt;div class=\"tu\"&gt;Tu&lt;/div&gt;&lt;/div&gt;';\n } else if (hasClass(e.target, 'test')) {\n alert('test');\n } else if (hasClass(e.target, 'tu')) {\n alert('tu');\n }\n\n}, false);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.test,\n.bu,\n.tu {\n border: 1px solid gray;\n padding: 10px;\n margin: 10px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"test\"&gt;Test\n &lt;div class=\"bu\"&gt;Bu&lt;/div&gt;test\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 32999007, "author": "Martin Da Rosa", "author_id": 2911545, "author_profile": "https://Stackoverflow.com/users/2911545", "pm_score": 5, "selected": false, "text": "<p>Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:</p>\n\n<pre><code>var myElement = $('&lt;button/&gt;', {\n text: 'Go to Google!'\n});\n\nmyElement.bind( 'click', goToGoogle);\nmyElement.append('body');\n\n\nfunction goToGoogle(event){\n window.location.replace(\"http://www.google.com\");\n}\n</code></pre>\n" }, { "answer_id": 33843105, "author": "Vatsal", "author_id": 4249059, "author_profile": "https://Stackoverflow.com/users/4249059", "pm_score": 5, "selected": false, "text": "<p>I prefer using the selector and I apply it on the document.</p>\n\n<p>This binds itself on the document and will be applicable to the elements that will be rendered after page load.</p>\n\n<p>For example:</p>\n\n<pre><code>$(document).on(\"click\", 'selector', function() {\n // Your code here\n});\n</code></pre>\n" }, { "answer_id": 34351670, "author": "Ankit Kathiriya", "author_id": 4286710, "author_profile": "https://Stackoverflow.com/users/4286710", "pm_score": 4, "selected": false, "text": "<p>Any p<strong>arent that exists</strong> at the time the event is bound and if your page was <strong>dynamically creating elements</strong> with the class name <strong>button</strong> you would bind the event to a parent which already exists</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(document).ready(function(){\r\n //Particular Parent chield click\r\n $(\".buttons\").on(\"click\",\"button\",function(){\r\n alert(\"Clicked\");\r\n }); \r\n \r\n //Dynamic event bind on button class \r\n $(document).on(\"click\",\".button\",function(){\r\n alert(\"Dymamic Clicked\");\r\n });\r\n $(\"input\").addClass(\"button\"); \r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;div class=\"buttons\"&gt;\r\n &lt;input type=\"button\" value=\"1\"&gt;\r\n &lt;button&gt;2&lt;/button&gt;\r\n &lt;input type=\"text\"&gt;\r\n &lt;button&gt;3&lt;/button&gt; \r\n &lt;input type=\"button\" value=\"5\"&gt; \r\n &lt;/div&gt;\r\n&lt;button&gt;6&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 34937304, "author": "MadeInDreams", "author_id": 144015, "author_profile": "https://Stackoverflow.com/users/144015", "pm_score": 5, "selected": false, "text": "<h2>Event binding on dynamically created elements</h2>\n\n<p><strong>Single element:</strong></p>\n\n<pre><code>$(document.body).on('click','.element', function(e) { });\n</code></pre>\n\n<p><strong>Child Element:</strong></p>\n\n<pre><code> $(document.body).on('click','.element *', function(e) { });\n</code></pre>\n\n<p>Notice the added <code>*</code>. An event will be triggered for all children of that element.</p>\n\n<p>I have noticed that:</p>\n\n<pre><code>$(document.body).on('click','.#element_id &gt; element', function(e) { });\n</code></pre>\n\n<p>It is not working any more, but it was working before. I have been using jQuery from Google <a href=\"http://en.wikipedia.org/wiki/Content_delivery_network\" rel=\"noreferrer\">CDN</a>, but I don't know if they changed it.</p>\n" }, { "answer_id": 36230887, "author": "Aslan Kaya", "author_id": 1478851, "author_profile": "https://Stackoverflow.com/users/1478851", "pm_score": 4, "selected": false, "text": "<p>Take note of \"MAIN\" class the element is placed, for example,</p>\n\n<pre><code>&lt;div class=\"container\"&gt;\n &lt;ul class=\"select\"&gt;\n &lt;li&gt; First&lt;/li&gt;\n &lt;li&gt;Second&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>In the above scenario, the MAIN object the jQuery will watch is \"container\".</p>\n\n<p>Then you will basically have elements names under container such as <code>ul</code>, <code>li</code>, and <code>select</code>:</p>\n\n<pre><code>$(document).ready(function(e) {\n $('.container').on( 'click',\".select\", function(e) {\n alert(\"CLICKED\");\n });\n });\n</code></pre>\n" }, { "answer_id": 38115401, "author": "Rohit Suthar", "author_id": 1732454, "author_profile": "https://Stackoverflow.com/users/1732454", "pm_score": 5, "selected": false, "text": "<p>Try like this way - </p>\n\n<pre><code>$(document).on( 'click', '.click-activity', function () { ... });\n</code></pre>\n" }, { "answer_id": 38901509, "author": "Mensur Grišević", "author_id": 2938302, "author_profile": "https://Stackoverflow.com/users/2938302", "pm_score": 4, "selected": false, "text": "<p>you could use</p>\n\n<pre><code>$('.buttons').on('click', 'button', function(){\n // your magic goes here\n});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$('.buttons').delegate('button', 'click', function() {\n // your magic goes here\n});\n</code></pre>\n\n<p>these two methods are equivalent but have a different order of parameters.</p>\n\n<p>see: <a href=\"http://api.jquery.com/delegate/\" rel=\"noreferrer\">jQuery Delegate Event</a></p>\n" }, { "answer_id": 40884178, "author": "Kalpesh Patel", "author_id": 1044026, "author_profile": "https://Stackoverflow.com/users/1044026", "pm_score": 3, "selected": false, "text": "<p>Use the <code>.on()</code> method of jQuery <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\">http://api.jquery.com/on/</a> to attach event handlers to live element.</p>\n\n<p>Also as of version 1.9 <code>.live()</code> method is removed.</p>\n" }, { "answer_id": 43224244, "author": "guest271314", "author_id": 2801559, "author_profile": "https://Stackoverflow.com/users/2801559", "pm_score": 4, "selected": false, "text": "<p>You can attach event to element when dynamically created using <a href=\"https://api.jquery.com/jQuery/#jQuery-html-attributes\" rel=\"noreferrer\"><code>jQuery(html, attributes)</code></a>.</p>\n\n<blockquote>\n <p><strong>As of jQuery 1.8</strong>, any jQuery instance method (a method of <code>jQuery.fn</code>) can be used as a property of the object passed to the\n second parameter:</p>\n</blockquote>\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 handleDynamicElementEvent(event) {\r\n console.log(event.type, this.value)\r\n}\r\n// create and attach event to dynamic element\r\njQuery(\"&lt;select&gt;\", {\r\n html: $.map(Array(3), function(_, index) {\r\n return new Option(index, index)\r\n }),\r\n on: {\r\n change: handleDynamicElementEvent\r\n }\r\n })\r\n .appendTo(\"body\");</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;\r\n&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 43480940, "author": "Prasad De Silva", "author_id": 3128521, "author_profile": "https://Stackoverflow.com/users/3128521", "pm_score": 3, "selected": false, "text": "<p>Another flexible solution to create elements and bind events (<a href=\"https://stackoverflow.com/questions/10619445/the-preferred-way-of-creating-a-new-element-with-jquery\">source</a>)</p>\n\n<pre><code>// creating a dynamic element (container div)\nvar $div = $(\"&lt;div&gt;\", {id: 'myid1', class: 'myclass'});\n\n//creating a dynamic button\n var $btn = $(\"&lt;button&gt;\", { type: 'button', text: 'Click me', class: 'btn' });\n\n// binding the event\n $btn.click(function () { //for mouseover--&gt; $btn.on('mouseover', function () {\n console.log('clicked');\n });\n\n// append dynamic button to the dynamic container\n$div.append($btn);\n\n// add the dynamically created element(s) to a static element\n$(\"#box\").append($div);\n</code></pre>\n\n<p>Note: <strong>This will create an event handler instance for each element</strong> (may affect performance when used in loops)</p>\n" }, { "answer_id": 46251110, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Here is why dynamically created elements do not respond to clicks&nbsp;:</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 body = $(\"body\");\r\nvar btns = $(\"button\");\r\nvar btnB = $(\"&lt;button&gt;B&lt;/button&gt;\");\r\n// `&lt;button&gt;B&lt;/button&gt;` is not yet in the document.\r\n// Thus, `$(\"button\")` gives `[&lt;button&gt;A&lt;/button&gt;]`.\r\n// Only `&lt;button&gt;A&lt;/button&gt;` gets a click listener.\r\nbtns.on(\"click\", function () {\r\n console.log(this);\r\n});\r\n// Too late for `&lt;button&gt;B&lt;/button&gt;`...\r\nbody.append(btnB);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;button&gt;A&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>As a workaround, you have to listen to all clicks and check the source element&nbsp;:</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 body = $(\"body\");\r\nvar btnB = $(\"&lt;button&gt;B&lt;/button&gt;\");\r\nvar btnC = $(\"&lt;button&gt;C&lt;/button&gt;\");\r\n// Listen to all clicks and\r\n// check if the source element\r\n// is a `&lt;button&gt;&lt;/button&gt;`.\r\nbody.on(\"click\", function (ev) {\r\n if ($(ev.target).is(\"button\")) {\r\n console.log(ev.target);\r\n }\r\n});\r\n// Now you can add any number\r\n// of `&lt;button&gt;&lt;/button&gt;`.\r\nbody.append(btnB);\r\nbody.append(btnC);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;button&gt;A&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This is called \"Event Delegation\". Good news, it's a builtin feature in jQuery :-)</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 i = 11;\r\nvar body = $(\"body\");\r\nbody.on(\"click\", \"button\", function () {\r\n var letter = (i++).toString(36).toUpperCase();\r\n body.append($(\"&lt;button&gt;\" + letter + \"&lt;/button&gt;\"));\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;button&gt;A&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 46452083, "author": "Fakhrul Hasan", "author_id": 4524167, "author_profile": "https://Stackoverflow.com/users/4524167", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;HTML Document&lt;/title&gt;\n &lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js\"&gt;&lt;/script&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n &lt;div id=\"hover-id\"&gt;\n Hello World\n &lt;/div&gt;\n\n &lt;script&gt;\n jQuery(document).ready(function($){\n $(document).on('mouseover', '#hover-id', function(){\n $(this).css('color','yellowgreen');\n });\n\n $(document).on('mouseout', '#hover-id', function(){\n $(this).css('color','black');\n });\n });\n &lt;/script&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 50402087, "author": "Evhz", "author_id": 5476782, "author_profile": "https://Stackoverflow.com/users/5476782", "pm_score": -1, "selected": false, "text": "<p>I was looking a solution to get <code>$.bind</code> and <code>$.unbind</code> working without problems in dynamically added elements. </p>\n\n<p>As <a href=\"http://api.jquery.com/on/\" rel=\"nofollow noreferrer\">on()</a> makes the trick to attach events, in order to create a fake unbind on those I came to:</p>\n\n<pre><code>const sendAction = function(e){ ... }\n// bind the click\n$('body').on('click', 'button.send', sendAction );\n\n// unbind the click\n$('body').on('click', 'button.send', function(){} );\n</code></pre>\n" }, { "answer_id": 50752513, "author": "truongnm", "author_id": 3280050, "author_profile": "https://Stackoverflow.com/users/3280050", "pm_score": 4, "selected": false, "text": "<p>Bind the event to a parent which already exists:</p>\n\n<pre><code>$(document).on(\"click\", \"selector\", function() {\n // Your code here\n});\n</code></pre>\n" }, { "answer_id": 50752666, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 3, "selected": false, "text": "<p>I prefer to have event listeners deployed in a modular function fashion rather than scripting a <code>document</code> level event listener. So, I do like below. <em>Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.</em></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 iterations = 4;\r\nvar button;\r\nvar body = document.querySelector(\"body\");\r\n\r\nfor (var i = 0; i &lt; iterations; i++) {\r\n button = document.createElement(\"button\");\r\n button.classList.add(\"my-button\");\r\n button.appendChild(document.createTextNode(i));\r\n button.addEventListener(\"click\", myButtonWasClicked);\r\n body.appendChild(button);\r\n}\r\n\r\nfunction myButtonWasClicked(e) {\r\n console.log(e.target); //access to this specific button\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 50856235, "author": "Mustkeem K", "author_id": 9266400, "author_profile": "https://Stackoverflow.com/users/9266400", "pm_score": 5, "selected": false, "text": "<p><em><strong>This is done by event delegation</strong></em>. Event will get bind on wrapper-class element but will be delegated to selector-class element. This is how it works.</p>\n<pre><code>$('.wrapper-class').on(&quot;click&quot;, '.selector-class', function() {\n // Your code here\n});\n</code></pre>\n<p>And HTML</p>\n<pre><code>&lt;div class=&quot;wrapper-class&quot;&gt;\n &lt;button class=&quot;selector-class&quot;&gt;\n Click Me!\n &lt;/button&gt;\n&lt;/div&gt; \n</code></pre>\n<p>#Note:\nwrapper-class element can be anything ex. document, body or your wrapper. <strong>Wrapper should already exist</strong>. However, <code>selector</code> doesn't necessarily needs to be presented at page loading time. It may come later and the event will bind on <code>selector</code> <strong>without fail</strong>.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
I have a bit of code where I am looping through all the select boxes on a page and binding a `.hover` event to them to do a bit of twiddling with their width on `mouse on/off`. This happens on page ready and works just fine. The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound. I have found this plugin ([jQuery Live Query Plugin](http://brandonaaron.net/docs/livequery/#getting-started)), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
**As of jQuery 1.7** you should use [`jQuery.fn.on`](https://api.jquery.com/on/#on-events-selector-data-handler) with the selector parameter filled: ``` $(staticAncestors).on(eventName, dynamicChild, function() {}); ``` *Explanation:* This is called event delegation and works as followed. The event is attached to a static parent (`staticAncestors`) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (`dynamicChild`). When there is a match then your custom handler function is executed. --- **Prior to this**, the recommended approach was to use [`live()`](http://api.jquery.com/live): ``` $(selector).live( eventName, function(){} ); ``` However, `live()` was deprecated in 1.7 in favour of `on()`, and completely removed in 1.9. The `live()` signature: ``` $(selector).live( eventName, function(){} ); ``` ... can be replaced with the following [`on()`](http://api.jquery.com/on/) signature: ``` $(document).on( eventName, selector, function(){} ); ``` --- For example, if your page was dynamically creating elements with the class name `dosomething` you would bind the event to **a parent which already exists** (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is `document`. Though bear in mind [`document` may not be the most efficient option](https://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document). ``` $(document).on('mouseover mouseout', '.dosomething', function(){ // what you want to happen when mouseover and mouseout // occurs on elements that match '.dosomething' }); ``` Any parent that exists at the time the event is bound is fine. For example ``` $('.buttons').on('click', 'button', function(){ // do something here }); ``` would apply to ``` <div class="buttons"> <!-- <button>s that are generated dynamically and added here --> </div> ```
203,199
<p>I tried but I guess Message Box only works with win forms. What is the best alternative to use in web forms?</p>
[ { "answer_id": 203205, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 2, "selected": false, "text": "<pre><code>result = confirm('Yes or no question here.')\n</code></pre>\n" }, { "answer_id": 203210, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 0, "selected": false, "text": "<p>JavaScript:</p>\n\n<pre><code>alert(\"This box has an OK button.\");\n</code></pre>\n" }, { "answer_id": 203213, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 4, "selected": true, "text": "<p>You can use <code>confirm</code> for yes/no questions and <code>alert</code> for \"OK\" messages in JavaScript.</p>\n\n<p>The other alternative is to use JavaScript to pop up a new window that looks and acts like a message box. Modality in this case varied by browser. In Internet Explorer, the method </p>\n\n<pre><code>window.showModalDialog(url,name,params)\n</code></pre>\n\n<p>will display a modal dialog. The Mozilla approach is to still use</p>\n\n<pre><code>window.open(url,name,params)\n</code></pre>\n\n<p>but add <code>modal=yes</code> to the <code>params</code> list.</p>\n" }, { "answer_id": 203217, "author": "troyappeldorn", "author_id": 27566, "author_profile": "https://Stackoverflow.com/users/27566", "pm_score": 0, "selected": false, "text": "<p>The Ajax ModalPopup also works nicely. Here is an example:</p>\n\n<p><a href=\"http://www.asp.net/ajax/ajaxcontroltoolkit/samples/modalpopup/modalpopup.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/ajax/ajaxcontroltoolkit/samples/modalpopup/modalpopup.aspx</a></p>\n" }, { "answer_id": 203234, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 0, "selected": false, "text": "<p>You have dojo dialog widget: <a href=\"http://www.dojotoolkit.org/\" rel=\"nofollow noreferrer\">http://www.dojotoolkit.org/</a> and you can use it as a message box.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
I tried but I guess Message Box only works with win forms. What is the best alternative to use in web forms?
You can use `confirm` for yes/no questions and `alert` for "OK" messages in JavaScript. The other alternative is to use JavaScript to pop up a new window that looks and acts like a message box. Modality in this case varied by browser. In Internet Explorer, the method ``` window.showModalDialog(url,name,params) ``` will display a modal dialog. The Mozilla approach is to still use ``` window.open(url,name,params) ``` but add `modal=yes` to the `params` list.
203,207
<p>I got a program with a fscanf like this:</p> <p>fscanf(stdin, "%d %d,....</p> <p>I got many fscanf and files that I'd like to test, the files are like this</p> <p>10485770 15 51200000 -2 10 10 10485760 10485760 10 10485760 10485760 10 10485760 10485760</p> <p>Well my question is how can I tell to the program or the compiler to take the inputs not from the keyboard, but from those files. These programs are benchmarks and in the files I got the inputs, I'm sure there is a way to do this automatic because in some case there are many inputs. Thank you in advance.</p>
[ { "answer_id": 203216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Try freopen. Eg.</p>\n\n<pre><code>freopen( \"somefile.txt\", \"r\", stdin );\n</code></pre>\n" }, { "answer_id": 203218, "author": "Sufian", "author_id": 9241, "author_profile": "https://Stackoverflow.com/users/9241", "pm_score": 2, "selected": false, "text": "<p>When running from the command line, you can redirect a file to standard input using the '&lt;' operator.</p>\n\n<p>For example, on windows:</p>\n\n<pre><code>$ type input_file\n10485770 15 51200000 -2 10 10 10485760 10485760 10 10485760 10485760 10 10485760\n10485760\n$ my_program.exe &lt; input_file\n</code></pre>\n\n<p>Or on *nix:</p>\n\n<pre><code>$ cat input_file\n10485770 15 51200000 -2 10 10 10485760 10485760 10 10485760 10485760 10 10485760\n10485760\n$ ./my_program &lt; input_file\n</code></pre>\n" }, { "answer_id": 203230, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": -1, "selected": false, "text": "<p>Look up the FILE structure. You'll be wanting to use FILE pointers for this solution.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I got a program with a fscanf like this: fscanf(stdin, "%d %d,.... I got many fscanf and files that I'd like to test, the files are like this 10485770 15 51200000 -2 10 10 10485760 10485760 10 10485760 10485760 10 10485760 10485760 Well my question is how can I tell to the program or the compiler to take the inputs not from the keyboard, but from those files. These programs are benchmarks and in the files I got the inputs, I'm sure there is a way to do this automatic because in some case there are many inputs. Thank you in advance.
Try freopen. Eg. ``` freopen( "somefile.txt", "r", stdin ); ```
203,246
<p>What is the best way to keep a console application open as long as the CancelKeyPress event has not been fired?</p> <p>I would prefer to not use Console.Read or Console.ReadLine as I do not want to accept input. I just want to enable the underlying application to print to the console event details as they are fired. Then once the CancelKeyPress event is fired I want to gracefully shut down the application.</p>
[ { "answer_id": 203258, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>There is already a handler bound to CancelKeyPress that terminates your application, the only reason to hook to it is if you want to intercept the event and prevent the app from closing.</p>\n\n<p>In your situation, just put your app into an infinite loop, and let the built in event handler kill it. You may want to look into using something like Wait(1) or a background process to prevent it from using tons of CPU while doing nothing.</p>\n" }, { "answer_id": 203264, "author": "Mattio", "author_id": 19626, "author_profile": "https://Stackoverflow.com/users/19626", "pm_score": 1, "selected": false, "text": "<p>This may be what you're looking for:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.console.cancelkeypress.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.console.cancelkeypress.aspx</a></p>\n" }, { "answer_id": 203289, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": true, "text": "<p>I'm assuming that \"gracefully shut down the application\" is the part you are struggling with here. Otherwise your application will automatically exit on ctrl-c. You should change the title.</p>\n\n<p>Here's a quick demo of what I think you need. It could be refined a bit more with use of locking and Monitors for notification. I'm not sure exactly what you need though, so I'll just pose this...</p>\n\n<pre><code>class Program\n{\n\n private static volatile bool _s_stop = false;\n\n public static void Main(string[] args)\n {\n Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);\n while (!_s_stop)\n {\n /* put real logic here */\n Console.WriteLine(\"still running at {0}\", DateTime.Now);\n Thread.Sleep(3000);\n }\n Console.WriteLine(\"Graceful shut down code here...\");\n\n //don't leave this... demonstration purposes only...\n Console.ReadLine();\n }\n\n static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)\n {\n //you have 2 options here, leave e.Cancel set to false and just handle any\n //graceful shutdown that you can while in here, or set a flag to notify the other\n //thread at the next check that it's to shut down. I'll do the 2nd option\n e.Cancel = true;\n _s_stop = true;\n Console.WriteLine(\"CancelKeyPress fired...\");\n }\n\n}\n</code></pre>\n\n<p>The _s_stop boolean should be declared volatile or an overly-ambitious optimizer might cause the program to loop infinitely.</p>\n" }, { "answer_id": 1083356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The <code>_s_stop</code> boolean should be declared volatile in the example code, or an overly-ambitious optimizer might cause the program to loop infinitely.</p>\n" }, { "answer_id": 23285792, "author": "victoromondy", "author_id": 3571747, "author_profile": "https://Stackoverflow.com/users/3571747", "pm_score": 0, "selected": false, "text": "<p>Simply run your program or codes without debugging, on your keyboard key in <kbd>CTRL + f5</kbd> instead of F5(debugging).</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/203246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
What is the best way to keep a console application open as long as the CancelKeyPress event has not been fired? I would prefer to not use Console.Read or Console.ReadLine as I do not want to accept input. I just want to enable the underlying application to print to the console event details as they are fired. Then once the CancelKeyPress event is fired I want to gracefully shut down the application.
I'm assuming that "gracefully shut down the application" is the part you are struggling with here. Otherwise your application will automatically exit on ctrl-c. You should change the title. Here's a quick demo of what I think you need. It could be refined a bit more with use of locking and Monitors for notification. I'm not sure exactly what you need though, so I'll just pose this... ``` class Program { private static volatile bool _s_stop = false; public static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); while (!_s_stop) { /* put real logic here */ Console.WriteLine("still running at {0}", DateTime.Now); Thread.Sleep(3000); } Console.WriteLine("Graceful shut down code here..."); //don't leave this... demonstration purposes only... Console.ReadLine(); } static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { //you have 2 options here, leave e.Cancel set to false and just handle any //graceful shutdown that you can while in here, or set a flag to notify the other //thread at the next check that it's to shut down. I'll do the 2nd option e.Cancel = true; _s_stop = true; Console.WriteLine("CancelKeyPress fired..."); } } ``` The \_s\_stop boolean should be declared volatile or an overly-ambitious optimizer might cause the program to loop infinitely.
203,274
<p>Usually when I build a site, I put all the CSS into one file, and all the properties that relate to a set of elements are defined at once. Like this:</p> <pre><code>#myElement { color: #fff; background-color: #000; padding: 10px; border: 1px solid #ccc; font-size: 14pt; } .myClass { font-size: 12pt; padding: 5px; color: #ee3; } </code></pre> <p>I've been considering splitting up my definitions into a number of different files (colours.css, layout.css, fonts.css ...) as I have seen recommended. Something like this:</p> <pre><code>/* colours.css */ #myElement { color: #fff; background-color: #000; border-color: #ccc; } .myClass { color: #ee3; } /* layout.css */ #myElement { padding: 10px; border: 1px solid; } .myClass { padding: 5px; } /* fonts.css */ #myElement { font-size: 14pt; } .myClass { font-size: 12pt; } </code></pre> <p>To reduce HTTP requests, I'd be combining the files and stripping whitespace prior to rollout, so that's not an issue, but my question is: does having all those selectors repeated over and over cause any performance issues in browsers?</p> <p>Alternatively, are there any tools which avoid this (potential) issue by merging definitions from different files? ie: take the input given in my second example (3 different files), and combine them into one file, like the first example.</p>
[ { "answer_id": 203298, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 3, "selected": true, "text": "<p>The browser will have to find all the definitions and then add them up and override the different properties based on the latest definition. So there will be a slight overhead.</p>\n\n<p>That being said it would be rather minimal and not very noticeable even on hardware 5 years old. The browsers are quite efficient at it these days.</p>\n" }, { "answer_id": 203319, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 0, "selected": false, "text": "<p>As William said, you're not going to see any issue from the browsers parsing the CSS. What you might see, though, is an issue with the number of HTTP requests that a client can open to a single host. Typically this defaults to two. So, if you do put your CSS in multiple files, you might want to put them on a separate sub-domain and they will be treated as a different host which will allow the HTML page to be loaded at the same time as your CSS files.</p>\n" }, { "answer_id": 203325, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 0, "selected": false, "text": "<p>There shouldn't be any noticeable difference in rendering/parsing speed. As everyone else said, computers are fast enough that they can render CSS pretty quick.</p>\n\n<p>Your problem is really going to be with the number of requests required to load the page. Extra web requests increase overhead when loading a page. It is much faster to load one large file than it is to load several smaller files. It has an impact on both the client (browser) and the server serving up all of those CSS files.</p>\n\n<p>As long as you combine your files in production, you should be fine.</p>\n\n<p><a href=\"http://developer.yahoo.com/yui/compressor/\" rel=\"nofollow noreferrer\">Yahoo's YUI Compressor</a> is a pretty good tool for compressing your CSS files into smaller files. The last time I checked, it can't definitions (at least the last time I looked at it) but there shouldn't be enough of a performance hit to really need to.</p>\n" }, { "answer_id": 206660, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 1, "selected": false, "text": "<p>I can't comment on performance, but I tried this approach on my website and ended up reverting to one large file.</p>\n\n<p>My reasons:</p>\n\n<ul> \n<li>I got tired of creating a rule for div.foo in three or four different files, and opening three or four files if I wanted to change that div. </li>\n<li>Sometimes it's not as easy as it should be to separate functions. To center a div in IE, you may have to center the text of the parent element, even though that's not the standard way. Now my layout is mixed in with my fonts.</li>\n<li>As the code grows, the easiest way for me to find things is to do a text search for the element I want. But I have to open several files to see all the rules, and maybe that element doesn't have a rule in this file so I get no matches.</li>\n</ul>\n\n<p>So I went back to having main.css and iehacks.css. And breathed a sigh of relief. </p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
Usually when I build a site, I put all the CSS into one file, and all the properties that relate to a set of elements are defined at once. Like this: ``` #myElement { color: #fff; background-color: #000; padding: 10px; border: 1px solid #ccc; font-size: 14pt; } .myClass { font-size: 12pt; padding: 5px; color: #ee3; } ``` I've been considering splitting up my definitions into a number of different files (colours.css, layout.css, fonts.css ...) as I have seen recommended. Something like this: ``` /* colours.css */ #myElement { color: #fff; background-color: #000; border-color: #ccc; } .myClass { color: #ee3; } /* layout.css */ #myElement { padding: 10px; border: 1px solid; } .myClass { padding: 5px; } /* fonts.css */ #myElement { font-size: 14pt; } .myClass { font-size: 12pt; } ``` To reduce HTTP requests, I'd be combining the files and stripping whitespace prior to rollout, so that's not an issue, but my question is: does having all those selectors repeated over and over cause any performance issues in browsers? Alternatively, are there any tools which avoid this (potential) issue by merging definitions from different files? ie: take the input given in my second example (3 different files), and combine them into one file, like the first example.
The browser will have to find all the definitions and then add them up and override the different properties based on the latest definition. So there will be a slight overhead. That being said it would be rather minimal and not very noticeable even on hardware 5 years old. The browsers are quite efficient at it these days.
203,294
<p>I have two NSURLConnections. The second one depends on the content of the first, so handling the data received from the connection will be different for the two connections. </p> <p>I'm just picking up Objective-C and I would like to know what the proper way to implement the delegates is.</p> <p>Right now I'm using: </p> <pre><code>NSURL *url=[NSURL URLWithString:feedURL]; NSURLRequest *urlR=[[[NSURLRequest alloc] initWithURL:url] autorelease]; NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:urlR delegate:self]; </code></pre> <p>I don't want to use self as the delegate, how do I define two connections with different delegates?</p> <pre><code>NSURLConnection *c1 = [[NSURLConnection alloc] initWithRequest:url delegate:handle1]; NSURLConnection *c2 = [[NSURLConnection alloc] initWithRequest:url delegate:handle2]; </code></pre> <p>How would do i create handle1 and handle2 as implementations? Or interfaces? I don't really get how you would do this. </p> <p>Any help would be awesome.</p> <p>Thanks, Brian Gianforcaro</p>
[ { "answer_id": 203356, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "<p>delegates are implemented as standard NSObject-descended objects. </p>\n\n<p>You can point both connections to the same delegate. </p>\n\n<p>The delegate should implement the NSURLConnectionDelegate methods you'd like to catch (such as -connection:didReceiveData: and -connectionDidFinishLoading:). These methods will get called by the delegate as appropriate.</p>\n" }, { "answer_id": 206430, "author": "Brian Gianforcaro", "author_id": 3415, "author_profile": "https://Stackoverflow.com/users/3415", "pm_score": 4, "selected": false, "text": "<p><strong>Ben</strong>, while your info was helpful It didn't fully answer the question I asked. </p>\n\n<p>I finally figured out how to setup my own delegates, which was what I was really asking. </p>\n\n<p>I implemented it like so: </p>\n\n<pre><code>@interface DownloadDelegate : NSObject \n- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;\n- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;\n@end\n\n@implementation DownloadDelegate\n- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {\n}\n- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {\n}\n@end\n</code></pre>\n\n<p>We use the delegate like so:</p>\n\n<pre><code>DownloadDelegate *dd = [DownloadDelegate alloc];\nNSURLConnection *c2 = [[NSURLConnection alloc] initWithRequest:url delegate:dd];\n</code></pre>\n\n<p>Hope that helps anybody in the same position, and thanks again <strong>Ben</strong> for your help. </p>\n\n<p>Thanks, </p>\n\n<p><strong>Brian Gianforcaro</strong></p>\n" }, { "answer_id": 207307, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 3, "selected": true, "text": "<p>In your sample, you alloc a DownloadDelegate object without ever init'ing it. \n<code><pre>\n DownloadDelegate *dd = [DownloadDelegate alloc];\n</pre></code></p>\n\n<p>This is dangerous. Instead:</p>\n\n<p><code><pre>\n DownloadDelegate *dd = [[DownloadDelegate alloc] init];\n</pre></code></p>\n\n<p>Also, it's not <i>strictly</i> necessary to declare your delegate response methods in your @interface declaration (though it won't hurt, of course). Finally, you'll want to make sure that you implement connection:didFailWithError: and connectionDidFinishLoading: to -release your DownloadDelegate object, otherwise you'll leak.</p>\n\n<p>Glad you're up and running!</p>\n" }, { "answer_id": 284918, "author": "leonho", "author_id": 30883, "author_profile": "https://Stackoverflow.com/users/30883", "pm_score": 1, "selected": false, "text": "<p>Try my MultipleDownload class at <a href=\"http://github.com/leonho/iphone-libs/tree/master\" rel=\"nofollow noreferrer\">http://github.com/leonho/iphone-libs/tree/master</a>, which it handles multiple NSURLConnection objects for you.</p>\n" }, { "answer_id": 1843673, "author": "mml", "author_id": 224066, "author_profile": "https://Stackoverflow.com/users/224066", "pm_score": 0, "selected": false, "text": "<p>since the delegates are called asynchronously, they could call didfinishloading in random order. you can then use a state check to determine if the \"other\" download is done yet before continuing.</p>\n\n<p>i use 2 delegates:</p>\n\n<p>for instance (this is pseudo oc):</p>\n\n<pre><code>jsondelegate = [[JSonDelegate alloc]initWithCaller:self andSelector:@selector(jsonDone:)]\notherdelegate = [[OtherDelegate] initWithCaller:self andSelector:@selector(otherDone:)]\n</code></pre>\n\n<p>when each delegate finishes, the delegate informs the caller, by calling the 2 done methods.</p>\n\n<p>each done method receives the url data, and saves its state to an ivar. then they check to see if the other ivar is set, and continue processing if they both are done.</p>\n\n<pre><code>if(self.jsonString &amp;&amp; self.otherData){\n continueProcessing\n}\n</code></pre>\n\n<p>hope this helps.</p>\n" }, { "answer_id": 4013208, "author": "shein", "author_id": 285798, "author_profile": "https://Stackoverflow.com/users/285798", "pm_score": 3, "selected": false, "text": "<p>I think the best way to handle multiple connections in a clean way is to keep a single delegate and just identify each NSURLConnection with a tag (it's a very VERY simple subclassing you can read about and copy from <a href=\"http://www.isignmeout.com/multiple-nsurlconnections-viewcontroller/\" rel=\"noreferrer\">http://www.isignmeout.com/multiple-nsurlconnections-viewcontroller/</a> )</p>\n\n<p>Basically to init every NSURLConnection with an identifying tag and then you can pull that tag in the delegate and using Switch-Case handle it according to whatever logic you need.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I've turned the subclassed NSURLConnection into a simple Category - a little simpler and cleaner</p>\n\n<p><a href=\"https://github.com/Shein/Categories\" rel=\"noreferrer\">https://github.com/Shein/Categories</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
I have two NSURLConnections. The second one depends on the content of the first, so handling the data received from the connection will be different for the two connections. I'm just picking up Objective-C and I would like to know what the proper way to implement the delegates is. Right now I'm using: ``` NSURL *url=[NSURL URLWithString:feedURL]; NSURLRequest *urlR=[[[NSURLRequest alloc] initWithURL:url] autorelease]; NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:urlR delegate:self]; ``` I don't want to use self as the delegate, how do I define two connections with different delegates? ``` NSURLConnection *c1 = [[NSURLConnection alloc] initWithRequest:url delegate:handle1]; NSURLConnection *c2 = [[NSURLConnection alloc] initWithRequest:url delegate:handle2]; ``` How would do i create handle1 and handle2 as implementations? Or interfaces? I don't really get how you would do this. Any help would be awesome. Thanks, Brian Gianforcaro
In your sample, you alloc a DownloadDelegate object without ever init'ing it. ```` DownloadDelegate *dd = [DownloadDelegate alloc]; ```` This is dangerous. Instead: ```` DownloadDelegate *dd = [[DownloadDelegate alloc] init]; ```` Also, it's not *strictly* necessary to declare your delegate response methods in your @interface declaration (though it won't hurt, of course). Finally, you'll want to make sure that you implement connection:didFailWithError: and connectionDidFinishLoading: to -release your DownloadDelegate object, otherwise you'll leak. Glad you're up and running!
203,302
<p>I have a table of items, each of which has a date associated with it. If I have the date associated with one item, how do I query the database with SQL to get the 'previous' and 'subsequent' items in the table?</p> <p>It is not possible to simply add (or subtract) a value, as the dates do not have a regular gap between them. </p> <p>One possible application would be 'previous/next' links in a photo album or blog web application, where the underlying data is in a SQL table.</p> <p>I think there are two possible cases:</p> <p><strong>Firstly</strong> where each date is unique:</p> <p>Sample data:</p> <pre><code>1,3,8,19,67,45 </code></pre> <p>What query (or queries) would give 3 and 19 when supplied 8 as the parameter? (or the rows 3,8,19). Note that there are not always three rows to be returned - at the ends of the sequence one would be missing.</p> <p><strong>Secondly</strong>, if there is a separate unique key to order the elements by, what is the query to return the set 'surrounding' a date? The order expected is by date then key.</p> <p>Sample data:</p> <pre><code>(key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8 </code></pre> <p>What query for '8' returns the set:</p> <pre><code>2:3,3:8,4:8,16:8,5:19 </code></pre> <p>or what query generates the table:</p> <pre><code>key date prev-key next-key 1 1 null 2 2 3 1 3 3 8 2 4 4 8 3 16 5 19 16 10 10 19 5 11 11 67 10 15 15 45 11 null 16 8 4 5 </code></pre> <p>The table order is not important - just the next-key and prev-key fields.</p> <hr> <p>Both TheSoftwareJedi and Cade Roux have solutions that work for the data sets I posted last night. For the second question, both seem to fail for this dataset:</p> <pre><code>(key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8 </code></pre> <p>The order expected is by date then key, so one expected result might be: </p> <pre><code>2:3,3:8,4:8,16:8,5:19 </code></pre> <p>and another:</p> <pre><code>key date prev-key next-key 1 1 null 2 2 3 1 3 3 8 2 4 4 8 3 16 5 19 16 10 10 19 5 11 11 67 10 15 15 45 11 null 16 8 4 5 </code></pre> <p>The table order is not important - just the next-key and prev-key fields.</p>
[ { "answer_id": 203310, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 2, "selected": false, "text": "<p>Firstly, this should work (the ORDER BY is important):</p>\n\n<pre><code>select min(a)\nfrom theTable\nwhere a &gt; 8\n\nselect max(a)\nfrom theTable\nwhere a &lt; 8\n</code></pre>\n\n<p>For the second question that I begged you to ask...:</p>\n\n<pre><code> select * \n from theTable\n where date = 8\n\n union all\n\n select *\n from theTable\n where key = (select min(key) \n from theTable\n where key &gt; (select max(key)\n from theTable\n where date = 8)\n )\n\n union all\n\n select *\n from theTable\n where key = (select max(key) \n from theTable\n where key &lt; (select min(key)\n from theTable\n where date = 8)\n )\n\n order by key\n</code></pre>\n" }, { "answer_id": 203311, "author": "fatbuddha", "author_id": 28034, "author_profile": "https://Stackoverflow.com/users/28034", "pm_score": 3, "selected": false, "text": "<p>Select max(element) From Data Where Element &lt; 8 </p>\n\n<p>Union</p>\n\n<p>Select min(element) From Data Where Element > 8 </p>\n\n<p>But generally it is more usefull to think of sql for set oriented operations rather than iterative operation. </p>\n" }, { "answer_id": 203351, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<p>Self-joins.</p>\n\n<p>For the table:</p>\n\n<pre><code>/*\nCREATE TABLE [dbo].[stackoverflow_203302](\n [val] [int] NOT NULL\n) ON [PRIMARY]\n*/\n</code></pre>\n\n<p>With parameter <code>@val</code></p>\n\n<pre><code>SELECT cur.val, MAX(prv.val) AS prv_val, MIN(nxt.val) AS nxt_val\nFROM stackoverflow_203302 AS cur\nLEFT JOIN stackoverflow_203302 AS prv\n ON cur.val &gt; prv.val\nLEFT JOIN stackoverflow_203302 AS nxt\n ON cur.val &lt; nxt.val\nWHERE cur.val = @val\nGROUP BY cur.val\n</code></pre>\n\n<p>You could make this a stored procedure with output parameters or just join this as a correlated subquery to the data you are pulling.</p>\n\n<p>Without the parameter, for your data the result would be:</p>\n\n<pre><code>val prv_val nxt_val\n----------- ----------- -----------\n1 NULL 3\n3 1 8\n8 3 19\n19 8 45\n45 19 67\n67 45 NULL\n</code></pre>\n\n<p>For the modified example, you use this as a correlated subquery:</p>\n\n<pre><code>/*\nCREATE TABLE [dbo].[stackoverflow_203302](\n [ky] [int] NOT NULL,\n [val] [int] NOT NULL,\n CONSTRAINT [PK_stackoverflow_203302] PRIMARY KEY CLUSTERED (\n [ky] ASC\n )\n)\n*/\n\nSELECT cur.ky AS cur_ky\n ,cur.val AS cur_val\n ,prv.ky AS prv_ky\n ,prv.val AS prv_val\n ,nxt.ky AS nxt_ky\n ,nxt.val as nxt_val\nFROM (\n SELECT cur.ky, MAX(prv.ky) AS prv_ky, MIN(nxt.ky) AS nxt_ky\n FROM stackoverflow_203302 AS cur\n LEFT JOIN stackoverflow_203302 AS prv\n ON cur.ky &gt; prv.ky\n LEFT JOIN stackoverflow_203302 AS nxt\n ON cur.ky &lt; nxt.ky\n GROUP BY cur.ky\n) AS ordering\nINNER JOIN stackoverflow_203302 as cur\n ON cur.ky = ordering.ky\nLEFT JOIN stackoverflow_203302 as prv\n ON prv.ky = ordering.prv_ky\nLEFT JOIN stackoverflow_203302 as nxt\n ON nxt.ky = ordering.nxt_ky\n</code></pre>\n\n<p>With the output as expected:</p>\n\n<pre><code>cur_ky cur_val prv_ky prv_val nxt_ky nxt_val\n----------- ----------- ----------- ----------- ----------- -----------\n1 1 NULL NULL 2 3\n2 3 1 1 3 8\n3 8 2 3 4 19\n4 19 3 8 5 67\n5 67 4 19 6 45\n6 45 5 67 NULL NULL\n</code></pre>\n\n<p>In SQL Server, I prefer to make the subquery a Common table Expression. This makes the code seem more linear, less nested and easier to follow if there are a lot of nestings (also, less repetition is required on some re-joins).</p>\n" }, { "answer_id": 203385, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT 'next' AS direction, MIN(date_field) AS date_key\nFROM table_name\n WHERE date_field &gt; current_date\nGROUP BY 1 -- necessity for group by varies from DBMS to DBMS in this context\nUNION\nSELECT 'prev' AS direction, MAX(date_field) AS date_key\n FROM table_name\n WHERE date_field &lt; current_date\nGROUP BY 1\nORDER BY 1 DESC;\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>direction date_key\n--------- --------\nprev 3\nnext 19\n</code></pre>\n" }, { "answer_id": 203451, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 0, "selected": false, "text": "<p>Try this...</p>\n\n<pre><code>SELECT TOP 3 * FROM YourTable\nWHERE Col &gt;= (SELECT MAX(Col) FROM YourTable b WHERE Col &lt; @Parameter)\nORDER BY Col\n</code></pre>\n" }, { "answer_id": 204397, "author": "John McAleely", "author_id": 10019, "author_profile": "https://Stackoverflow.com/users/10019", "pm_score": 2, "selected": true, "text": "<p>My own attempt at the set solution, based on TheSoftwareJedi.</p>\n\n<p>First question:</p>\n\n<pre><code>select date from test where date = 8\nunion all\nselect max(date) from test where date &lt; 8\nunion all\nselect min(date) from test where date &gt; 8\norder by date;\n</code></pre>\n\n<p>Second question:</p>\n\n<p>While debugging this, I used the data set:</p>\n\n<pre><code>(key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8,17:3,18:1\n</code></pre>\n\n<p>to give this result:</p>\n\n<pre><code>select * from test2 where date = 8\nunion all\nselect * from (select * from test2\n where date = (select max(date) from test2 \n where date &lt; 8)) \n where key = (select max(key) from test2 \n where date = (select max(date) from test2 \n where date &lt; 8))\nunion all\nselect * from (select * from test2\n where date = (select min(date) from test2 \n where date &gt; 8)) \n where key = (select min(key) from test2 \n where date = (select min(date) from test2 \n where date &gt; 8))\norder by date,key;\n</code></pre>\n\n<p>In both cases the final order by clause is strictly speaking optional.</p>\n" }, { "answer_id": 8288771, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 1, "selected": false, "text": "<p>If your RDBMS supports LAG and LEAD, this is straightforward (Oracle, PostgreSQL, SQL Server 2012)</p>\n\n<p>These allow to choose the row either side of any given row in a single query</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10019/" ]
I have a table of items, each of which has a date associated with it. If I have the date associated with one item, how do I query the database with SQL to get the 'previous' and 'subsequent' items in the table? It is not possible to simply add (or subtract) a value, as the dates do not have a regular gap between them. One possible application would be 'previous/next' links in a photo album or blog web application, where the underlying data is in a SQL table. I think there are two possible cases: **Firstly** where each date is unique: Sample data: ``` 1,3,8,19,67,45 ``` What query (or queries) would give 3 and 19 when supplied 8 as the parameter? (or the rows 3,8,19). Note that there are not always three rows to be returned - at the ends of the sequence one would be missing. **Secondly**, if there is a separate unique key to order the elements by, what is the query to return the set 'surrounding' a date? The order expected is by date then key. Sample data: ``` (key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8 ``` What query for '8' returns the set: ``` 2:3,3:8,4:8,16:8,5:19 ``` or what query generates the table: ``` key date prev-key next-key 1 1 null 2 2 3 1 3 3 8 2 4 4 8 3 16 5 19 16 10 10 19 5 11 11 67 10 15 15 45 11 null 16 8 4 5 ``` The table order is not important - just the next-key and prev-key fields. --- Both TheSoftwareJedi and Cade Roux have solutions that work for the data sets I posted last night. For the second question, both seem to fail for this dataset: ``` (key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8 ``` The order expected is by date then key, so one expected result might be: ``` 2:3,3:8,4:8,16:8,5:19 ``` and another: ``` key date prev-key next-key 1 1 null 2 2 3 1 3 3 8 2 4 4 8 3 16 5 19 16 10 10 19 5 11 11 67 10 15 15 45 11 null 16 8 4 5 ``` The table order is not important - just the next-key and prev-key fields.
My own attempt at the set solution, based on TheSoftwareJedi. First question: ``` select date from test where date = 8 union all select max(date) from test where date < 8 union all select min(date) from test where date > 8 order by date; ``` Second question: While debugging this, I used the data set: ``` (key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8,17:3,18:1 ``` to give this result: ``` select * from test2 where date = 8 union all select * from (select * from test2 where date = (select max(date) from test2 where date < 8)) where key = (select max(key) from test2 where date = (select max(date) from test2 where date < 8)) union all select * from (select * from test2 where date = (select min(date) from test2 where date > 8)) where key = (select min(key) from test2 where date = (select min(date) from test2 where date > 8)) order by date,key; ``` In both cases the final order by clause is strictly speaking optional.
203,316
<p>I have a table in my database which stores a tree structure. Here are the relevant fields:</p> <pre><code>mytree (id, parentid, otherfields...) </code></pre> <p>I want to find all the leaf nodes (that is, any record whose <code>id</code> is not another record's <code>parentid</code>)</p> <p>I've tried this:</p> <pre><code>SELECT * FROM mytree WHERE `id` NOT IN (SELECT DISTINCT `parentid` FROM `mytree`) </code></pre> <p>But that returned an empty set. Strangely, removing the "NOT" returns the set of all the non-leaf nodes.</p> <p>Can anyone see where I'm going wrong?</p> <p><em>Update:</em> Thanks for the answers folks, they all have been correct and worked for me. I've accepted Daniel's since it also explains why my query didn't work (the NULL thing).</p>
[ { "answer_id": 203323, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 3, "selected": false, "text": "<p>No clue why your query didn't work. Here's the identical thing in left outer join syntax - try it this way?</p>\n\n<pre><code>select a.*\nfrom mytree a left outer join\n mytree b on a.id = b.parentid\nwhere b.parentid is null\n</code></pre>\n" }, { "answer_id": 203329, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 6, "selected": true, "text": "<p>Your query didn't work because the sub-query includes <code>NULL</code>. The following slight modification works for me:</p>\n\n<pre><code>SELECT * FROM `mytree` WHERE `id` NOT IN (\n SELECT DISTINCT `parentid` FROM `mytree` WHERE `parentid` IS NOT NULL)\n</code></pre>\n" }, { "answer_id": 203331, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT * FROM mytree AS t1\nLEFT JOIN mytree AS t2 ON t1.id=t2.parentid\nWHERE t2.parentid IS NULL\n</code></pre>\n" }, { "answer_id": 203352, "author": "fatbuddha", "author_id": 28034, "author_profile": "https://Stackoverflow.com/users/28034", "pm_score": 1, "selected": false, "text": "<pre><code>Select * from mytree where id not in (Select distinct parentid from mytree where parentid is not null)\n</code></pre>\n<p><a href=\"http://archives.postgresql.org/pgsql-sql/2005-10/msg00228.php\" rel=\"nofollow noreferrer\">http://archives.postgresql.org/pgsql-sql/2005-10/msg00228.php</a></p>\n" }, { "answer_id": 32957298, "author": "Sunny srivastav", "author_id": 5411480, "author_profile": "https://Stackoverflow.com/users/5411480", "pm_score": -1, "selected": false, "text": "<p>my table structure is</p>\n\n<pre><code>memberid MemberID joiningposition packagetype\nRPM00000 NULL Root free\nRPM71572 RPM00000 Left Royal\nRPM323768 RPM00000 Right Royal\nRPM715790 RPM71572 Left free\nRPM323769 RPM71572 Right free\nRPM715987 RPM323768 Left free\nRPM323985 RPM323768 Right free\nRPM733333 RPM323985 Right free\nRPM324444 RPM715987 *emphasized text*Right Royal\n</code></pre>\n\n<p>--</p>\n\n<pre><code>ALTER procedure [dbo].[sunnypro]\nas\nDECLARE @pId varchar(40) = 'RPM00000';\nDeclare @Id int\nset @Id=(select id from registration where childid=@pId) \nbegin\n\n\n\n\n-- Recursive CTE\n WITH R AS\n (\n\n\n\nSELECT \n\n BU.DateofJoing,\n BU.childid,\n BU.joiningposition,\n BU.packagetype\n FROM registration AS BU\n WHERE\n BU.MemberID = @pId and\n BU.joiningposition IN ('Left', 'Right')\n or BU.packagetype in('Royal','Platinum','Majestic')\n and BU.Id&gt;@id\n UNION All\n\n-- Recursive part\nSELECT\n\n BU.DateofJoing,\n BU.childid,\n R.joiningposition,\n BU.packagetype\n\n\n FROM R\n JOIN registration AS BU\n ON BU.MemberID = R.childid\n WHERE\n BU.joiningposition IN ('Left', 'Right') and\n BU.packagetype in('Royal','Platinum','Majestic')\n and BU.Id&gt;@id\n)\n\nINSERT INTO Wallatpayout\n (childid\n ,packagetype\n\n ,joiningposition\n ,DateofJoing\n ,Total)\n\n-- Final groups of nodes found\nSELECT top 3\n\nR.childid,\nR.packagetype,\nR.joiningposition,\nR.DateofJoing,\nTotal = COUNT_BIG(*)\nFROM R where R.packagetype in('Royal','Platinum','Majestic')\nGROUP BY R.childid,\nR.joiningposition,\nR.DateofJoing,\nR.packagetype\nOPTION (MAXRECURSION 0);\nend\n</code></pre>\n" }, { "answer_id": 71867168, "author": "Rakib Hossain", "author_id": 4929725, "author_profile": "https://Stackoverflow.com/users/4929725", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-sql prettyprint-override\"><code>select *\nfrom `mytree `\nwhere not exists (select *\n from `mytree ` as `nodes`\n where `categories`.`id` = `nodes`.`parent`)\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I have a table in my database which stores a tree structure. Here are the relevant fields: ``` mytree (id, parentid, otherfields...) ``` I want to find all the leaf nodes (that is, any record whose `id` is not another record's `parentid`) I've tried this: ``` SELECT * FROM mytree WHERE `id` NOT IN (SELECT DISTINCT `parentid` FROM `mytree`) ``` But that returned an empty set. Strangely, removing the "NOT" returns the set of all the non-leaf nodes. Can anyone see where I'm going wrong? *Update:* Thanks for the answers folks, they all have been correct and worked for me. I've accepted Daniel's since it also explains why my query didn't work (the NULL thing).
Your query didn't work because the sub-query includes `NULL`. The following slight modification works for me: ``` SELECT * FROM `mytree` WHERE `id` NOT IN ( SELECT DISTINCT `parentid` FROM `mytree` WHERE `parentid` IS NOT NULL) ```
203,336
<p>How would one create a Singleton class using PHP5 classes?</p>
[ { "answer_id": 203359, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": true, "text": "<pre><code>/**\n * Singleton class\n *\n */\nfinal class UserFactory\n{\n private static $inst = null;\n\n // Prevent cloning and de-serializing\n private function __clone(){}\n private function __wakeup(){}\n\n\n /**\n * Call this method to get singleton\n *\n * @return UserFactory\n */\n public static function Instance()\n {\n if ($inst === null) {\n $inst = new UserFactory();\n }\n return $inst;\n }\n \n /**\n * Private ctor so nobody else can instantiate it\n *\n */\n private function __construct()\n {\n \n }\n}\n</code></pre>\n<p>To use:</p>\n<pre><code>$fact = UserFactory::Instance();\n$fact2 = UserFactory::Instance();\n</code></pre>\n<p><code>$fact == $fact2;</code></p>\n<p>But:</p>\n<pre><code>$fact = new UserFactory()\n</code></pre>\n<p>Throws an error.</p>\n<p>See <a href=\"http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static\" rel=\"nofollow noreferrer\" title=\"PHP: Variable Scope : Using Static Variables\">http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static</a> to understand static variable scopes and why setting <code>static $inst = null;</code> works.</p>\n" }, { "answer_id": 203919, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 5, "selected": false, "text": "<p>You probably should add a private __clone() method to disallow cloning of an instance.</p>\n\n<pre><code>private function __clone() {}\n</code></pre>\n\n<p>If you don't include this method the following gets possible</p>\n\n<pre><code>$inst1=UserFactory::Instance(); // to stick with the example provided above\n$inst2=clone $inst1;\n</code></pre>\n\n<p>now <code>$inst1</code> !== <code>$inst2</code> - they are not the same instance any more.</p>\n" }, { "answer_id": 1939269, "author": "selfawaresoup", "author_id": 235308, "author_profile": "https://Stackoverflow.com/users/235308", "pm_score": 7, "selected": false, "text": "<p>PHP 5.3 allows the creation of an inheritable Singleton class via late static binding:</p>\n\n<pre><code>class Singleton\n{\n protected static $instance = null;\n\n protected function __construct()\n {\n //Thou shalt not construct that which is unconstructable!\n }\n\n protected function __clone()\n {\n //Me not like clones! Me smash clones!\n }\n\n public static function getInstance()\n {\n if (!isset(static::$instance)) {\n static::$instance = new static;\n }\n return static::$instance;\n }\n}\n</code></pre>\n\n<p>This solves the problem, that prior to PHP 5.3 any class that extended a Singleton would produce an instance of its parent class instead of its own.</p>\n\n<p>Now you can do:</p>\n\n<pre><code>class Foobar extends Singleton {};\n$foo = Foobar::getInstance();\n</code></pre>\n\n<p>And $foo will be an instance of Foobar instead of an instance of Singleton.</p>\n" }, { "answer_id": 3245620, "author": "RobertPitt", "author_id": 353790, "author_profile": "https://Stackoverflow.com/users/353790", "pm_score": 3, "selected": false, "text": "<h1>Supports Multiple Objects with 1 line per class:</h1>\n<p>This method will enforce singletons on any class you wish, al you have to do is add 1 method to the class you wish to make a singleton and this will do it for you.</p>\n<p>This also stores objects in a &quot;SingleTonBase&quot; class so you can debug all your objects that you have used in your system by recursing the <code>SingleTonBase</code> objects.</p>\n<hr />\n<p>Create a file called SingletonBase.php and include it in root of your script!</p>\n<p>The code is</p>\n<pre><code>abstract class SingletonBase\n{\n private static $storage = array();\n\n public static function Singleton($class)\n {\n if(in_array($class,self::$storage))\n {\n return self::$storage[$class];\n }\n return self::$storage[$class] = new $class();\n }\n public static function storage()\n {\n return self::$storage;\n }\n}\n</code></pre>\n<p>Then for any class you want to make a singleton just add this small single method.</p>\n<pre><code>public static function Singleton()\n{\n return SingletonBase::Singleton(get_class());\n}\n</code></pre>\n<hr />\n<p>Here is a small example:</p>\n<pre><code>include 'libraries/SingletonBase.resource.php';\n\nclass Database\n{\n //Add that singleton function.\n public static function Singleton()\n {\n return SingletonBase::Singleton(get_class());\n }\n\n public function run()\n {\n echo 'running...';\n }\n}\n\n$Database = Database::Singleton();\n\n$Database-&gt;run();\n</code></pre>\n<p>And you can just add this singleton function in any class you have and it will only create 1 instance per class.</p>\n<p>NOTE: You should always make the __construct private to eliminate the use of new Class(); instantiations.</p>\n" }, { "answer_id": 8905139, "author": "hungneox", "author_id": 237107, "author_profile": "https://Stackoverflow.com/users/237107", "pm_score": 3, "selected": false, "text": "<pre><code>protected static $_instance;\n\npublic static function getInstance()\n{\n if(is_null(self::$_instance))\n {\n self::$_instance = new self();\n }\n return self::$_instance;\n}\n</code></pre>\n\n<p>This code can apply for any class without caring about its class name.</p>\n" }, { "answer_id": 13716841, "author": "rizon", "author_id": 794822, "author_profile": "https://Stackoverflow.com/users/794822", "pm_score": 3, "selected": false, "text": "<pre><code>class Database{\n\n //variable to hold db connection\n private $db;\n //note we used static variable,beacuse an instance cannot be used to refer this\n public static $instance;\n\n //note constructor is private so that classcannot be instantiated\n private function __construct(){\n //code connect to database \n\n } \n\n //to prevent loop hole in PHP so that the class cannot be cloned\n private function __clone() {}\n\n //used static function so that, this can be called from other classes\n public static function getInstance(){\n\n if( !(self::$instance instanceof self) ){\n self::$instance = new self(); \n }\n return self::$instance;\n }\n\n\n public function query($sql){\n //code to run the query\n }\n\n }\n\n\nAccess the method getInstance using\n$db = Singleton::getInstance();\n$db-&gt;query();\n</code></pre>\n" }, { "answer_id": 14511989, "author": "user2009125", "author_id": 2009125, "author_profile": "https://Stackoverflow.com/users/2009125", "pm_score": 2, "selected": false, "text": "<p>I know this is probably going to cause an unnecessary flame war, but I can see how you might want more than one database connection, so I would concede the point that singleton might not be the best solution for that... however, there are other uses of the singleton pattern that I find extremely useful.</p>\n\n<p>Here's an example: I decided to roll my own MVC and templating engine because I wanted something really lightweight. However, the data that I want to display contains a lot of special math characters such as &ge; and &mu; and what have you... The data is stored as the actual UTF-8 character in my database rather than pre-HTML-encoded because my app can deliver other formats such as PDF and CSV in addition to HTML. The appropriate place to format for HTML is inside the template (\"view\" if you will) that is responsible for rendering that page section (snippet). I want to convert them to their appropriate HTML entities, but PHPs get_html_translation_table() function is not super fast. It makes better sense to retrieve the data one time and store as an array, making it available for all to use. Here's a sample I knocked together to test the speed. Presumably, this would work regardless of whether the other methods you use (after getting the instance) were static or not.</p>\n\n<pre><code>class EncodeHTMLEntities {\n\n private static $instance = null;//stores the instance of self\n private $r = null;//array of chars elligalbe for replacement\n\n private function __clone(){\n }//disable cloning, no reason to clone\n\n private function __construct()\n {\n $allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);\n $specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);\n $this-&gt;r = array_diff($allEntities, $specialEntities);\n }\n\n public static function replace($string)\n {\n if(!(self::$instance instanceof self) ){\n self::$instance = new self();\n }\n return strtr($string, self::$instance-&gt;r);\n }\n}\n//test one million encodings of a string\n$start = microtime(true);\nfor($x=0; $x&lt;1000000; $x++){\n $dump = EncodeHTMLEntities::replace(\"Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (≥96 hrs)\");\n}\n$end = microtime(true);\necho \"Run time: \".($end-$start).\" seconds using singleton\\n\";\n//now repeat the same without using singleton\n$start = microtime(true);\nfor($x=0; $x&lt;1000000; $x++){\n $allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);\n $specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);\n $r = array_diff($allEntities, $specialEntities);\n $dump = strtr(\"Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (≥96 hrs)\", $r);\n}\n$end = microtime(true);\necho \"Run time: \".($end-$start).\" seconds without using singleton\";\n</code></pre>\n\n<p>Basically, I saw typical results like this:</p>\n\n<pre>php test.php\nRun time: 27.842966794968 seconds using singleton\nRun time: 237.78191494942 seconds without using singleton\n</pre>\n\n<p>So while I'm certainly no expert, I don't see a more convenient and reliable way to reduce the overhead of slow calls for some kind of data, while making it super simple (single line of code to do what you need). Granted my example only has one useful method, and therefore is no better than a globally defined function, but as soon as you have two methods, you're going to want to group them together, right? Am I way off base?</p>\n\n<p>Also, I prefer examples that actually DO something, since sometimes it's hard to visualise when an example includes statements like \"//do something useful here\" which I see all the time when searching for tutorials.</p>\n\n<p>Anyway, I'd love any feedback or comments on why using a singleton for this type of thing is detrimental (or overly complicated).</p>\n" }, { "answer_id": 14645766, "author": "bboydev", "author_id": 1578690, "author_profile": "https://Stackoverflow.com/users/1578690", "pm_score": -1, "selected": false, "text": "<p>Here's my example that provides ability to call as $var = new Singleton() and also creating 3 variables to test if it creates new object: </p>\n\n<pre><code>class Singleton{\n\n private static $data;\n\n function __construct(){\n if ($this::$data == null){\n $this-&gt;makeSingleton();\n }\n echo \"&lt;br/&gt;\".$this::$data;\n }\n\n private function makeSingleton(){\n $this::$data = rand(0, 100);\n }\n\n public function change($new_val){\n $this::$data = $new_val;\n }\n\n public function printme(){\n echo \"&lt;br/&gt;\".$this::$data;\n }\n\n}\n\n\n$a = new Singleton();\n$b = new Singleton();\n$c = new Singleton();\n\n$a-&gt;change(-2);\n$a-&gt;printme();\n$b-&gt;printme();\n\n$d = new Singleton();\n$d-&gt;printme();\n</code></pre>\n" }, { "answer_id": 15870364, "author": "mpartel", "author_id": 965979, "author_profile": "https://Stackoverflow.com/users/965979", "pm_score": 7, "selected": false, "text": "<p>Unfortunately <a href=\"https://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5/1939269#1939269\">Inwdr's answer</a> breaks when there are multiple subclasses.</p>\n\n<p>Here is a correct inheritable Singleton base class.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class Singleton\n{\n private static $instances = array();\n protected function __construct() {}\n protected function __clone() {}\n public function __wakeup()\n {\n throw new Exception(\"Cannot unserialize singleton\");\n }\n\n public static function getInstance()\n {\n $cls = get_called_class(); // late-static-bound class name\n if (!isset(self::$instances[$cls])) {\n self::$instances[$cls] = new static;\n }\n return self::$instances[$cls];\n }\n}\n</code></pre>\n\n<p>Test code:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class Foo extends Singleton {}\nclass Bar extends Singleton {}\n\necho get_class(Foo::getInstance()) . \"\\n\";\necho get_class(Bar::getInstance()) . \"\\n\";\n</code></pre>\n" }, { "answer_id": 16624144, "author": "jose segura", "author_id": 2396760, "author_profile": "https://Stackoverflow.com/users/2396760", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;?php\n/**\n * Singleton patter in php\n **/\ntrait SingletonTrait {\n protected static $inst = null;\n\n /**\n * call this method to get instance\n **/\n public static function getInstance(){\n if (static::$inst === null){\n static::$inst = new static();\n }\n return static::$inst;\n }\n\n /**\n * protected to prevent clonning \n **/\n protected function __clone(){\n }\n\n /**\n * protected so no one else can instance it \n **/\n protected function __construct(){\n }\n}\n</code></pre>\n\n<p>to use:</p>\n\n<pre><code>/**\n * example of class definitions using SingletonTrait\n */\nclass DBFactory {\n /**\n * we are adding the trait here \n **/\n use SingletonTrait;\n\n /**\n * This class will have a single db connection as an example\n **/\n protected $db;\n\n\n /**\n * as an example we will create a PDO connection\n **/\n protected function __construct(){\n $this-&gt;db = \n new PDO('mysql:dbname=foodb;port=3305;host=127.0.0.1','foouser','foopass');\n }\n}\nclass DBFactoryChild extends DBFactory {\n /**\n * we repeating the inst so that it will differentiate it\n * from UserFactory singleton\n **/\n protected static $inst = null;\n}\n\n\n/**\n * example of instanciating the classes\n */\n$uf0 = DBFactoryChild::getInstance();\nvar_dump($uf0);\n$uf1 = DBFactory::getInstance();\nvar_dump($uf1);\necho $uf0 === $uf1;\n</code></pre>\n\n<p>respose:</p>\n\n<pre><code>object(DBFactoryChild)#1 (0) {\n}\nobject(DBFactory)#2 (0) {\n}\n</code></pre>\n\n<p>If you are using PHP 5.4: <strong><em>trait</em></strong> its an option, so you don't have to waste the inheritance hierarchy in order to have the <strong><em>Singleton pattern</em></strong></p>\n\n<p>and also notice that whether you use <strong><em>traits</em></strong> or <strong><em>extends Singleton</em></strong> class \none loose end was to create singleton of child classes if you dont add the following line of code:</p>\n\n<pre><code> protected static $inst = null;\n</code></pre>\n\n<p>in the child class</p>\n\n<p>the unexpected result will be:</p>\n\n<pre><code>object(DBFactoryChild)#1 (0) {\n}\nobject(DBFactoryChild)#1 (0) {\n}\n</code></pre>\n" }, { "answer_id": 18155710, "author": "Tom Stambaugh", "author_id": 1723615, "author_profile": "https://Stackoverflow.com/users/1723615", "pm_score": 2, "selected": false, "text": "<p>All this complexity (\"late static binding\" ... harumph) is, to me, simply a sign of PHP's broken object/class model. If class objects were first-class objects (see Python), then \"$_instance\" would be a class <em>instance</em> variable -- a member of the class object, as opposed to a member/property of its instances, and also as opposed to shared by its descendants. In the Smalltalk world, this is the difference between a \"class variable\" and a \"class instance variable\".</p>\n\n<p>In PHP, it looks to me as though we need to take to heart the guidance that patterns are a guide towards writing code -- we might perhaps think about a Singleton template, but trying to write code that inherits from an actual \"Singleton\" class looks misguided for PHP (though I supposed some enterprising soul could create a suitable SVN keyword).</p>\n\n<p>I will continue to just code each singleton separately, using a shared template.</p>\n\n<p>Notice that I'm absolutely staying OUT of the singletons-are-evil discussion, life is too short.</p>\n" }, { "answer_id": 19259931, "author": "Joseph Crawford", "author_id": 1827986, "author_profile": "https://Stackoverflow.com/users/1827986", "pm_score": 0, "selected": false, "text": "<p>I agree with the first answer but I would also declare the class as final so that it cannot be extended as extending a singleton violates the singleton pattern. Also the instance variable should be private so that it cannot be accessed directly. Also make the __clone method private so that you cannot clone the singleton object.</p>\n\n<p>Below is some example code.</p>\n\n<pre><code>/**\n * Singleton class\n *\n */\nfinal class UserFactory\n{\n private static $_instance = null;\n\n /**\n * Private constructor\n *\n */\n private function __construct() {}\n\n /**\n * Private clone method\n *\n */\n private function __clone() {}\n\n /**\n * Call this method to get singleton\n *\n * @return UserFactory\n */\n public static function getInstance()\n {\n if (self::$_instance === null) {\n self::$_instance = new UserFactory();\n }\n return self::$_instance;\n }\n}\n</code></pre>\n\n<p>Example Usage</p>\n\n<pre><code>$user_factory = UserFactory::getInstance();\n</code></pre>\n\n<p>What this stops you from doing (which would violate the singleton pattern.. </p>\n\n<p><strong>YOU CANNOT DO THIS!</strong></p>\n\n<pre><code>$user_factory = UserFactory::$_instance;\n\nclass SecondUserFactory extends UserFactory { }\n</code></pre>\n" }, { "answer_id": 19959264, "author": "Mário Kapusta", "author_id": 2076112, "author_profile": "https://Stackoverflow.com/users/2076112", "pm_score": 0, "selected": false, "text": "<p>This should be the right way of Singleton.</p>\n\n<pre><code>class Singleton {\n\n private static $instance;\n private $count = 0;\n\n protected function __construct(){\n\n }\n\n public static function singleton(){\n\n if (!isset(self::$instance)) {\n\n self::$instance = new Singleton;\n\n }\n\n return self::$instance;\n\n }\n\n public function increment()\n {\n return $this-&gt;count++;\n }\n\n protected function __clone(){\n\n }\n\n protected function __wakeup(){\n\n }\n\n} \n</code></pre>\n" }, { "answer_id": 23998306, "author": "Eric Anderson", "author_id": 120067, "author_profile": "https://Stackoverflow.com/users/120067", "pm_score": 0, "selected": false, "text": "<p>I liked @jose-segura method of using traits but didn't like the need to define a static variable on sub-classes. Below is a solution that avoids it by caching the instances in a static local variable to the factory method indexed by class name:</p>\n\n<pre><code>&lt;?php\ntrait Singleton {\n\n # Single point of entry for creating a new instance. For a given\n # class always returns the same instance.\n public static function instance(){\n static $instances = array();\n $class = get_called_class();\n if( !isset($instances[$class]) ) $instances[$class] = new $class();\n return $instances[$class];\n }\n\n # Kill traditional methods of creating new instances\n protected function __clone() {}\n protected function __construct() {}\n}\n</code></pre>\n\n<p>Usage is the same as @jose-segura only no need for the static variable in sub-classes.</p>\n" }, { "answer_id": 27361638, "author": "sunil rajput", "author_id": 1071262, "author_profile": "https://Stackoverflow.com/users/1071262", "pm_score": 0, "selected": false, "text": "<p>Database class that checks if there is any existing database instance it will return previous instance.</p>\n\n<pre><code> class Database { \n public static $instance; \n public static function getInstance(){ \n if(!isset(Database::$instance) ) { \n Database::$instance = new Database(); \n } \n return Database::$instance; \n } \n private function __cunstruct() { \n /* private and cant create multiple objects */ \n } \n public function getQuery(){ \n return \"Test Query Data\"; \n } \n } \n $dbObj = Database::getInstance(); \n $dbObj2 = Database::getInstance(); \n var_dump($dbObj); \n var_dump($dbObj2); \n\n\n/* \nAfter execution you will get following output: \n\nobject(Database)[1] \nobject(Database)[1] \n\n*/ \n</code></pre>\n\n<p>Ref <a href=\"http://www.phptechi.com/php-singleton-design-patterns-example.html\" rel=\"nofollow\">http://www.phptechi.com/php-singleton-design-patterns-example.html</a></p>\n" }, { "answer_id": 34342568, "author": "Krzysztof Przygoda", "author_id": 2254935, "author_profile": "https://Stackoverflow.com/users/2254935", "pm_score": 1, "selected": false, "text": "<p>This article covers topic quite extensively: \n<a href=\"http://www.phptherightway.com/pages/Design-Patterns.html#singleton\" rel=\"nofollow\">http://www.phptherightway.com/pages/Design-Patterns.html#singleton</a></p>\n\n<blockquote>\n <p>Note the following:</p>\n \n <ul>\n <li>The constructor <code>__construct()</code> is declared as <code>protected</code> to prevent creating a new instance outside of the class via the <code>new</code> operator.</li>\n <li>The magic method <code>__clone()</code> is declared as <code>private</code> to prevent cloning of an instance of the class via the <code>clone</code> operator.</li>\n <li>The magic method <code>__wakeup()</code> is declared as <code>private</code> to prevent unserializing of an instance of the class via the global function\n <code>unserialize()</code>.</li>\n <li>A new instance is created via late static binding in the static creation method <code>getInstance()</code> with the keyword <code>static</code>. This\n allows the subclassing of the <code>class Singleton</code> in the example.</li>\n </ul>\n</blockquote>\n" }, { "answer_id": 34563986, "author": "Surendra Kumar Ahir", "author_id": 4773669, "author_profile": "https://Stackoverflow.com/users/4773669", "pm_score": 0, "selected": false, "text": "<p><strong>This is the example of create singleton on Database class</strong> </p>\n\n<p>design patterns\n1) singleton</p>\n\n<pre><code>class Database{\n public static $instance;\n public static function getInstance(){\n if(!isset(Database::$instance)){\n Database::$instance=new Database();\n\n return Database::$instance;\n }\n\n }\n\n $db=Database::getInstance();\n $db2=Database::getInstance();\n $db3=Database::getInstance();\n\n var_dump($db);\n var_dump($db2);\n var_dump($db3);\n</code></pre>\n\n<p>then out put is --</p>\n\n<pre><code> object(Database)[1]\n object(Database)[1]\n object(Database)[1]\n</code></pre>\n\n<p>use only single instance not create 3 instance </p>\n" }, { "answer_id": 37800033, "author": "Abraham Tugalov", "author_id": 3684575, "author_profile": "https://Stackoverflow.com/users/3684575", "pm_score": 5, "selected": false, "text": "<p><strong>The Real One and Modern</strong> way to make Singleton Pattern is:</p>\n\n<pre><code>&lt;?php\n\n/**\n * Singleton Pattern.\n * \n * Modern implementation.\n */\nclass Singleton\n{\n /**\n * Call this method to get singleton\n */\n public static function instance()\n {\n static $instance = false;\n if( $instance === false )\n {\n // Late static binding (PHP 5.3+)\n $instance = new static();\n }\n\n return $instance;\n }\n\n /**\n * Make constructor private, so nobody can call \"new Class\".\n */\n private function __construct() {}\n\n /**\n * Make clone magic method private, so nobody can clone instance.\n */\n private function __clone() {}\n\n /**\n * Make sleep magic method private, so nobody can serialize instance.\n */\n private function __sleep() {}\n\n /**\n * Make wakeup magic method private, so nobody can unserialize instance.\n */\n private function __wakeup() {}\n\n}\n</code></pre>\n\n<p>So now you can use it like.</p>\n\n<pre><code>&lt;?php\n\n/**\n * Database.\n *\n * Inherited from Singleton, so it's now got singleton behavior.\n */\nclass Database extends Singleton {\n\n protected $label;\n\n /**\n * Example of that singleton is working correctly.\n */\n public function setLabel($label)\n {\n $this-&gt;label = $label;\n }\n\n public function getLabel()\n {\n return $this-&gt;label;\n }\n\n}\n\n// create first instance\n$database = Database::instance();\n$database-&gt;setLabel('Abraham');\necho $database-&gt;getLabel() . PHP_EOL;\n\n// now try to create other instance as well\n$other_db = Database::instance();\necho $other_db-&gt;getLabel() . PHP_EOL; // Abraham\n\n$other_db-&gt;setLabel('Priler');\necho $database-&gt;getLabel() . PHP_EOL; // Priler\necho $other_db-&gt;getLabel() . PHP_EOL; // Priler\n</code></pre>\n\n<p>As you see this realization is lot more flexible.</p>\n" }, { "answer_id": 39729914, "author": "DevWL", "author_id": 2179965, "author_profile": "https://Stackoverflow.com/users/2179965", "pm_score": 3, "selected": false, "text": "<p>You don't really need to use Singleton pattern because it's considered to be an antipattern. Basically there is a lot of reasons to not to implement this pattern at all. Read this to start with: <a href=\"https://stackoverflow.com/questions/8776788/best-practice-on-php-singleton-classes\">Best practice on PHP singleton classes</a>. </p>\n\n<p>If after all you still think you need to use Singleton pattern then we could write a class that will allow us to get Singleton functionality by extending our SingletonClassVendor abstract class.</p>\n\n<p>This is what I came with to solve this problem.</p>\n\n<pre><code>&lt;?php\nnamespace wl;\n\n\n/**\n * @author DevWL\n * @dosc allows only one instance for each extending class.\n * it acts a litle bit as registry from the SingletonClassVendor abstract class point of view\n * but it provides a valid singleton behaviour for its children classes\n * Be aware, the singleton pattern is consider to be an anti-pattern\n * mostly because it can be hard to debug and it comes with some limitations.\n * In most cases you do not need to use singleton pattern\n * so take a longer moment to think about it before you use it.\n */\nabstract class SingletonClassVendor\n{\n /**\n * holds an single instance of the child class\n *\n * @var array of objects\n */\n protected static $instance = [];\n\n /**\n * @desc provides a single slot to hold an instance interchanble between all child classes.\n * @return object\n */\n public static final function getInstance(){\n $class = get_called_class(); // or get_class(new static());\n if(!isset(self::$instance[$class]) || !self::$instance[$class] instanceof $class){\n self::$instance[$class] = new static(); // create and instance of child class which extends Singleton super class\n echo \"new \". $class . PHP_EOL; // remove this line after testing\n return self::$instance[$class]; // remove this line after testing\n }\n echo \"old \". $class . PHP_EOL; // remove this line after testing\n return static::$instance[$class];\n }\n\n /**\n * Make constructor abstract to force protected implementation of the __constructor() method, so that nobody can call directly \"new Class()\".\n */\n abstract protected function __construct();\n\n /**\n * Make clone magic method private, so nobody can clone instance.\n */\n private function __clone() {}\n\n /**\n * Make sleep magic method private, so nobody can serialize instance.\n */\n private function __sleep() {}\n\n /**\n * Make wakeup magic method private, so nobody can unserialize instance.\n */\n private function __wakeup() {}\n\n}\n</code></pre>\n\n<p>Use example:</p>\n\n<pre><code>/**\n * EXAMPLE\n */\n\n/**\n * @example 1 - Database class by extending SingletonClassVendor abstract class becomes fully functional singleton\n * __constructor must be set to protected becaouse: \n * 1 to allow instansiation from parent class \n * 2 to prevent direct instanciation of object with \"new\" keword.\n * 3 to meet requierments of SingletonClassVendor abstract class\n */\nclass Database extends SingletonClassVendor\n{\n public $type = \"SomeClass\";\n protected function __construct(){\n echo \"DDDDDDDDD\". PHP_EOL; // remove this line after testing\n }\n}\n\n\n/**\n * @example 2 - Config ...\n */\nclass Config extends SingletonClassVendor\n{\n public $name = \"Config\";\n protected function __construct(){\n echo \"CCCCCCCCCC\" . PHP_EOL; // remove this line after testing\n }\n}\n</code></pre>\n\n<p>Just to prove that it works as expected: </p>\n\n<pre><code>/**\n * TESTING\n */\n$bd1 = Database::getInstance(); // new\n$bd2 = Database::getInstance(); // old\n$bd3 = Config::getInstance(); // new\n$bd4 = Config::getInstance(); // old\n$bd5 = Config::getInstance(); // old\n$bd6 = Database::getInstance(); // old\n$bd7 = Database::getInstance(); // old\n$bd8 = Config::getInstance(); // old\n\necho PHP_EOL.\"COMPARE ALL DATABASE INSTANCES\".PHP_EOL;\nvar_dump($bd1);\necho '$bd1 === $bd2' . ($bd1 === $bd2)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\necho '$bd2 === $bd6' . ($bd2 === $bd6)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\necho '$bd6 === $bd7' . ($bd6 === $bd7)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\n\necho PHP_EOL;\n\necho PHP_EOL.\"COMPARE ALL CONFIG INSTANCES\". PHP_EOL;\nvar_dump($bd3);\necho '$bd3 === $bd4' . ($bd3 === $bd4)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\necho '$bd4 === $bd5' . ($bd4 === $bd5)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\necho '$bd5 === $bd8' . ($bd5 === $bd8)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\n</code></pre>\n" }, { "answer_id": 41951477, "author": "Gyaneshwar Pardhi", "author_id": 565551, "author_profile": "https://Stackoverflow.com/users/565551", "pm_score": 1, "selected": false, "text": "<p>I have written long back thought to share here </p>\n\n<pre><code>class SingletonDesignPattern {\n\n //just for demo there will be only one instance\n private static $instanceCount =0;\n\n //create the private instance variable\n private static $myInstance=null;\n\n //make constructor private so no one create object using new Keyword\n private function __construct(){}\n\n //no one clone the object\n private function __clone(){}\n\n //avoid serialazation\n public function __wakeup(){}\n\n //ony one way to create object\n public static function getInstance(){\n\n if(self::$myInstance==null){\n self::$myInstance=new SingletonDesignPattern();\n self::$instanceCount++;\n }\n return self::$myInstance;\n }\n\n public static function getInstanceCount(){\n return self::$instanceCount;\n }\n\n}\n\n//now lets play with singleton design pattern\n\n$instance = SingletonDesignPattern::getInstance();\n$instance = SingletonDesignPattern::getInstance();\n$instance = SingletonDesignPattern::getInstance();\n$instance = SingletonDesignPattern::getInstance();\n\necho \"number of instances: \".SingletonDesignPattern::getInstanceCount();\n</code></pre>\n" }, { "answer_id": 59662578, "author": "Dmitry", "author_id": 3723707, "author_profile": "https://Stackoverflow.com/users/3723707", "pm_score": 0, "selected": false, "text": "<p>Quick example:</p>\n\n<pre><code>final class Singleton\n{\n private static $instance = null;\n\n private function __construct(){}\n\n private function __clone(){}\n\n private function __wakeup(){}\n\n public static function get_instance()\n {\n if ( static::$instance === null ) {\n static::$instance = new static();\n }\n return static::$instance;\n }\n}\n</code></pre>\n\n<p>Hope help.</p>\n" }, { "answer_id": 70051757, "author": "Maniruzzaman Akash", "author_id": 5543577, "author_profile": "https://Stackoverflow.com/users/5543577", "pm_score": 0, "selected": false, "text": "<p>The above answers are ok, But I'll add more.</p>\n<p>Whoever come here in 2021, I'll show another example of using <code>Singleton</code> Pattern class as a <code>trait</code> and Re-use this in any class.</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n\nnamespace Akash;\n\ntrait Singleton\n{\n /**\n * Singleton Instance\n *\n * @var Singleton\n */\n private static $instance;\n\n /**\n * Private Constructor\n *\n * We can't use the constructor to create an instance of the class\n *\n * @return void\n */\n private function __construct()\n {\n // Don't do anything, we don't want to be initialized\n }\n\n /**\n * Get the singleton instance\n *\n * @return Singleton\n */\n public static function getInstance()\n {\n if (!isset(self::$instance)) {\n self::$instance = new self();\n }\n\n return self::$instance;\n }\n\n /**\n * Private clone method to prevent cloning of the instance of the\n * Singleton instance.\n *\n * @return void\n */\n private function __clone()\n {\n // Don't do anything, we don't want to be cloned\n }\n\n /**\n * Private unserialize method to prevent unserializing of the Singleton\n * instance.\n *\n * @return void\n */\n private function __wakeup()\n {\n // Don't do anything, we don't want to be unserialized\n }\n}\n</code></pre>\n<p>So, use it like in any class easily. Suppose, we want to implement Singleton pattern in <code>UserSeeder</code> class.</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n\nclass UserSeeder\n{\n use Singleton;\n\n /**\n * Seed Users\n *\n * @return void\n */\n public function seed()\n {\n echo 'Seeding...';\n }\n}\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26210/" ]
How would one create a Singleton class using PHP5 classes?
``` /** * Singleton class * */ final class UserFactory { private static $inst = null; // Prevent cloning and de-serializing private function __clone(){} private function __wakeup(){} /** * Call this method to get singleton * * @return UserFactory */ public static function Instance() { if ($inst === null) { $inst = new UserFactory(); } return $inst; } /** * Private ctor so nobody else can instantiate it * */ private function __construct() { } } ``` To use: ``` $fact = UserFactory::Instance(); $fact2 = UserFactory::Instance(); ``` `$fact == $fact2;` But: ``` $fact = new UserFactory() ``` Throws an error. See [http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static](http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static "PHP: Variable Scope : Using Static Variables") to understand static variable scopes and why setting `static $inst = null;` works.
203,358
<p>I want to set a style on the first and last TabItems in a TabControl, and have them updated as the visibility of the TabItems is changed. I can't see a way to do so with triggers.</p> <p>What we're after looks like this:</p> <pre>| > > > |</pre> <p>And the visibility of TabItems are determined by binding.</p> <p>I do have it working in code. On TabItem visibility changed, enumerate through TabItems until you find the first visible one. Set the style on that one. For all other visible TabItems, set them to the pointy style (so that the previously first visible one is now pointy). Then start from the end until you find a visible TabItem and set the last style on that one. (This also lets us address an issue with TabControl where it will display the content of a non-visible TabItem if none of the visible TabItems are selected.)</p> <p>There's undoubtably improvements I could make to my method, but I'm not convinced that it IS the right approach.</p> <p>How would you approach this?</p>
[ { "answer_id": 204455, "author": "Dave", "author_id": 28197, "author_profile": "https://Stackoverflow.com/users/28197", "pm_score": 1, "selected": false, "text": "<p>Sorry can you explain this a little better so far i have interpreted your question as so:</p>\n\n<p>Apply a specific style when the visibility changes on the tab items at the beginning and end of the tab control - ie if it scrolls out of view then change the style?</p>\n\n<p>If this is so then, as you add your TabItems (either programmatically or in wpf) you will need to implement the IsVisibleChanged event handler on the TabItems you wish to handle (ie first and last or all?)</p>\n\n<pre><code> public Window1()\n {\n InitializeComponent();\n\n this.myTabItem.IsVisibleChanged += new DependencyPropertyChangedEventHandler(myTabItem_IsVisibleChanged);\n }\n\n private void myTabItem_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n myTabControl.Items[0].Style = FindResource(\"MyTabItemStyle\") as Style;\n }\n</code></pre>\n\n<p>This is simple if you programmatically add the tab items to your control... :)</p>\n" }, { "answer_id": 210081, "author": "Donnelle", "author_id": 28074, "author_profile": "https://Stackoverflow.com/users/28074", "pm_score": 1, "selected": false, "text": "<p>Note that the visibility of our TabItems will not be affected while that TabControl is in view, so we can apply styles only when the TabControl visibility changes. </p>\n\n<pre>\nprivate void Breadcrumb_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n{\n if ((bool)e.NewValue)\n {\n if (sender is TabControl)\n {\n TabControl tabControl = (TabControl)sender;\n int firstVisible = -1;\n\n for (int i = 0; i -1) //if is -1, they're all invisible\n {\n\n for (int i = tabControl.Items.Count - 1; i > firstVisible; i--)\n {\n TabItem tabItem = (TabItem)tabControl.Items[i];\n if (tabItem.Visibility == Visibility.Visible)\n {\n\n tabItem.Style = (Style)FindResource(\"LastBreadcrumbTabItem\");\n break;\n\n }\n }\n }\n }\n }\n }\n</pre>\n" }, { "answer_id": 3290692, "author": "dan soltesz", "author_id": 396871, "author_profile": "https://Stackoverflow.com/users/396871", "pm_score": 0, "selected": false, "text": "<p>I have taken the silverlight tabcontrol and made the tabitems scrollable. here is a link to the post. I think this is what you are looking for.</p>\n\n<p><a href=\"http://www.dansoltesz.com/post/2010/07/20/Silverlight-tabcontrol-with-scrollable-tabItems.aspx\" rel=\"nofollow noreferrer\">http://www.dansoltesz.com/post/2010/07/20/Silverlight-tabcontrol-with-scrollable-tabItems.aspx</a> </p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28074/" ]
I want to set a style on the first and last TabItems in a TabControl, and have them updated as the visibility of the TabItems is changed. I can't see a way to do so with triggers. What we're after looks like this: ``` | > > > | ``` And the visibility of TabItems are determined by binding. I do have it working in code. On TabItem visibility changed, enumerate through TabItems until you find the first visible one. Set the style on that one. For all other visible TabItems, set them to the pointy style (so that the previously first visible one is now pointy). Then start from the end until you find a visible TabItem and set the last style on that one. (This also lets us address an issue with TabControl where it will display the content of a non-visible TabItem if none of the visible TabItems are selected.) There's undoubtably improvements I could make to my method, but I'm not convinced that it IS the right approach. How would you approach this?
Sorry can you explain this a little better so far i have interpreted your question as so: Apply a specific style when the visibility changes on the tab items at the beginning and end of the tab control - ie if it scrolls out of view then change the style? If this is so then, as you add your TabItems (either programmatically or in wpf) you will need to implement the IsVisibleChanged event handler on the TabItems you wish to handle (ie first and last or all?) ``` public Window1() { InitializeComponent(); this.myTabItem.IsVisibleChanged += new DependencyPropertyChangedEventHandler(myTabItem_IsVisibleChanged); } private void myTabItem_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { myTabControl.Items[0].Style = FindResource("MyTabItemStyle") as Style; } ``` This is simple if you programmatically add the tab items to your control... :)
203,377
<p>How do you get the max value of an enum?</p>
[ { "answer_id": 203389, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 9, "selected": true, "text": "<p>Enum.GetValues() seems to return the values in order, so you can do something like this:</p>\n\n<pre><code>// given this enum:\npublic enum Foo\n{\n Fizz = 3, \n Bar = 1,\n Bang = 2\n}\n\n// this gets Fizz\nvar lastFoo = Enum.GetValues(typeof(Foo)).Cast&lt;Foo&gt;().Last();\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>For those not willing to read through the comments: You can also do it this way:</p>\n\n<pre><code>var lastFoo = Enum.GetValues(typeof(Foo)).Cast&lt;Foo&gt;().Max();\n</code></pre>\n\n<p>... which will work when some of your enum values are negative.</p>\n" }, { "answer_id": 203995, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": false, "text": "<p>This is slightly nitpicky but the actual maximum value of any <code>enum</code> is <code>Int32.MaxValue</code> (assuming it's a <code>enum</code> derived from <code>int</code>). It's perfectly legal to cast any <code>Int32</code> value to an any <code>enum</code> regardless of whether or not it actually declared a member with that value. </p>\n\n<p>Legal:</p>\n\n<pre><code>enum SomeEnum\n{\n Fizz = 42\n}\n\npublic static void SomeFunc()\n{\n SomeEnum e = (SomeEnum)5;\n}\n</code></pre>\n" }, { "answer_id": 1303417, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 5, "selected": false, "text": "<p>According to Matt Hamilton's answer, I thought on creating an Extension method for it.</p>\n\n<p>Since <code>ValueType</code> is not accepted as a generic type parameter constraint, I didn't find a better way to restrict <code>T</code> to <code>Enum</code> but the following.</p>\n\n<p>Any ideas would be really appreciated.</p>\n\n<p>PS. please ignore my VB implicitness, I love using VB in this way, that's the strength of VB and that's why I love VB.</p>\n\n<p>Howeva, here it is:</p>\n\n<h2>C#:</h2>\n\n<pre><code>static void Main(string[] args)\n{\n MyEnum x = GetMaxValue&lt;MyEnum&gt;(); //In newer versions of C# (7.3+)\n MyEnum y = GetMaxValueOld&lt;MyEnum&gt;(); \n}\n\npublic static TEnum GetMaxValue&lt;TEnum&gt;()\n where TEnum : Enum\n{\n return Enum.GetValues(typeof(TEnum)).Cast&lt;TEnum&gt;().Max();\n}\n\n//When C# version is smaller than 7.3, use this:\npublic static TEnum GetMaxValueOld&lt;TEnum&gt;()\n where TEnum : IComparable, IConvertible, IFormattable\n{\n Type type = typeof(TEnum);\n\n if (!type.IsSubclassOf(typeof(Enum)))\n throw new\n InvalidCastException\n (\"Cannot cast '\" + type.FullName + \"' to System.Enum.\");\n\n return (TEnum)Enum.ToObject(type, Enum.GetValues(type).Cast&lt;int&gt;().Last());\n}\n\n\n\nenum MyEnum\n{\n ValueOne,\n ValueTwo\n}\n</code></pre>\n\n<h2>VB:</h2>\n\n<pre><code>Public Function GetMaxValue _\n (Of TEnum As {IComparable, IConvertible, IFormattable})() As TEnum\n\n Dim type = GetType(TEnum)\n\n If Not type.IsSubclassOf(GetType([Enum])) Then _\n Throw New InvalidCastException _\n (\"Cannot cast '\" &amp; type.FullName &amp; \"' to System.Enum.\")\n\n Return [Enum].ToObject(type, [Enum].GetValues(type) _\n .Cast(Of Integer).Last)\nEnd Function\n</code></pre>\n" }, { "answer_id": 1376406, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>There are methods for getting information about enumerated types under System.Enum.</p>\n\n<p>So, in a VB.Net project in Visual Studio I can type \"System.Enum.\" and the intellisense brings up all sorts of goodness.</p>\n\n<p>One method in particular is System.Enum.GetValues(), which returns an array of the enumerated values. Once you've got the array, you should be able to do whatever is appropriate for your particular circumstances.</p>\n\n<p>In my case, my enumerated values started at zero and skipped no numbers, so to get the max value for my enum I just need to know how many elements were in the array.</p>\n\n<p>VB.Net code snippets:</p>\n\n<pre><code>'''''''\n\nEnum MattType\n zerothValue = 0\n firstValue = 1\n secondValue = 2\n thirdValue = 3\nEnd Enum\n\n'''''''\n\nDim iMax As Integer\n\niMax = System.Enum.GetValues(GetType(MattType)).GetUpperBound(0)\n\nMessageBox.Show(iMax.ToString, \"Max MattType Enum Value\")\n\n'''''''\n</code></pre>\n" }, { "answer_id": 1665787, "author": "Eric Feng", "author_id": 201457, "author_profile": "https://Stackoverflow.com/users/201457", "pm_score": 3, "selected": false, "text": "<p>Use the Last function could not get the max value. Use the \"max\" function could. Like:</p>\n\n<pre><code> class Program\n {\n enum enum1 { one, two, second, third };\n enum enum2 { s1 = 10, s2 = 8, s3, s4 };\n enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };\n\n static void Main(string[] args)\n {\n TestMaxEnumValue(typeof(enum1));\n TestMaxEnumValue(typeof(enum2));\n TestMaxEnumValue(typeof(enum3));\n }\n\n static void TestMaxEnumValue(Type enumType)\n {\n Enum.GetValues(enumType).Cast&lt;Int32&gt;().ToList().ForEach(item =&gt;\n Console.WriteLine(item.ToString()));\n\n int maxValue = Enum.GetValues(enumType).Cast&lt;int&gt;().Max(); \n Console.WriteLine(\"The max value of {0} is {1}\", enumType.Name, maxValue);\n }\n }\n</code></pre>\n" }, { "answer_id": 1665930, "author": "Eric Feng", "author_id": 201457, "author_profile": "https://Stackoverflow.com/users/201457", "pm_score": 3, "selected": false, "text": "<p>After tried another time, I got this extension method:</p>\n\n<pre><code>public static class EnumExtension\n{\n public static int Max(this Enum enumType)\n { \n return Enum.GetValues(enumType.GetType()).Cast&lt;int&gt;().Max(); \n }\n}\n\nclass Program\n{\n enum enum1 { one, two, second, third };\n enum enum2 { s1 = 10, s2 = 8, s3, s4 };\n enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };\n\n static void Main(string[] args)\n {\n Console.WriteLine(enum1.one.Max()); \n }\n}\n</code></pre>\n" }, { "answer_id": 2320749, "author": "Engineer", "author_id": 279738, "author_profile": "https://Stackoverflow.com/users/279738", "pm_score": 2, "selected": false, "text": "<p>In agreement with Matthew J Sullivan, for C#:</p>\n\n<pre><code> Enum.GetValues(typeof(MyEnum)).GetUpperBound(0);\n</code></pre>\n\n<p>I'm really not sure why anyone would want to use:</p>\n\n<pre><code> Enum.GetValues(typeof(MyEnum)).Cast&lt;MyEnum&gt;().Last();\n</code></pre>\n\n<p>...As word-for-word, semantically speaking, it doesn't seem to make as much sense? (always good to have different ways, but I don't see the benefit in the latter.)</p>\n" }, { "answer_id": 7130448, "author": "Stephen Hosking", "author_id": 114044, "author_profile": "https://Stackoverflow.com/users/114044", "pm_score": 1, "selected": false, "text": "<p>In F#, with a helper function to convert the enum to a sequence:</p>\n\n<pre><code>type Foo =\n | Fizz = 3\n | Bang = 2\n\n// Helper function to convert enum to a sequence. This is also useful for iterating.\n// stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values-c\nlet ToSeq (a : 'A when 'A : enum&lt;'B&gt;) =\n Enum.GetValues(typeof&lt;'A&gt;).Cast&lt;'B&gt;()\n\n// Get the max of Foo\nlet FooMax = ToSeq (Foo()) |&gt; Seq.max \n</code></pre>\n\n<p>Running it...</p>\n\n<pre>\n> type Foo = | Fizz = 3 | Bang = 2\n> val ToSeq : 'A -> seq&lt;'B> when 'A : enum&lt;'B>\n> val FooMax : Foo = Fizz\n</pre>\n\n<p>The <code>when 'A : enum&lt;'B&gt;</code> is not required by the compiler for the definition, but is required for any use of ToSeq, even by a valid enum type.</p>\n" }, { "answer_id": 17618529, "author": "Karanvir Kang", "author_id": 1563840, "author_profile": "https://Stackoverflow.com/users/1563840", "pm_score": 6, "selected": false, "text": "<p>I agree with Matt's answer. If you need just min and max int values, then you can do it as follows.</p>\n\n<p><strong>Maximum:</strong></p>\n\n<pre><code>Enum.GetValues(typeof(Foo)).Cast&lt;int&gt;().Max();\n</code></pre>\n\n<p><strong>Minimum:</strong></p>\n\n<pre><code>Enum.GetValues(typeof(Foo)).Cast&lt;int&gt;().Min();\n</code></pre>\n" }, { "answer_id": 54275613, "author": "yvan vander sanden", "author_id": 2227654, "author_profile": "https://Stackoverflow.com/users/2227654", "pm_score": 1, "selected": false, "text": "<p>It is not usable in all circumstances, but I often define the max value myself:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>enum Values {\n one,\n two,\n tree,\n End,\n}\n\nfor (Values i = 0; i &lt; Values.End; i++) {\n Console.WriteLine(i);\n}\n\nvar random = new Random();\nConsole.WriteLine(random.Next((int)Values.End));\n</code></pre>\n\n<p>Of course this won't work when you use custom values in an enum, but often it can be an easy solution.</p>\n" }, { "answer_id": 58610374, "author": "XLars", "author_id": 2989400, "author_profile": "https://Stackoverflow.com/users/2989400", "pm_score": 2, "selected": false, "text": "<p>I used the following when I needed the min and max values of my enum.\nI just set a min equal to the lowest value of the enumeration and a max equal to the highest value in the enumeration as enum values themselves.</p>\n\n<pre><code>public enum ChannelMessageTypes : byte\n{\n Min = 0x80, // Or could be: Min = NoteOff\n NoteOff = 0x80,\n NoteOn = 0x90,\n PolyKeyPressure = 0xA0,\n ControlChange = 0xB0,\n ProgramChange = 0xC0,\n ChannelAfterTouch = 0xD0,\n PitchBend = 0xE0,\n Max = 0xE0 // Or could be: Max = PitchBend\n}\n\n// I use it like this to check if a ... is a channel message.\nif(... &gt;= ChannelMessageTypes.Min || ... &lt;= ChannelMessages.Max)\n{\n Console.WriteLine(\"Channel message received!\");\n}\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438/" ]
How do you get the max value of an enum?
Enum.GetValues() seems to return the values in order, so you can do something like this: ``` // given this enum: public enum Foo { Fizz = 3, Bar = 1, Bang = 2 } // this gets Fizz var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Last(); ``` **Edit** For those not willing to read through the comments: You can also do it this way: ``` var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max(); ``` ... which will work when some of your enum values are negative.
203,383
<p>I get obsessed with the best names for arrays and variables that I use, I'll look up words in the thesaurus, dictionary, etc..</p> <p>So I'm trying to name this array / structure:</p> <pre><code>$nameMe = array( '392' =&gt; TRUE, '234' =&gt; TRUE, '754' =&gt; TRUE, '464' =&gt; TRUE, ); </code></pre> <p>and it's used to check if that id has a certain property, like so</p> <pre><code>if(isset($name[$id])) { doSomething(); } </code></pre> <p>Problem being I'm getting really long variable names like</p> <pre><code>$propertyNameArrayIdIndexed </code></pre> <p>Any ideas for how I can better name this particular function of array? or better names in general</p>
[ { "answer_id": 203395, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>propertyNameable, IspropertyNameable.</p>\n" }, { "answer_id": 203401, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<p>Nothing wrong with long variable names, as long as they describe what the variable is doing, rather than how it's declared or defined.</p>\n" }, { "answer_id": 203409, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>I would drop \"Array\" from variable names.</p>\n\n<p>A function that used the array may be named something like:</p>\n\n<p>IsPropertyAvailable?($id)</p>\n\n<p>or just</p>\n\n<p>IsAvailable?($id)</p>\n\n<p>when properly encapsulated.</p>\n\n<p>So the associated data structure for querying could be named</p>\n\n<p>$availableIds</p>\n" }, { "answer_id": 203413, "author": "Bill Forster", "author_id": 3955, "author_profile": "https://Stackoverflow.com/users/3955", "pm_score": 1, "selected": false, "text": "<p>You want your code to read as much like plain English as possible. In plain English you'd end up with something like;</p>\n\n<p>If the car is red\n Do the red car stuff</p>\n\n<p>So my recommendation is to avoid introducing unnecessary computerese ('array', 'property', 'index' etc.) into the naming of the variable. Your programming language is imposing \"isset\" on you. That's fine, that makes it clear that you have an array of booleans and means you can simply say;</p>\n\n<p>if( isset(red[car_idx]) )\n dosomething();</p>\n\n<p>Summary: I think the array should be named simply as the property you are trying to test for. If the name of the property is a nice English language adjective that either applies to a noun or not, the boolean nature of the array is apparent even without isset(). So simply;</p>\n\n<p>Red[], Oblong[], Large[]</p>\n\n<p>Not IsRed[], IsOblong[], IsLarge[] because the extra \"Is\" in addition to the one in isset() is redundant.</p>\n" }, { "answer_id": 203414, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 3, "selected": true, "text": "<pre><code>$hasProperty[$id]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$isSomething[$id]\n</code></pre>\n\n<p>What is the property exactly?</p>\n\n<pre><code>$isOdd[$id]\n$isWriteable[$id]\n$hasAssociatedFile[$id]\n</code></pre>\n" }, { "answer_id": 203424, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>is your array only going to contain <code>true</code>? If so, I'd say change your data structure to something like this:</p>\n\n<pre><code>$availableIds = array(392, 234, 754, 464);\n</code></pre>\n\n<p>and then your <code>if</code> statements are much more meaningful:</p>\n\n<pre><code>if (in_array($myId, $availableIds)) { ... }\n</code></pre>\n" }, { "answer_id": 203452, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 1, "selected": false, "text": "<p>Name variables by their \"role\" (in the UML sense) not their type. So, the proper name for the variable should depend very much on where and how its used. Simply knowing the type of data structure is not enough to give it an apt name. So, say that you have an enumeration of properties, each of which might be renderable as an icon. I'd leave out any indication of type, and declare it something like <code>Set&lt;Property&gt; displayableIcons</code>.</p>\n\n<p>Even if you are using Hungarian notation, the actual type shouldn't be part of the name, but some type-qualifier or indication of an informal sub-type would be alright, like <code>String b64JpgMugshot</code>.</p>\n" }, { "answer_id": 203471, "author": "Jon Davis", "author_id": 11398, "author_profile": "https://Stackoverflow.com/users/11398", "pm_score": 0, "selected": false, "text": "<p>I just use dah[].</p>\n" }, { "answer_id": 203486, "author": "Lara Dougan", "author_id": 4081, "author_profile": "https://Stackoverflow.com/users/4081", "pm_score": 0, "selected": false, "text": "<p>I would agree with other commenters that the question seems to lack proper context for proper concise naming, but something generic like able['foo'], enabled['bar'] or ready['ack'] may work.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
I get obsessed with the best names for arrays and variables that I use, I'll look up words in the thesaurus, dictionary, etc.. So I'm trying to name this array / structure: ``` $nameMe = array( '392' => TRUE, '234' => TRUE, '754' => TRUE, '464' => TRUE, ); ``` and it's used to check if that id has a certain property, like so ``` if(isset($name[$id])) { doSomething(); } ``` Problem being I'm getting really long variable names like ``` $propertyNameArrayIdIndexed ``` Any ideas for how I can better name this particular function of array? or better names in general
``` $hasProperty[$id] ``` or ``` $isSomething[$id] ``` What is the property exactly? ``` $isOdd[$id] $isWriteable[$id] $hasAssociatedFile[$id] ```
203,384
<p>Various programs can do stuff only when you haven't used the computer for a while (eg screensaver, Google Desktop indexing, etc).</p> <p>How do they know when it has been inactive? Is there some function in Windows that tells you how long it has been inactive, or do you have to use some kind of keyboard/mouse hook to track activity yourself?</p> <p>I'm using C#, but I'm interested in any method of determining the inactivity.</p>
[ { "answer_id": 203404, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://dataerror.blogspot.com/2005/02/detect-windows-idle-time.html\" rel=\"noreferrer\">Google is your friend</a></p>\n\n<p>Basically uses <a href=\"http://msdn.microsoft.com/en-us/library/ms646302.aspx\" rel=\"noreferrer\">this.</a><br>\ndon't forget to fully ready the documentation before using.</p>\n" }, { "answer_id": 203410, "author": "Bill", "author_id": 14547, "author_profile": "https://Stackoverflow.com/users/14547", "pm_score": 0, "selected": false, "text": "<p>The keyboard and mouse hooks are what I find to be most valuable. The class below can be inserted and you just have to figure out what you want to do with the information about key and mouse updates. </p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace Example {\n\n public class Hook {\n\n delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);\n\n [FlagsAttribute]\n public enum WindowMessage {\n WM_KEYDOWN = 0x0000000000000100, // &amp;H100\n WM_MOUSEMOVE = 0x0000000000000200, // &amp;H200\n WM_LBUTTONDOWN = 0x0000000000000201, // &amp;H201\n WM_RBUTTONDOWN = 0x0000000000000204, // &amp;H204\n WH_KEYBOARD = 2,\n WH_MOUSE = 7,\n HC_ACTION = 0\n }\n\n [DllImport(\"user32.dll\",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]\n private static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"user32.dll\",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]\n private static extern bool UnhookWindowsHookEx(int idHook);\n\n [DllImport(\"user32.dll\",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]\n private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);\n\n //Declare MouseHookProcedure as a HookProc type.\n static HookProc MouseHookProcedure;\n static HookProc KeyboardHookProcedure;\n\n private static int mhMouseHook = 0;\n private static int mhKeyboardHook = 0;\n\n public Hook() {}\n\n public static void Init() {\n MouseHookProcedure = new HookProc( MouseHookProc );\n KeyboardHookProcedure = new HookProc( KeyboardHookProc );\n mhMouseHook = SetWindowsHookEx( (int)WindowMessage.WH_MOUSE, MouseHookProcedure, (IntPtr)0, AppDomain.GetCurrentThreadId() );\n mhKeyboardHook = SetWindowsHookEx( (int)WindowMessage.WH_KEYBOARD, KeyboardHookProcedure, (IntPtr)0, AppDomain.GetCurrentThreadId() );\n }\n\n public static void Terminate() {\n UnhookWindowsHookEx( mhMouseHook );\n UnhookWindowsHookEx( mhKeyboardHook );\n }\n\n private static int MouseHookProc( int nCode, IntPtr wParam, IntPtr lParam ) {\n if ( nCode &gt;= 0 ) {\n //do something here to update the last activity point, i.e. a keystroke was detected so reset our idle timer.\n }\n return CallNextHookEx( mhMouseHook, nCode, wParam, lParam );\n }\n\n private static int KeyboardHookProc( int nCode, IntPtr wParam, IntPtr lParam ) {\n if ( nCode &gt;= 0 ) {\n //do something here to update the last activity point, i.e. a mouse action was detected so reset our idle timer.\n }\n return CallNextHookEx( mhKeyboardHook, nCode, wParam, lParam );\n }\n\n }\n}\n</code></pre>\n\n<p>Of course this only works within the application you are hooking. If you need to track inactivity across the entire system, you need to create a DLL that can be loaded into the address spaces of all other windows. Unfortunately, I haven't heard of any hack that would allow a .net compiled .dll that will work in this scenario; we have a C++ DLL that hooks for this purpose.</p>\n" }, { "answer_id": 203420, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": true, "text": "<p>EDIT: changed answer, providing text and detail behind Shy's answer (which should be and was accepted). Feel free to merge and delete this one.</p>\n\n<p><a href=\"http://pinvoke.net/default.aspx/user32/GetLastInputInfo.html\" rel=\"nofollow noreferrer\">GetLastInputInfo</a> Function\nThe GetLastInputInfo function retrieves the time of the last input event.</p>\n\n<p>Pasted here from P/Invoke</p>\n\n<p>This function retrieves the time since last user input</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nstatic extern bool GetLastInputInfo(ref LASTINPUTINFO plii);\n\nstatic int GetLastInputTime()\n{\n int idleTime = 0;\n LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();\n lastInputInfo.cbSize = Marshal.SizeOf( lastInputInfo );\n lastInputInfo.dwTime = 0;\n\n int envTicks = Environment.TickCount;\n\n if( GetLastInputInfo( ref lastInputInfo ) )\n {\n int lastInputTick = lastInputInfo.dwTime;\n\n idleTime = envTicks - lastInputTick;\n }\n\n return (( idleTime &gt; 0 ) ? ( idleTime / 1000 ) : idleTime );\n}\n\n[StructLayout( LayoutKind.Sequential )]\nstruct LASTINPUTINFO\n{\n public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));\n\n [MarshalAs(UnmanagedType.U4)]\n public int cbSize; \n [MarshalAs(UnmanagedType.U4)]\n public UInt32 dwTime;\n}\n</code></pre>\n\n<p><strike>\nFWIW:\nI implemented a global keyboard and mouse hook during AnAppADay. See this app for the source - it's pretty close to what you want. The classes you'll want are in the AnAppADay.Utils namespace.\n</strike> [scratched due to linkrot]</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4495/" ]
Various programs can do stuff only when you haven't used the computer for a while (eg screensaver, Google Desktop indexing, etc). How do they know when it has been inactive? Is there some function in Windows that tells you how long it has been inactive, or do you have to use some kind of keyboard/mouse hook to track activity yourself? I'm using C#, but I'm interested in any method of determining the inactivity.
EDIT: changed answer, providing text and detail behind Shy's answer (which should be and was accepted). Feel free to merge and delete this one. [GetLastInputInfo](http://pinvoke.net/default.aspx/user32/GetLastInputInfo.html) Function The GetLastInputInfo function retrieves the time of the last input event. Pasted here from P/Invoke This function retrieves the time since last user input ``` [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); static int GetLastInputTime() { int idleTime = 0; LASTINPUTINFO lastInputInfo = new LASTINPUTINFO(); lastInputInfo.cbSize = Marshal.SizeOf( lastInputInfo ); lastInputInfo.dwTime = 0; int envTicks = Environment.TickCount; if( GetLastInputInfo( ref lastInputInfo ) ) { int lastInputTick = lastInputInfo.dwTime; idleTime = envTicks - lastInputTick; } return (( idleTime > 0 ) ? ( idleTime / 1000 ) : idleTime ); } [StructLayout( LayoutKind.Sequential )] struct LASTINPUTINFO { public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO)); [MarshalAs(UnmanagedType.U4)] public int cbSize; [MarshalAs(UnmanagedType.U4)] public UInt32 dwTime; } ``` FWIW: I implemented a global keyboard and mouse hook during AnAppADay. See this app for the source - it's pretty close to what you want. The classes you'll want are in the AnAppADay.Utils namespace. [scratched due to linkrot]
203,397
<p>Is there a way to change the context sensitive help in Visual Studio so that it will only search against the text under the caret instead of a compilation error in your code?</p> <p>More info: After you compile and receive a compilation error(underlined), placing the caret within the underlined text and pressing <kbd>F1</kbd> will take you to the Compilation error page instead of the help for the function under the caret. Can this behavior be changed to always go to the method/keyword help?</p> <p>Language: C#</p>
[ { "answer_id": 203436, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 0, "selected": false, "text": "<p>If I remember, after you compile, the default selected window is the message (error list) one. If you hit <kbd>F1</kbd> at this point, you will get help on the error message. But if you select the code window, you will get the help on the selected text.</p>\n<p>Is this the behavior your are experiencing???</p>\n" }, { "answer_id": 211389, "author": "Robin Bennett", "author_id": 27794, "author_profile": "https://Stackoverflow.com/users/27794", "pm_score": 3, "selected": true, "text": "<p>The only solution I've found is to fix the compile error ;-)</p>\n<p>A workaround is to <strong>use the 'Dynamic Help' window</strong> (from the help menu, or <kbd>CTRL</kbd>-<kbd>F1</kbd>, <kbd>D</kbd>), the compile error is top of the list but the usual item will be listed next.</p>\n<p>For those that don't understand the question, here's a trivial, unrealistic example:</p>\n<pre><code>int myInt = new int(3);\n</code></pre>\n<p>As soon as you move off the line, the 'new int(3);' bit is underlined in red, but if you select the second 'int' and press <kbd>F1</kbd>, you get help on declaring integers.</p>\n<p>However if you compile it, the offending section is underlined with a wiggly blue line and selecting 'int' and pressing <kbd>F1</kbd> takes you to help on the compile error. It's not just a case of the focus moving to the Error List window.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
Is there a way to change the context sensitive help in Visual Studio so that it will only search against the text under the caret instead of a compilation error in your code? More info: After you compile and receive a compilation error(underlined), placing the caret within the underlined text and pressing `F1` will take you to the Compilation error page instead of the help for the function under the caret. Can this behavior be changed to always go to the method/keyword help? Language: C#
The only solution I've found is to fix the compile error ;-) A workaround is to **use the 'Dynamic Help' window** (from the help menu, or `CTRL`-`F1`, `D`), the compile error is top of the list but the usual item will be listed next. For those that don't understand the question, here's a trivial, unrealistic example: ``` int myInt = new int(3); ``` As soon as you move off the line, the 'new int(3);' bit is underlined in red, but if you select the second 'int' and press `F1`, you get help on declaring integers. However if you compile it, the offending section is underlined with a wiggly blue line and selecting 'int' and pressing `F1` takes you to help on the compile error. It's not just a case of the focus moving to the Error List window.
203,399
<p>I'm running a MySQL database locally for development, but deploying to Heroku which uses Postgres. Heroku handles almost everything, but my case-insensitive Like statements become case sensitive. I could use iLike statements, but my local MySQL database can't handle that.</p> <p>What is the best way to write a case insensitive query that is compatible with both MySQL and Postgres? Or do I need to write separate Like and iLike statements depending on the DB my app is talking to?</p>
[ { "answer_id": 203419, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 7, "selected": true, "text": "<pre><code>select * from foo where upper(bar) = upper(?);\n</code></pre>\n\n<p>If you set the parameter to upper case in the caller, you can avoid the second function call.</p>\n" }, { "answer_id": 203428, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": false, "text": "<p>In postgres, you can do this:</p>\n\n<pre><code>SELECT whatever FROM mytable WHERE something ILIKE 'match this';\n</code></pre>\n\n<p>I'm not sure if there is an equivalent for MySQL but you can always do this which is a bit ugly but should work in both MySQL and postgres:</p>\n\n<pre><code>SELECT whatever FROM mytable WHERE UPPER(something) = UPPER('match this');\n</code></pre>\n" }, { "answer_id": 615922, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Converting to upper is best as it covers compatible syntax for the 3 most-used Rails database backends. PostgreSQL, MySQL and SQLite all support this syntax. It has the (minor) drawback that you have to uppercase your search string in your application or in your conditions string, making it a bit uglier, but I think the compatibility you gain makes it worthwile.</p>\n\n<p>Both MySQL and SQLite3 have a case-insensitive LIKE operator. Only PostgreSQL has a case-sensitive LIKE operator and a PostgreSQL-specific (per the manual) ILIKE operator for case-insensitive searches. You might specify ILIKE insead of LIKE in your conditions on the Rails application, but be aware that the application will cease to work under MySQL or SQLite.</p>\n\n<p>A third option might be to check which database engine you're using and modify the search string accordingly. This might be better done by hacking into / monkeypatching ActiveRecord's connection adapters and have the PostgreSQL adapter modify the query string to substitute \"LIKE\" for \"ILIKE\" prior to query execution. This solution is however the most convoluted and in light of easier ways like uppercasing both terms, I think this is not worh the effort (although you'd get plenty of brownie points for doing it this way).</p>\n" }, { "answer_id": 1550846, "author": "Trevor Turk", "author_id": 45197, "author_profile": "https://Stackoverflow.com/users/45197", "pm_score": 1, "selected": false, "text": "<p>You might also consider checking out the <a href=\"http://github.com/binarylogic/searchlogic\" rel=\"nofollow noreferrer\">searchlogic</a> plugin, which does the <a href=\"http://github.com/binarylogic/searchlogic/blob/master/lib/searchlogic/named_scopes/conditions.rb#L89\" rel=\"nofollow noreferrer\">LIKE/ILIKE</a> switch for you. </p>\n" }, { "answer_id": 1550860, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 6, "selected": false, "text": "<p>The moral of this story is: Don't use a different software stack for development and production. Never.</p>\n\n<p>You'll just end up with bugs which you can't reproduce in dev; your testing will be worthless. Just don't do it.</p>\n\n<p>Using a different database engine is out of the question - there will be FAR more cases where it behaves differently than just LIKE (also, have you checked the collations in use by the databases? Are they identical in EVERY CASE? If not, you can forget ORDER BY on varchar columns working the same)</p>\n" }, { "answer_id": 2388195, "author": "MkV", "author_id": 46235, "author_profile": "https://Stackoverflow.com/users/46235", "pm_score": 2, "selected": false, "text": "<p>If you're using PostgreSQL 8.4 you can use the <a href=\"http://developer.postgresql.org/pgdocs/postgres/citext.html\" rel=\"nofollow noreferrer\">citext</a> module to create case insensitive text fields.</p>\n" }, { "answer_id": 4664415, "author": "Sheldon Ross", "author_id": 60789, "author_profile": "https://Stackoverflow.com/users/60789", "pm_score": 1, "selected": false, "text": "<p>You can also use ~* in postgres if you want to match a substring within a block. ~ matches case-sensitive substring, ~* case insensitive substring. Its a slow operation, but might I find it useful for searches.</p>\n\n<pre><code>Select * from table where column ~* 'UnEvEn TeXt';\nSelect * from table where column ~ 'Uneven text';\n</code></pre>\n\n<p>Both would hit on \"Some Uneven text here\"\nOnly the former would hit on \"Some UNEVEN TEXT here\"</p>\n" }, { "answer_id": 10149458, "author": "jswanner", "author_id": 542478, "author_profile": "https://Stackoverflow.com/users/542478", "pm_score": 5, "selected": false, "text": "<p>Use Arel:</p>\n\n<pre><code>Author.where(Author.arel_table[:name].matches(\"%foo%\"))\n</code></pre>\n\n<p><code>matches</code> will use the <code>ILIKE</code> operator for Postgres, and <code>LIKE</code> for everything else.</p>\n" }, { "answer_id": 10353607, "author": "RuelB", "author_id": 1361487, "author_profile": "https://Stackoverflow.com/users/1361487", "pm_score": 2, "selected": false, "text": "<p>use COLLATE.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html</a></p>\n" }, { "answer_id": 11119331, "author": "tims", "author_id": 651443, "author_profile": "https://Stackoverflow.com/users/651443", "pm_score": 3, "selected": false, "text": "<p>There are several answers, none of which are very satisfactory.</p>\n\n<ul>\n<li><strong>LOWER(bar) = LOWER(?)</strong> will <em>work</em> on MySQL and Postgres, but is likely to <em>perform terribly on MySQL</em>: MySQL won't use its indexes because of the LOWER function. On Postgres you can add a functional index (on <strong>LOWER(bar)</strong>) but MySQL doesn't support this.</li>\n<li>MySQL will (unless you have set a case-sensitive <a href=\"http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html\">collation</a>) do case-insensitive matching automatically, and use its indexes. (<strong>bar = ?</strong>).</li>\n<li>From your code outside the database, maintain <strong>bar</strong> and <strong>bar_lower</strong> fields, where bar_lower contains the result of <strong>lower(bar)</strong>. (This may be possible using database triggers, also). (See a discussion of this solution on <a href=\"http://drupal.org/node/83738\">Drupal</a>). This is clumsy but does at least run the same way on pretty much every database.</li>\n</ul>\n" }, { "answer_id": 11749968, "author": "Ben Wilhelm", "author_id": 1461460, "author_profile": "https://Stackoverflow.com/users/1461460", "pm_score": 3, "selected": false, "text": "<p>REGEXP is case insensitive (unless used with BINARY), and can be used, like so...</p>\n\n<pre><code> SELECT id FROM person WHERE name REGEXP 'john';\n</code></pre>\n\n<p>...to match 'John', 'JOHN', 'john', etc.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23885/" ]
I'm running a MySQL database locally for development, but deploying to Heroku which uses Postgres. Heroku handles almost everything, but my case-insensitive Like statements become case sensitive. I could use iLike statements, but my local MySQL database can't handle that. What is the best way to write a case insensitive query that is compatible with both MySQL and Postgres? Or do I need to write separate Like and iLike statements depending on the DB my app is talking to?
``` select * from foo where upper(bar) = upper(?); ``` If you set the parameter to upper case in the caller, you can avoid the second function call.
203,425
<p>What's the ASP equivalent to PHP's <code>.=</code> when concatenating strings? I'm referring to asp NOT asp.net.</p> <p>I meant to specify that I'm in a for-loop. So I want to know the equivalent for <code>.=</code> (in php) not standard concatenation.</p> <p><em>Example:</em></p> <pre><code>For Each Item In Request.Form If (Item = "service") then For x=1 To Request.Form(item).Count service = "&amp;service="&amp;Request.Form(Item)(x) Next End If Next </code></pre>
[ { "answer_id": 203429, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": false, "text": "<p>In VBScript:</p>\n\n<pre><code>Variable = Variable &amp; \"something more\"\n</code></pre>\n\n<p>In JScript I believe you can use:</p>\n\n<pre><code>variable += \"something more\";\n</code></pre>\n\n<p>Specifically:</p>\n\n<pre><code>service = service &amp; \"&amp;service=\" &amp; Request.Form(Item)(x)\n</code></pre>\n\n<p>assuming you want your result to look something like...</p>\n\n<pre><code>&amp;service=blah1&amp;service=blah2&amp;service=blah3\n</code></pre>\n\n<p>Though you may need to URL encode your Request.Form(Item)(x) values because any \"&amp;\" (and other characters) could really muck up what you are trying to do. Also be careful when using unsanitized input like this directly from an HTML form, its very dangerous.</p>\n" }, { "answer_id": 203435, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": -1, "selected": false, "text": "<p>I can't remember for certain, but &amp;= should work in ASP. I know it works in VB.Net. Although I can't recall if that worked in asp. If that doesn't work, the only solution is a = a &amp; b.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What's the ASP equivalent to PHP's `.=` when concatenating strings? I'm referring to asp NOT asp.net. I meant to specify that I'm in a for-loop. So I want to know the equivalent for `.=` (in php) not standard concatenation. *Example:* ``` For Each Item In Request.Form If (Item = "service") then For x=1 To Request.Form(item).Count service = "&service="&Request.Form(Item)(x) Next End If Next ```
In VBScript: ``` Variable = Variable & "something more" ``` In JScript I believe you can use: ``` variable += "something more"; ``` Specifically: ``` service = service & "&service=" & Request.Form(Item)(x) ``` assuming you want your result to look something like... ``` &service=blah1&service=blah2&service=blah3 ``` Though you may need to URL encode your Request.Form(Item)(x) values because any "&" (and other characters) could really muck up what you are trying to do. Also be careful when using unsanitized input like this directly from an HTML form, its very dangerous.
203,442
<p>Hey All, I have been working on this problem for a while and the usual google searches are not helping :(</p> <p>I have a production database in SQL 2000. I want to copy it over the top of a training database to refresh it. I want this to be something that is scheduled to happen once a week to keep the training database up-to-date.</p> <p>I have a DTS job created for doing this. Within that DTS job I have a single "Copy SQL Server Objects" task. That task is set up to:</p> <ul> <li>Create all copied objects <ul> <li>Drop destination objects first</li> </ul></li> <li>Copy data <ul> <li>Replace existing data</li> </ul></li> <li>Copy indexes, triggers, primary and foreign keys</li> <li>Copy all user tables, views, functions and stored procedures.</li> </ul> <p>When I run this DTS package (in pre-production for testing of course) it gets to 99% done and throws the following error:</p> <pre><code>Step Error Source: Microsoft SQL-DMO (ODBC SQLState: 42S02) Step Error Description:[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'dbo.vwEstAssetStationAddress'. Step Error code: 800400D0 Step Error Help File:SQLDMO80.hlp Step Error Help Context ID:1131 </code></pre> <p>My searches on the net didn't provide much help. There are reports of these errors getting hit, but none seem to match my circumstances. One suggestion I found was the the sysdepends table had become corrupted, making the DTS job run its scripts in the wrong order. Howeever, I ran the following script to correct that table and it still throws the same error:</p> <pre><code>USE master GO ALTER DATABASE [DATABASE NAME] SET SINGLE_USER GO USE [DATABASE NAME] GO DBCC CHECKTABLE('sysdepends',REPAIR_REBUILD ) GO USE master GO ALTER DATABASE [DATABASE NAME] SET MULTI_USER GO </code></pre> <p>I have also seen that having different object owners can cause this error. But I have confirmed that the objects are all owned by the dbo user in this case.</p> <p>Any suggestions?</p>
[ { "answer_id": 203482, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 0, "selected": false, "text": "<p>Somehow the dbo.vwEstAssetStationAddress table is not being found by your DTS package. Unfortunately, the message doesn't say if it was on the source or destination that it couldn't find it.</p>\n\n<p>What are the exact steps, in the order that you have them in your DTS package? I'm assuming that the list of the task items above is not in order. I know this not an answer, but it looks like we are going to need a bit more information to help you further.</p>\n" }, { "answer_id": 203503, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "<p>Thanks for the response hectorsosajr.</p>\n\n<p>the object aparrently causing the error (dbo.vwEstAssetStationAddress) is a view that references 2 underlying tables. I have tested querying the view, as well as running the SELECT statement that defines it, on both the source and destination databases and it works fine.</p>\n\n<p>The database object copy task in DTS doesn't allow you to specify the order it transfers things in. As far as I understand it, it uses the sysdepends table to determine the requisite order of events.</p>\n" }, { "answer_id": 203554, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>Sounds like it is trying to create a stored procedure/view based on a view that doesn't yet exist.</p>\n<p>Why not just backup and restore the database under a different name? (if it wasn't production, I would say detach, copy and re-attach). You can do all that under the control of T-SQL.</p>\n<p>See if <a href=\"https://sqlblog.org/2008/09/09/keeping-sysdepends-up-to-date-in-sql-server-2008\" rel=\"nofollow noreferrer\">this link</a> helps you find your dependency issue.</p>\n" }, { "answer_id": 203570, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "<p>I was trying to avoid doing it via backup / restore. There are some users of the database that are SQL Server accounts (not Active Directory). This becomes a pain in the but if you need to do it from one server to another as you have to drop those users and recreate them.</p>\n" }, { "answer_id": 203668, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "<p>I've run another test to try and isolate this. I removed the mentioned view from the destination database totally, then ran the DTS again. It failed with the same error. However, the view that aparrently is an invalid object name was recreated successfully. It seems that the error is coming from something trying to reference that view, but it doesn't actually stop the script when it hits that error.</p>\n\n<p>Cade - I will check out that link. I will also try and establish what is referencing the view and breaking.</p>\n" }, { "answer_id": 203697, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 2, "selected": false, "text": "<p>I feel stupid, but am posting the answer I just found for posterity (and so all you helpful fellows can stop stressing on my behalf.</p>\n\n<p>Even though I had selected all the user tables, views, stored procedures and user defined functions to copy, I hadn't selected \"Include all dependant objects\". I had assumed that if you selected two objects to copy, and one was dependant on the other, SQL would always do them in the correct order. Aparrently not. Selecting this little check box made all the difference.</p>\n\n<p>Thanks again to those who helped with suggestions</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6014/" ]
Hey All, I have been working on this problem for a while and the usual google searches are not helping :( I have a production database in SQL 2000. I want to copy it over the top of a training database to refresh it. I want this to be something that is scheduled to happen once a week to keep the training database up-to-date. I have a DTS job created for doing this. Within that DTS job I have a single "Copy SQL Server Objects" task. That task is set up to: * Create all copied objects + Drop destination objects first * Copy data + Replace existing data * Copy indexes, triggers, primary and foreign keys * Copy all user tables, views, functions and stored procedures. When I run this DTS package (in pre-production for testing of course) it gets to 99% done and throws the following error: ``` Step Error Source: Microsoft SQL-DMO (ODBC SQLState: 42S02) Step Error Description:[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'dbo.vwEstAssetStationAddress'. Step Error code: 800400D0 Step Error Help File:SQLDMO80.hlp Step Error Help Context ID:1131 ``` My searches on the net didn't provide much help. There are reports of these errors getting hit, but none seem to match my circumstances. One suggestion I found was the the sysdepends table had become corrupted, making the DTS job run its scripts in the wrong order. Howeever, I ran the following script to correct that table and it still throws the same error: ``` USE master GO ALTER DATABASE [DATABASE NAME] SET SINGLE_USER GO USE [DATABASE NAME] GO DBCC CHECKTABLE('sysdepends',REPAIR_REBUILD ) GO USE master GO ALTER DATABASE [DATABASE NAME] SET MULTI_USER GO ``` I have also seen that having different object owners can cause this error. But I have confirmed that the objects are all owned by the dbo user in this case. Any suggestions?
I feel stupid, but am posting the answer I just found for posterity (and so all you helpful fellows can stop stressing on my behalf. Even though I had selected all the user tables, views, stored procedures and user defined functions to copy, I hadn't selected "Include all dependant objects". I had assumed that if you selected two objects to copy, and one was dependant on the other, SQL would always do them in the correct order. Aparrently not. Selecting this little check box made all the difference. Thanks again to those who helped with suggestions
203,456
<p>I can get the executable location from the process, how do I get the icon from file?</p> <p>Maybe use windows api LoadIcon(). I wonder if there is .NET way...</p>
[ { "answer_id": 203490, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": true, "text": "<pre><code>Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);\n</code></pre>\n" }, { "answer_id": 203517, "author": "RobS", "author_id": 18471, "author_profile": "https://Stackoverflow.com/users/18471", "pm_score": 4, "selected": false, "text": "<p>This is a sample from a console application implementation.</p>\n\n<pre><code>using System;\nusing System.Drawing; //For Icon\nusing System.Reflection; //For Assembly\n\nnamespace ConsoleApplication\n{\n class Program\n {\n static void Main(string[] args)\n {\n try\n {\n //Gets the icon associated with the currently executing assembly\n //(or pass a different file path and name for a different executable)\n Icon appIcon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location); \n }\n catch(ArgumentException ae) \n {\n //handle\n } \n }\n }\n}\n</code></pre>\n" }, { "answer_id": 203637, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 2, "selected": false, "text": "<p>Use the <a href=\"http://www.pinvoke.net/default.aspx/shell32/ExtractIconEx.html\" rel=\"nofollow noreferrer\">ExtractIconEx</a> (and <a href=\"http://msdn.microsoft.com/en-us/library/ms648069.aspx\" rel=\"nofollow noreferrer\">here</a>) p/invoke. You can extract small and large icons from any dll or exe. Shell32.dll itself has over 200 icons that are quite useful for a standard Windows application. You just have to first figure out what the index is for the icon(s) you want.</p>\n\n<p>Edit: I did quick SO search and found <a href=\"https://stackoverflow.com/questions/189031/set-same-icon-for-all-my-forms#189618\">this</a>. The index 0 icon is the application icon.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
I can get the executable location from the process, how do I get the icon from file? Maybe use windows api LoadIcon(). I wonder if there is .NET way...
``` Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName); ```
203,468
<p>Ok, so I'm looking for a bit of architecture guidance, my team is getting a chance to re-cast certain decisions with a new feature that we're building, and I wanted to see what SO thought :-) There are of course certain things that we're not changing, so the solution would have to fit in this model. Namely, that we've got an ASP.NET application, which uses web services to allow users to perform actions on the system.</p> <p>The problem comes in because, as with many systems, different users need access to different functions. Some roles have access to Y button, and others have access to Y and B button, while another still only has access to B. Most of the time that I see this, developers just put in a mish-mosh of if statements to deal with the UI state. My fear is that left unchecked, this will become an unmaintainable mess, because in addition to putting authorization logic in the GUI, it needs to be put in the web services (which are called via ajax) to ensure that only authorized users call certain methods.</p> <p>so my question to you is, how can a system be designed to decrease the random ad-hoc if statements here and there that check for specific roles, which could be re-used in both GUI/webform code, and web service code.</p> <p>Just for clarity, this is an ASP.NET web application, using webforms, and <a href="http://projects.nikhilk.net/ScriptSharp/" rel="nofollow noreferrer">Script#</a> for the AJAX functionality. Don't let the script# throw you off of answering, it's not fundamentally different than asp.net ajax :-)</p>
[ { "answer_id": 203490, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": true, "text": "<pre><code>Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);\n</code></pre>\n" }, { "answer_id": 203517, "author": "RobS", "author_id": 18471, "author_profile": "https://Stackoverflow.com/users/18471", "pm_score": 4, "selected": false, "text": "<p>This is a sample from a console application implementation.</p>\n\n<pre><code>using System;\nusing System.Drawing; //For Icon\nusing System.Reflection; //For Assembly\n\nnamespace ConsoleApplication\n{\n class Program\n {\n static void Main(string[] args)\n {\n try\n {\n //Gets the icon associated with the currently executing assembly\n //(or pass a different file path and name for a different executable)\n Icon appIcon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location); \n }\n catch(ArgumentException ae) \n {\n //handle\n } \n }\n }\n}\n</code></pre>\n" }, { "answer_id": 203637, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 2, "selected": false, "text": "<p>Use the <a href=\"http://www.pinvoke.net/default.aspx/shell32/ExtractIconEx.html\" rel=\"nofollow noreferrer\">ExtractIconEx</a> (and <a href=\"http://msdn.microsoft.com/en-us/library/ms648069.aspx\" rel=\"nofollow noreferrer\">here</a>) p/invoke. You can extract small and large icons from any dll or exe. Shell32.dll itself has over 200 icons that are quite useful for a standard Windows application. You just have to first figure out what the index is for the icon(s) you want.</p>\n\n<p>Edit: I did quick SO search and found <a href=\"https://stackoverflow.com/questions/189031/set-same-icon-for-all-my-forms#189618\">this</a>. The index 0 icon is the application icon.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]
Ok, so I'm looking for a bit of architecture guidance, my team is getting a chance to re-cast certain decisions with a new feature that we're building, and I wanted to see what SO thought :-) There are of course certain things that we're not changing, so the solution would have to fit in this model. Namely, that we've got an ASP.NET application, which uses web services to allow users to perform actions on the system. The problem comes in because, as with many systems, different users need access to different functions. Some roles have access to Y button, and others have access to Y and B button, while another still only has access to B. Most of the time that I see this, developers just put in a mish-mosh of if statements to deal with the UI state. My fear is that left unchecked, this will become an unmaintainable mess, because in addition to putting authorization logic in the GUI, it needs to be put in the web services (which are called via ajax) to ensure that only authorized users call certain methods. so my question to you is, how can a system be designed to decrease the random ad-hoc if statements here and there that check for specific roles, which could be re-used in both GUI/webform code, and web service code. Just for clarity, this is an ASP.NET web application, using webforms, and [Script#](http://projects.nikhilk.net/ScriptSharp/) for the AJAX functionality. Don't let the script# throw you off of answering, it's not fundamentally different than asp.net ajax :-)
``` Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName); ```
203,469
<p>How do you use enums in Oracle using SQL only? (No PSQL)</p> <p>In MySQL you can do:</p> <pre><code>CREATE TABLE sizes ( name ENUM('small', 'medium', 'large') ); </code></pre> <p>What would be a similar way to do this in Oracle?</p>
[ { "answer_id": 203547, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 7, "selected": true, "text": "<p>Reading a bit about the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/enum.html\" rel=\"noreferrer\">MySQL enum</a>, I'm guessing the closest equivalent would be a simple check constraint</p>\n\n<pre><code>CREATE TABLE sizes (\n name VARCHAR2(10) CHECK( name IN ('small','medium','large') )\n);\n</code></pre>\n\n<p>but that doesn't allow you to reference the value by the index. A more complicated foreign key relationship would also be possible</p>\n\n<pre><code>CREATE TABLE valid_names (\n name_id NUMBER PRIMARY KEY,\n name_str VARCHAR2(10)\n);\n\nINSERT INTO valid_sizes VALUES( 1, 'small' );\nINSERT INTO valid_sizes VALUES( 2, 'medium' );\nINSERT INTO valid_sizes VALUES( 3, 'large' );\n\nCREATE TABLE sizes (\n name_id NUMBER REFERENCES valid_names( name_id )\n);\n\nCREATE VIEW vw_sizes\n AS \n SELECT a.name_id name, &lt;&lt;other columns from the sizes table&gt;&gt;\n FROM valid_sizes a,\n sizes b\n WHERE a.name_id = b.name_id\n</code></pre>\n\n<p>As long as you operate through the view, it would seem that your could replicate the functionality reasonably well.</p>\n\n<p>Now, if you admit PL/SQL solutions, you can create custom object types that could include logic to limit the set of values they can hold and to have methods to get the IDs and to get the values, etc.</p>\n" }, { "answer_id": 4931205, "author": "giacomino", "author_id": 213588, "author_profile": "https://Stackoverflow.com/users/213588", "pm_score": 1, "selected": false, "text": "<p>At this link you can find an alternative solution/workaround for Oracle, inspired by C language enums: <a href=\"http://www.petefinnigan.com/weblog/archives/00001246.htm\" rel=\"nofollow\">http://www.petefinnigan.com/weblog/archives/00001246.htm</a></p>\n\n<p>Shortly put, Pete suggests to define some integer constants and to use a SUBTYPE to constrait them:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>RED constant number(1):=1;\nGREEN constant number(1):=2;\nBLUE constant number(1):=3;\nYELLOW constant number(1):=4;\n\nsubtype COLORS is binary_integer range 1..4;\n</code></pre>\n\n\n\n<p>After that you can declare variables, pass parameters and return values from functions and so on, with type COLORS.</p>\n" }, { "answer_id": 51859770, "author": "ezzadeen", "author_id": 1421405, "author_profile": "https://Stackoverflow.com/users/1421405", "pm_score": 2, "selected": false, "text": "<p>Why not use a constraint for the column? It will do the same thing:</p>\n\n<p>ALTER TABLE x ADD CONSTRAINT size_constraint check (x_size in ('small', 'medium', 'large'))</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
How do you use enums in Oracle using SQL only? (No PSQL) In MySQL you can do: ``` CREATE TABLE sizes ( name ENUM('small', 'medium', 'large') ); ``` What would be a similar way to do this in Oracle?
Reading a bit about the [MySQL enum](http://dev.mysql.com/doc/refman/5.0/en/enum.html), I'm guessing the closest equivalent would be a simple check constraint ``` CREATE TABLE sizes ( name VARCHAR2(10) CHECK( name IN ('small','medium','large') ) ); ``` but that doesn't allow you to reference the value by the index. A more complicated foreign key relationship would also be possible ``` CREATE TABLE valid_names ( name_id NUMBER PRIMARY KEY, name_str VARCHAR2(10) ); INSERT INTO valid_sizes VALUES( 1, 'small' ); INSERT INTO valid_sizes VALUES( 2, 'medium' ); INSERT INTO valid_sizes VALUES( 3, 'large' ); CREATE TABLE sizes ( name_id NUMBER REFERENCES valid_names( name_id ) ); CREATE VIEW vw_sizes AS SELECT a.name_id name, <<other columns from the sizes table>> FROM valid_sizes a, sizes b WHERE a.name_id = b.name_id ``` As long as you operate through the view, it would seem that your could replicate the functionality reasonably well. Now, if you admit PL/SQL solutions, you can create custom object types that could include logic to limit the set of values they can hold and to have methods to get the IDs and to get the values, etc.
203,473
<p>I have a Crystal Report that looks like:</p> <p><em>Date | Person | Ticket | Summary <br> Date | Person | Ticket | Summary <br> Date | Person | Ticket | Summary</em> </p> <p>I would like it to look like: </p> <p><em>Date <br> Person | Ticket | Summary <br> Person | Ticket | Summary <br><br> Date <br> Person | Ticket | Summary</em></p> <p>All values are pulled from a MS SQL 2000 database, the application that will ultimately use the report is a VB 6 app that I unfortunately have to support. </p>
[ { "answer_id": 203547, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 7, "selected": true, "text": "<p>Reading a bit about the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/enum.html\" rel=\"noreferrer\">MySQL enum</a>, I'm guessing the closest equivalent would be a simple check constraint</p>\n\n<pre><code>CREATE TABLE sizes (\n name VARCHAR2(10) CHECK( name IN ('small','medium','large') )\n);\n</code></pre>\n\n<p>but that doesn't allow you to reference the value by the index. A more complicated foreign key relationship would also be possible</p>\n\n<pre><code>CREATE TABLE valid_names (\n name_id NUMBER PRIMARY KEY,\n name_str VARCHAR2(10)\n);\n\nINSERT INTO valid_sizes VALUES( 1, 'small' );\nINSERT INTO valid_sizes VALUES( 2, 'medium' );\nINSERT INTO valid_sizes VALUES( 3, 'large' );\n\nCREATE TABLE sizes (\n name_id NUMBER REFERENCES valid_names( name_id )\n);\n\nCREATE VIEW vw_sizes\n AS \n SELECT a.name_id name, &lt;&lt;other columns from the sizes table&gt;&gt;\n FROM valid_sizes a,\n sizes b\n WHERE a.name_id = b.name_id\n</code></pre>\n\n<p>As long as you operate through the view, it would seem that your could replicate the functionality reasonably well.</p>\n\n<p>Now, if you admit PL/SQL solutions, you can create custom object types that could include logic to limit the set of values they can hold and to have methods to get the IDs and to get the values, etc.</p>\n" }, { "answer_id": 4931205, "author": "giacomino", "author_id": 213588, "author_profile": "https://Stackoverflow.com/users/213588", "pm_score": 1, "selected": false, "text": "<p>At this link you can find an alternative solution/workaround for Oracle, inspired by C language enums: <a href=\"http://www.petefinnigan.com/weblog/archives/00001246.htm\" rel=\"nofollow\">http://www.petefinnigan.com/weblog/archives/00001246.htm</a></p>\n\n<p>Shortly put, Pete suggests to define some integer constants and to use a SUBTYPE to constrait them:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>RED constant number(1):=1;\nGREEN constant number(1):=2;\nBLUE constant number(1):=3;\nYELLOW constant number(1):=4;\n\nsubtype COLORS is binary_integer range 1..4;\n</code></pre>\n\n\n\n<p>After that you can declare variables, pass parameters and return values from functions and so on, with type COLORS.</p>\n" }, { "answer_id": 51859770, "author": "ezzadeen", "author_id": 1421405, "author_profile": "https://Stackoverflow.com/users/1421405", "pm_score": 2, "selected": false, "text": "<p>Why not use a constraint for the column? It will do the same thing:</p>\n\n<p>ALTER TABLE x ADD CONSTRAINT size_constraint check (x_size in ('small', 'medium', 'large'))</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8900/" ]
I have a Crystal Report that looks like: *Date | Person | Ticket | Summary Date | Person | Ticket | Summary Date | Person | Ticket | Summary* I would like it to look like: *Date Person | Ticket | Summary Person | Ticket | Summary Date Person | Ticket | Summary* All values are pulled from a MS SQL 2000 database, the application that will ultimately use the report is a VB 6 app that I unfortunately have to support.
Reading a bit about the [MySQL enum](http://dev.mysql.com/doc/refman/5.0/en/enum.html), I'm guessing the closest equivalent would be a simple check constraint ``` CREATE TABLE sizes ( name VARCHAR2(10) CHECK( name IN ('small','medium','large') ) ); ``` but that doesn't allow you to reference the value by the index. A more complicated foreign key relationship would also be possible ``` CREATE TABLE valid_names ( name_id NUMBER PRIMARY KEY, name_str VARCHAR2(10) ); INSERT INTO valid_sizes VALUES( 1, 'small' ); INSERT INTO valid_sizes VALUES( 2, 'medium' ); INSERT INTO valid_sizes VALUES( 3, 'large' ); CREATE TABLE sizes ( name_id NUMBER REFERENCES valid_names( name_id ) ); CREATE VIEW vw_sizes AS SELECT a.name_id name, <<other columns from the sizes table>> FROM valid_sizes a, sizes b WHERE a.name_id = b.name_id ``` As long as you operate through the view, it would seem that your could replicate the functionality reasonably well. Now, if you admit PL/SQL solutions, you can create custom object types that could include logic to limit the set of values they can hold and to have methods to get the IDs and to get the values, etc.
203,475
<p>In my code, I am creating a collection of objects which will be accessed by various threads in a fashion that is only safe if the objects are immutable. When an attempt is made to insert a new object into my collection, I want to test to see if it is immutable (if not, I'll throw an exception).</p> <p>One thing I can do is to check a few well-known immutable types:</p> <pre><code>private static final Set&lt;Class&gt; knownImmutables = new HashSet&lt;Class&gt;(Arrays.asList( String.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Boolean.class, BigInteger.class, BigDecimal.class )); ... public static boolean isImmutable(Object o) { return knownImmutables.contains(o.getClass()); } </code></pre> <p>This actually gets me 90% of the way, but sometimes my users will want to create simple immutable types of their own:</p> <pre><code>public class ImmutableRectangle { private final int width; private final int height; public ImmutableRectangle(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } } </code></pre> <p>Is there some way (perhaps using reflection) that I could reliably detect whether a class is immutable? False positives (thinking it's immutable when it isn't) are not acceptable but false negatives (thinking it's mutable when it isn't) are.</p> <p><strong>Edited to add:</strong> Thanks for the insightful and helpful answers. As some of the answers pointed out, I neglected to define my security objectives. The threat here is clueless developers -- this is a piece of framework code that will be used by large numbers of people who know next-to-nothing about threading and won't be reading the documentation. I do NOT need to defend against malicious developers -- anyone clever enough to <a href="http://directwebremoting.org/blog/joe/2005/05/26/1117108773674.html" rel="noreferrer">mutate a String</a> or perform other shenanigans will also be smart enough to know it's not safe in this case. Static analysis of the codebase IS an option, so long as it is automated, but code reviews cannot be counted on because there is no guarantee every review will have threading-savvy reviewers.</p>
[ { "answer_id": 203500, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 3, "selected": false, "text": "<p>Basically no. </p>\n\n<p>You could build a giant white-list of accepted classes but I think the less crazy way would be to just write in the documentation for the collection that everything that goes is this collection <em>must</em> be immutable.</p>\n\n<p><strong>Edit:</strong> Other people have suggested having an immutable annotation. This is fine, but you need the documentation as well. Otherwise people will just think \"if I put this annotation on my class I can store it in the collection\" and will just chuck it on anything, immutable and mutable classes alike. In fact, I would be wary of having an immutable annotation just in case people think that annotation <em>makes</em> their class immutable.</p>\n" }, { "answer_id": 203504, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "<p>At my company we've defined an Attribute called <code>@Immutable</code>. If you choose to attach that to a class, it means you promise you're immutable.</p>\n\n<p>It works for documentation, and in your case it would work as a filter.</p>\n\n<p>Of course you're still depending on the author keeping his word about being immutable, but since the author explicitly added the annotation it's a reasonable assumption.</p>\n" }, { "answer_id": 203506, "author": "Pablo Fernandez", "author_id": 7595, "author_profile": "https://Stackoverflow.com/users/7595", "pm_score": 2, "selected": false, "text": "<p>You Can Ask your clients to add metadata (annotations) and check them at runtime with reflection, like this:</p>\n\n<p>Metadata:</p>\n\n<pre><code>@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.CLASS)\npublic @interface Immutable{ }\n</code></pre>\n\n<p>Client Code:</p>\n\n<pre><code>@Immutable\npublic class ImmutableRectangle {\n private final int width;\n private final int height;\n public ImmutableRectangle(int width, int height) {\n this.width = width;\n this.height = height;\n }\n public int getWidth() { return width; }\n public int getHeight() { return height; }\n}\n</code></pre>\n\n<p>Then by using reflection on the class, check if it has the annotation (I would paste the code but its boilerplate and can be found easily online)</p>\n" }, { "answer_id": 203571, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 6, "selected": true, "text": "<p>There is no reliable way to detect if a class is immutable. This is because there are so many ways a property of a class might be altered and you can't detect all of them via reflection.</p>\n\n<p>The only way to get close to this is:</p>\n\n<ul>\n<li>Only allow final properties of types that are immutable (primitive types and classes you know are immutable),</li>\n<li>Require the class to be final itself</li>\n<li>Require that they inherit from a base class you provide (which is guaranteed to be immutable)</li>\n</ul>\n\n<p>Then you can check with the following code if the object you have is immutable:</p>\n\n<pre><code>static boolean isImmutable(Object obj) {\n Class&lt;?&gt; objClass = obj.getClass();\n\n // Class of the object must be a direct child class of the required class\n Class&lt;?&gt; superClass = objClass.getSuperclass();\n if (!Immutable.class.equals(superClass)) {\n return false;\n }\n\n // Class must be final\n if (!Modifier.isFinal(objClass.getModifiers())) {\n return false;\n }\n\n // Check all fields defined in the class for type and if they are final\n Field[] objFields = objClass.getDeclaredFields();\n for (int i = 0; i &lt; objFields.length; i++) {\n if (!Modifier.isFinal(objFields[i].getModifiers())\n || !isValidFieldType(objFields[i].getType())) {\n return false;\n }\n }\n\n // Lets hope we didn't forget something\n return true;\n}\n\nstatic boolean isValidFieldType(Class&lt;?&gt; type) {\n // Check for all allowed property types...\n return type.isPrimitive() || String.class.equals(type);\n}\n</code></pre>\n\n<p><strong>Update:</strong> As suggested in the comments, it could be extended to recurse on the superclass instead of checking for a certain class. It was also suggested to recursively use isImmutable in the isValidFieldType Method. This could probably work and I have also done some testing. But this is not trivial. You can't just check all field types with a call to isImmutable, because String already fails this test (its field <code>hash</code> is not final!). Also you are easily running into endless recursions, causing <em>StackOverflowErrors</em> ;) Other problems might be caused by generics, where you also have to check their types for immutablity.</p>\n\n<p>I think with some work, these potential problems might be solved somehow. But then, you have to ask yourself first if it really is worth it (also performance wise).</p>\n" }, { "answer_id": 203639, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "<p>This could be another hint:</p>\n\n<p>If the class has no setters then it cannot be mutated, granted the parameters it was created with are either \"primitive\" types or not mutable themselves. </p>\n\n<p>Also no methods could be overriden, all fields are final and private, </p>\n\n<p>I'll try to code something tomorrow for you, but Simon's code using reflection looks pretty good. </p>\n\n<p>In the mean time try to grab a copy of the \"Effective Java\" book by Josh Block , it has an Item related to this topic. While is does not for sure say how to detect an inmmutable class, it shows how to create a good one.</p>\n\n<p>The item is called: \"Favor immutability\"</p>\n\n<p>link:\n<a href=\"http://java.sun.com/docs/books/effective/\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/effective/</a></p>\n" }, { "answer_id": 203797, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 2, "selected": false, "text": "<p>Like the other answerers already said, IMHO there is no reliable way to find out if an object is really immutable.</p>\n\n<p>I would just introduce an interface \"Immutable\" to check against when appending. This works as a hint that only immutable objects should be inserted for whatever reason you're doing it.</p>\n\n<pre><code>interface Immutable {}\n\nclass MyImmutable implements Immutable{...}\n\npublic void add(Object o) {\n if (!(o instanceof Immutable) &amp;&amp; !checkIsImmutableBasePrimitive(o))\n throw new IllegalArgumentException(\"o is not immutable!\");\n ...\n}\n</code></pre>\n" }, { "answer_id": 203961, "author": "Martin Probst", "author_id": 22227, "author_profile": "https://Stackoverflow.com/users/22227", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>In my code, I am creating a collection of objects which will be accessed by various threads in a fashion that is only safe if the objects are immutable.</p>\n</blockquote>\n\n<p>Not a direct answer to your question, but keep in mind that objects that are immutable are not automatically guaranteed to be thread safe (sadly). Code needs to be side-effect free to be thread safe, and that's quite a bit more difficult.</p>\n\n<p>Suppose you have this class:</p>\n\n<pre><code>class Foo {\n final String x;\n final Integer y;\n ...\n\n public bar() {\n Singleton.getInstance().foolAround();\n }\n}\n</code></pre>\n\n<p>Then the <code>foolAround()</code> method might include some non-thread safe operations, which will blow up your app. And it's not possible to test for this using reflection, as the actual reference can only be found in the method body, not in the fields or exposed interface.</p>\n\n<p>Other than that, the others are correct: you can scan for all declared fields of the class, check if every one of them is final and also an immutable class, and you're done. I don't think methods being final is a requirement.</p>\n\n<p>Also, be careful about recursively checking dependent fields for immutability, you might end up with circles:</p>\n\n<pre><code>class A {\n final B b; // might be immutable...\n}\n\nclass B {\n final A a; // same so here.\n}\n</code></pre>\n\n<p>Classes A and B are perfectly immutable (and possibly even usable through some reflection hacks), but naive recursive code will go into an endless loop checking A, then B, then A again, onwards to B, ...</p>\n\n<p>You can fix that with a 'seen' map that disallows cycles, or with some really clever code that decides classes are immutable if all their dependees are immutable only depending on themselves, but that's going to be really complicated...</p>\n" }, { "answer_id": 204015, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 5, "selected": false, "text": "<p>Use the <a href=\"http://jcip.net.s3-website-us-east-1.amazonaws.com/annotations/doc/net/jcip/annotations/Immutable.html\" rel=\"noreferrer\">Immutable</a> annotation from <a href=\"http://jcip.net/\" rel=\"noreferrer\">Java Concurrency in Practice</a>. The tool <a href=\"http://findbugs.sourceforge.net/\" rel=\"noreferrer\">FindBugs</a> can then help in detecting classes which are mutable but shouldn't be.</p>\n" }, { "answer_id": 205428, "author": "james", "author_id": 24634, "author_profile": "https://Stackoverflow.com/users/24634", "pm_score": 2, "selected": false, "text": "<p>why do all the recommendations require the class to be final? if you are using reflection to check the class of each object, and you can determine programmatically that that class is immutable (immutable, final fields), then you don't need to require that the class itself is final.</p>\n" }, { "answer_id": 612042, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 0, "selected": false, "text": "<p>Something which works for a high percentage of builtin classes is test for instanceof Comparable. For the classes which are not immutable like Date, they are often treated as immutable in most cases.</p>\n" }, { "answer_id": 6843336, "author": "M. Tempesta", "author_id": 865227, "author_profile": "https://Stackoverflow.com/users/865227", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>public static boolean isImmutable(Object object){\n if (object instanceof Number) { // Numbers are immutable\n if (object instanceof AtomicInteger) {\n // AtomicIntegers are mutable\n } else if (object instanceof AtomicLong) {\n // AtomLongs are mutable\n } else {\n return true;\n }\n } else if (object instanceof String) { // Strings are immutable\n return true;\n } else if (object instanceof Character) { // Characters are immutable\n return true;\n } else if (object instanceof Class) { // Classes are immutable\n return true;\n }\n\n Class&lt;?&gt; objClass = object.getClass();\n\n // Class must be final\n if (!Modifier.isFinal(objClass.getModifiers())) {\n return false;\n }\n\n // Check all fields defined in the class for type and if they are final\n Field[] objFields = objClass.getDeclaredFields();\n for (int i = 0; i &lt; objFields.length; i++) {\n if (!Modifier.isFinal(objFields[i].getModifiers())\n || !isImmutable(objFields[i].getType())) {\n return false;\n }\n }\n\n // Lets hope we didn't forget something\n return true;\n}\n</code></pre>\n" }, { "answer_id": 14931051, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 2, "selected": false, "text": "<p>You can use AOP and <a href=\"http://aspects.jcabi.com/annotation-immutable.html\" rel=\"nofollow\"><code>@Immutable</code></a> annotation from <a href=\"http://aspects.jcabi.com/\" rel=\"nofollow\">jcabi-aspects</a>:</p>\n\n<pre><code>@Immutable\npublic class Foo {\n private String data;\n}\n// this line will throw a runtime exception since class Foo\n// is actually mutable, despite the annotation\nObject object = new Foo();\n</code></pre>\n" }, { "answer_id": 23955278, "author": "Grundlefleck", "author_id": 4120, "author_profile": "https://Stackoverflow.com/users/4120", "pm_score": 1, "selected": false, "text": "<p>To my knowledge, there is no way to identify immutable objects that is 100% correct. However, I have written a library to get you closer. It performs analysis of bytecode of a class to determine if it is immutable or not, and can execute at runtime. It is on the strict side, so it also allows whitelisting known immutable classes.</p>\n\n<p>You can check it out at: <a href=\"http://www.mutabilitydetector.org\" rel=\"nofollow\">www.mutabilitydetector.org</a></p>\n\n<p>It allows you to write code like this in your application:</p>\n\n<pre><code>/*\n* Request an analysis of the runtime class, to discover if this\n* instance will be immutable or not.\n*/\nAnalysisResult result = analysisSession.resultFor(dottedClassName);\n\nif (result.isImmutable.equals(IMMUTABLE)) {\n /*\n * rest safe in the knowledge the class is\n * immutable, share across threads with joyful abandon\n */\n} else if (result.isImmutable.equals(NOT_IMMUTABLE)) {\n /*\n * be careful here: make defensive copies,\n * don't publish the reference,\n * read Java Concurrency In Practice right away!\n */\n}\n</code></pre>\n\n<p>It is free and open source under the Apache 2.0 license.</p>\n" }, { "answer_id": 28112166, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 0, "selected": false, "text": "<p>I appreciate and admire the amount of work Grundlefleck has put into his mutability detector, but I think it is a bit of an overkill. You can write a simple but practically very adequate (that is, <em>pragmatic</em>) detector as follows:</p>\n\n<p>(note: this is a copy of my comment here: <a href=\"https://stackoverflow.com/a/28111150/773113\">https://stackoverflow.com/a/28111150/773113</a>)</p>\n\n<p>First of all, you are not going to be just writing a method which determines whether a class is immutable; instead, you will need to write an immutability detector class, because it is going to have to maintain some state. The state of the detector will be the detected immutability of all classes which it has examined so far. This is not only useful for performance, but it is actually necessary because a class may contain a circular reference, which would cause a simplistic immutability detector to fall into infinite recursion.</p>\n\n<p>The immutability of a class has four possible values: <code>Unknown</code>, <code>Mutable</code>, <code>Immutable</code>, and <code>Calculating</code>. You will probably want to have a map which associates each class that you have encountered so far to an immutability value. Of course, <code>Unknown</code> does not actually need to be implemented, since it will be the implied state of any class which is not yet in the map.</p>\n\n<p>So, when you begin examining a class, you associate it with a <code>Calculating</code> value in the map, and when you are done, you replace <code>Calculating</code> with either <code>Immutable</code> or <code>Mutable</code>.</p>\n\n<p>For each class, you only need to check the field members, not the code. The idea of checking bytecode is rather misguided.</p>\n\n<p>First of all, you should <strong>not</strong> check whether a class is final; The finality of a class does not affect its immutability. Instead, a method which expects an immutable parameter should first of all invoke the immutability detector to assert the immutability of the class of the actual object that was passed. This test can be omitted if the type of the parameter is a final class, so finality is good for performance, but strictly speaking not necessary. Also, as you will see further down, a field whose type is of a non-final class will cause the declaring class to be considered as mutable, but still, that's a problem of the declaring class, not the problem of the non-final immutable member class. It is perfectly fine to have a tall hierarchy of immutable classes, in which all the non-leaf nodes must of course be non-final.</p>\n\n<p>You should <strong>not</strong> check whether a field is private; it is perfectly fine for a class to have a public field, and the visibility of the field does not affect the immutability of the declaring class in any way, shape, or form. You only need to check whether the field is final and its type is immutable.</p>\n\n<p>When examining a class, what you want to do first of all is to recurse to determine the immutability of its <code>super</code> class. If the super is mutable, then the descendant is by definition mutable too.</p>\n\n<p>Then, you only need to check the <em>declared</em> fields of the class, not <em>all</em> fields.</p>\n\n<p>If a field is non-final, then your class is mutable.</p>\n\n<p>If a field is final, but the type of the field is mutable, then your class is mutable. (Arrays are by definition mutable.)</p>\n\n<p>If a field is final, and the type of the field is <code>Calculating</code>, then ignore it and proceed to the next field. If all fields are either immutable or <code>Calculating</code>, then your class is immutable.</p>\n\n<p>If the type of the field is an interface, or an abstract class, or a non-final class, then it is to be considered as mutable, since you have absolutely no control over what the actual implementation may do. This might seem like an insurmountable problem, because it means that wrapping a modifiable collection inside an <code>UnmodifiableCollection</code> will still fail the immutability test, but it is actually fine, and it can be handled with the following workaround.</p>\n\n<p>Some classes may contain non-final fields and still be <em>effectively immutable</em>. An example of this is the <code>String</code> class. Other classes which fall into this category are classes which contain non-final members purely for performance monitoring purposes (invocation counters, etc.), classes which implement <em>popsicle immutability</em> (look it up), and classes which contain members that are interfaces which are known to not cause any side effects. Also, if a class contains bona fide mutable fields but promises not to take them into account when computing hashCode() and equals(), then the class is of course unsafe when it comes to multi-threading, but it can still be considered as immutable for the purpose of using it as a key in a map. So, all these cases can be handled in one of two ways:</p>\n\n<ol>\n<li><p>Manually adding classes (and interfaces) to your immutability detector. If you know that a certain class is effectively immutable despite the fact that the immutability test for it fails, you can manually add an entry to your detector which associates it with <code>Immutable</code>. This way, the detector will never attempt to check whether it is immutable, it will always just say 'yes, it is.'</p></li>\n<li><p>Introducing an <code>@ImmutabilityOverride</code> annotation. Your immutability detector can check for the presence of this annotation on a field, and if present, it may treat the field as immutable despite the fact that the field may be non-final or its type may be mutable. The detector may also check for the presence of this annotation on the class, thus treating the class as immutable without even bothering to check its fields.</p></li>\n</ol>\n\n<p>I hope this helps future generations.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14570/" ]
In my code, I am creating a collection of objects which will be accessed by various threads in a fashion that is only safe if the objects are immutable. When an attempt is made to insert a new object into my collection, I want to test to see if it is immutable (if not, I'll throw an exception). One thing I can do is to check a few well-known immutable types: ``` private static final Set<Class> knownImmutables = new HashSet<Class>(Arrays.asList( String.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Boolean.class, BigInteger.class, BigDecimal.class )); ... public static boolean isImmutable(Object o) { return knownImmutables.contains(o.getClass()); } ``` This actually gets me 90% of the way, but sometimes my users will want to create simple immutable types of their own: ``` public class ImmutableRectangle { private final int width; private final int height; public ImmutableRectangle(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } } ``` Is there some way (perhaps using reflection) that I could reliably detect whether a class is immutable? False positives (thinking it's immutable when it isn't) are not acceptable but false negatives (thinking it's mutable when it isn't) are. **Edited to add:** Thanks for the insightful and helpful answers. As some of the answers pointed out, I neglected to define my security objectives. The threat here is clueless developers -- this is a piece of framework code that will be used by large numbers of people who know next-to-nothing about threading and won't be reading the documentation. I do NOT need to defend against malicious developers -- anyone clever enough to [mutate a String](http://directwebremoting.org/blog/joe/2005/05/26/1117108773674.html) or perform other shenanigans will also be smart enough to know it's not safe in this case. Static analysis of the codebase IS an option, so long as it is automated, but code reviews cannot be counted on because there is no guarantee every review will have threading-savvy reviewers.
There is no reliable way to detect if a class is immutable. This is because there are so many ways a property of a class might be altered and you can't detect all of them via reflection. The only way to get close to this is: * Only allow final properties of types that are immutable (primitive types and classes you know are immutable), * Require the class to be final itself * Require that they inherit from a base class you provide (which is guaranteed to be immutable) Then you can check with the following code if the object you have is immutable: ``` static boolean isImmutable(Object obj) { Class<?> objClass = obj.getClass(); // Class of the object must be a direct child class of the required class Class<?> superClass = objClass.getSuperclass(); if (!Immutable.class.equals(superClass)) { return false; } // Class must be final if (!Modifier.isFinal(objClass.getModifiers())) { return false; } // Check all fields defined in the class for type and if they are final Field[] objFields = objClass.getDeclaredFields(); for (int i = 0; i < objFields.length; i++) { if (!Modifier.isFinal(objFields[i].getModifiers()) || !isValidFieldType(objFields[i].getType())) { return false; } } // Lets hope we didn't forget something return true; } static boolean isValidFieldType(Class<?> type) { // Check for all allowed property types... return type.isPrimitive() || String.class.equals(type); } ``` **Update:** As suggested in the comments, it could be extended to recurse on the superclass instead of checking for a certain class. It was also suggested to recursively use isImmutable in the isValidFieldType Method. This could probably work and I have also done some testing. But this is not trivial. You can't just check all field types with a call to isImmutable, because String already fails this test (its field `hash` is not final!). Also you are easily running into endless recursions, causing *StackOverflowErrors* ;) Other problems might be caused by generics, where you also have to check their types for immutablity. I think with some work, these potential problems might be solved somehow. But then, you have to ask yourself first if it really is worth it (also performance wise).
203,477
<p>I'm using KML and the GGeoXml object to overlay some shapes on an embedded Google map. The placemarks in the KML file have some custom descriptive information that shows up in the balloons.</p> <pre><code>&lt;Placemark&gt; &lt;name /&gt; &lt;description&gt; &lt;![CDATA[ &lt;div class=&quot;MapPopup&quot;&gt; &lt;h6&gt;Concession&lt;/h6&gt; &lt;h4&gt;~Name~&lt;/h4&gt; &lt;p&gt;Description goes here&lt;/p&gt; &lt;a class=&quot;Button GoRight FloatRight&quot; href=&quot;#&quot;&gt;&lt;span&gt;&lt;/span&gt;View details&lt;/a&gt; &lt;/div&gt; ]]&gt; &lt;/description&gt; &lt;styleUrl&gt;#masterPolyStyle&lt;/styleUrl&gt; ...Placemarks go here ... &lt;/Placemark&gt; </code></pre> <p>So far so good - the popups show up and have the correct text in them. Here's the weird thing: I'm trying to use CSS to format what goes in the popups, and it halfway works.</p> <p>Specifically:</p> <ul> <li><p>The <code>&lt;h6&gt;</code> and <code>&lt;h4&gt;</code> elements are rendered using the colors and background images I've specified in my stylesheet.</p> </li> <li><p>Everything shows up in Arial, not in the font I've specified in my CSS.</p> </li> <li><p>The class names seem to be ignored (e.g. none of the <code>a.Button</code> formatting is applied; if I define a style like the one below, it's ignored.)</p> <pre><code> div.MapPopup { background:pink; } </code></pre> </li> </ul> <p>Any ideas? I wouldn't have been surprised for the CSS not to work at all, but it's weird that it only partly works.</p> <h3>Update</h3> <p>Here's a screenshot to better illustrate this. I've reproduced the <code>&lt;div class=&quot;MapPopup&quot;&gt;</code> markup further down on the page (in yellow), to show how it should be rendered according to my CSS.</p> <p><img src="https://farm4.static.flickr.com/3072/2942636927_2f8119a72a.jpg?v=0" alt="alt text" /></p>
[ { "answer_id": 203621, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 0, "selected": false, "text": "<p>My first guess is that you're running into an issue with CSS specificity. There is a good article on it at <a href=\"http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/\" rel=\"nofollow noreferrer\">http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/</a>, so if you can include a container element ID, that <em>may</em> help. </p>\n\n<p>Let me know if this doesn't turn out to be the problem and I'll come up with more ideas.</p>\n" }, { "answer_id": 208902, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 4, "selected": true, "text": "<p>As suggested I've gone in with Firebug to see what's going on. It looks like Google is doing two obnoxious things:</p>\n\n<ol>\n<li>It's stripping out all class attributes from my HTML.</li>\n<li>It's throwing all kinds of hard-coded styles around. </li>\n</ol>\n\n<p>Here's my HTML along with the first couple of wrappers inserted by Google:</p>\n\n<pre><code>&lt;div style=\"font-family: Arial,sans-serif; font-size: small;\"&gt;\n &lt;div id=\"iw_kml\"&gt;\n &lt;div&gt;\n &lt;h6&gt;Concession&lt;/h6&gt;\n &lt;h4&gt;BOIS KASSA 1108000 (Mobola-Mbondo)&lt;/h4&gt;\n &lt;p&gt;\n Description goes here&lt;/p&gt;\n &lt;a target=\"_blank\"&gt;&lt;span /&gt;View details &lt;/a&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>As you can see, my classes (e.g. <code>MapPopup</code> in my first <code>div</code>, <code>Button</code> etc. in the <code>&lt;a&gt;</code> tag) have all been stripped out. </p>\n\n<p>Knowing this I'll be able to work around Google's interference, using <code>!important</code> and targeting the container <code>div</code> for the whole map - still, this is annoying, and unexpectedly clumsy coming from Google.</p>\n" }, { "answer_id": 213893, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 2, "selected": false, "text": "<p>More related obnoxiousness related to the HTML in a KML <code>&lt;description&gt;</code> block: Any links are given the attribute <code>target=\"_blank\"</code>, whether you like it or not. I'm currently exploring ways to undo that, using jQuery, but what a drag. I really don't understand why Google feels the need to tamper with this HTML.</p>\n\n<p>See also <a href=\"http://groups.google.com/group/Google-Maps-API/browse_thread/thread/455e75b2c4549ab2/517f48eefbae46cb\" rel=\"nofollow noreferrer\">this thread on the official Google Group</a>.</p>\n" }, { "answer_id": 6949199, "author": "Mitchell", "author_id": 823833, "author_profile": "https://Stackoverflow.com/users/823833", "pm_score": 1, "selected": false, "text": "<p>I've had similar issues. I don't know how you are implementing your Marker, or if you are using InfoWindow, or .addListener, but they way I have had to get css styling to work inside of the \"pop up bubble\" (over the Marker) is to use what is called \"inline styling.\" So I have a variable that I pass into InfoWindow. Assuming you have initialized a variable \"marker\" with some options, and have the \"map\" instance created, some example code would look like this:</p>\n\n<pre><code>/*start of myHtml2 variable*/\nvar myHtml2 = \"&lt;div style=\\\"background-color:lightgray\\\"&gt;&lt;div style=\\\"padding:5px\\\"&gt;&lt;div\nstyle=\\\"font-size:1.25em\\\"&gt;Some text&lt;/div&gt;&lt;div&gt;Some more text&lt;br/&gt;\nYet more text&lt;br/&gt;&lt;/div&gt;&lt;table style=\\\"padding:5px\\\"&gt;&lt;tr&gt;&lt;td&gt;&lt;img src=\\\"A lake.jpg\\\"\nwidth=\\\"75px\\\" height=\\\"50px\\\"&gt;&lt;/td&gt;&lt;td&gt;More text&lt;br/&gt;Again, more text&lt;br/&gt;&lt;div\nstyle=\\\"font-size:.7em\\\"&gt;Last text&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/div&gt;&lt;/div&gt;\"\n/*end of variable*/\n\nvar infowindow2 = new google.maps.InfoWindow({content: myHtml2});\n /*mouseover could be 'click', etc.*/\ngoogle.maps.event.addListener(marker, 'mouseover', function(){ \ninfowindow2.open(map, marker);\n}); \n</code></pre>\n\n<p>I know the css styling code is cumbersome, but I haven't found a way to use complicated css styling inside \"the bubble pop up\" using css in the head, or from a style sheet There are always conflicts, and some features don't render properly.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I'm using KML and the GGeoXml object to overlay some shapes on an embedded Google map. The placemarks in the KML file have some custom descriptive information that shows up in the balloons. ``` <Placemark> <name /> <description> <![CDATA[ <div class="MapPopup"> <h6>Concession</h6> <h4>~Name~</h4> <p>Description goes here</p> <a class="Button GoRight FloatRight" href="#"><span></span>View details</a> </div> ]]> </description> <styleUrl>#masterPolyStyle</styleUrl> ...Placemarks go here ... </Placemark> ``` So far so good - the popups show up and have the correct text in them. Here's the weird thing: I'm trying to use CSS to format what goes in the popups, and it halfway works. Specifically: * The `<h6>` and `<h4>` elements are rendered using the colors and background images I've specified in my stylesheet. * Everything shows up in Arial, not in the font I've specified in my CSS. * The class names seem to be ignored (e.g. none of the `a.Button` formatting is applied; if I define a style like the one below, it's ignored.) ``` div.MapPopup { background:pink; } ``` Any ideas? I wouldn't have been surprised for the CSS not to work at all, but it's weird that it only partly works. ### Update Here's a screenshot to better illustrate this. I've reproduced the `<div class="MapPopup">` markup further down on the page (in yellow), to show how it should be rendered according to my CSS. ![alt text](https://farm4.static.flickr.com/3072/2942636927_2f8119a72a.jpg?v=0)
As suggested I've gone in with Firebug to see what's going on. It looks like Google is doing two obnoxious things: 1. It's stripping out all class attributes from my HTML. 2. It's throwing all kinds of hard-coded styles around. Here's my HTML along with the first couple of wrappers inserted by Google: ``` <div style="font-family: Arial,sans-serif; font-size: small;"> <div id="iw_kml"> <div> <h6>Concession</h6> <h4>BOIS KASSA 1108000 (Mobola-Mbondo)</h4> <p> Description goes here</p> <a target="_blank"><span />View details </a> </div> </div> </div> ``` As you can see, my classes (e.g. `MapPopup` in my first `div`, `Button` etc. in the `<a>` tag) have all been stripped out. Knowing this I'll be able to work around Google's interference, using `!important` and targeting the container `div` for the whole map - still, this is annoying, and unexpectedly clumsy coming from Google.
203,520
<p>I have what must be a typical catch-22 problem. I have a .NET WinForm control that contains a textbox and a checkbox. Both controls are data bound to properties on a data class instance. The textbox is for price, the check box to indicate that the price is a price override. Also on the data class is a property that holds the item's original price.</p> <p>I would like the controls to respect the following rules:</p> <ul> <li>When the user enters a value into the price textbox, the checkbox is automatically checked to indicate they are overriding the price value</li> <li>When the check box is un-checked, the item's price is restored to the original price.</li> </ul> <p>When the user unchecks the checkbox, the event handler tests the checked state, and sets the item's price property to the original price value. However, the price value being databound, a bind event is fired, which updates the textbox value, which fires the text changed event handler which re-checks the checkbox. </p> <p>I've attempted to trap the conditions where I'm explicitly updating something that would trigger a control change event. This only works for part of it though. The textbox change event fires other times that are outside my control, such as when databinding fires when the form is initially shown.</p> <p>I've been searching around and I guess I'm just not coming up with the right search terms to find what I'm looking for. It seems that databinding is all wonderful and nifty until you need to do something pratical with it, like having two bound controls interact with each other. There just doesn't seem to be a way to discriminate between what triggered the control events.</p> <p>I've also looked at the events available on the binding source component but there doesn't seem to be anything there that is any more useful. I can handle the event that fires after binding is complete, but that's after the problems occur.</p> <p>Anyone have any suggestions?</p>
[ { "answer_id": 203580, "author": "Chris Roland", "author_id": 27975, "author_profile": "https://Stackoverflow.com/users/27975", "pm_score": 0, "selected": false, "text": "<p>Have you considered handling the TextBox <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged(VS.80).aspx\" rel=\"nofollow noreferrer\">TextChanged</a> event to handle the CheckBox state instead of binding it?</p>\n\n<p>You could then compare the current TextBox value to the original and determine if the CheckBox should be true or false.</p>\n\n<p>Another thought is you could inherit TextBox and add properties to your custom TextBox so the TextBox handles it's own state. For example it can have a read-only IsOriginal property. </p>\n\n<p>I don't have VS installed right now so I didn't verify it, let me know if you want an example.</p>\n" }, { "answer_id": 203920, "author": "Tom Juergens", "author_id": 2899, "author_profile": "https://Stackoverflow.com/users/2899", "pm_score": 2, "selected": false, "text": "<p>I would suggest not handling the logic in the form code, but rather in the data class. All you need in the form is a couple of lines to set up the data binding. The data class can then take care of the rest:</p>\n\n<p>Form</p>\n\n<pre><code>Private _dc As DataClass\n\nPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n _dc = New DataClass\n txtPrice.DataBindings.Add(\"text\", _dc, \"Price\")\n chkOverride.DataBindings.Add(\"checked\", _dc, \"override\")\nEnd Sub\n</code></pre>\n\n<p>Data Class</p>\n\n<pre><code>Private _originalPrice As Double = 50\n\nPrivate _price As Double = _originalPrice\nPublic Property Price() As Double\n Get\n Return _price\n End Get\n Set(ByVal value As Double)\n If (_price &lt;&gt; value) Then\n _price = value\n Override = _price &lt;&gt; _originalPrice\n End If\n End Set\nEnd Property\n\n\nPrivate _override As Boolean\nPublic Property Override() As Boolean\n Get\n Return _override\n End Get\n Set(ByVal value As Boolean)\n If _override &lt;&gt; value Then\n _override = value\n If Not _override Then Price = OriginalPrice\n End If\n End Set\nEnd Property\n</code></pre>\n\n<p>No need to handle any CheckedChanged or TextChanged events in the form.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5496/" ]
I have what must be a typical catch-22 problem. I have a .NET WinForm control that contains a textbox and a checkbox. Both controls are data bound to properties on a data class instance. The textbox is for price, the check box to indicate that the price is a price override. Also on the data class is a property that holds the item's original price. I would like the controls to respect the following rules: * When the user enters a value into the price textbox, the checkbox is automatically checked to indicate they are overriding the price value * When the check box is un-checked, the item's price is restored to the original price. When the user unchecks the checkbox, the event handler tests the checked state, and sets the item's price property to the original price value. However, the price value being databound, a bind event is fired, which updates the textbox value, which fires the text changed event handler which re-checks the checkbox. I've attempted to trap the conditions where I'm explicitly updating something that would trigger a control change event. This only works for part of it though. The textbox change event fires other times that are outside my control, such as when databinding fires when the form is initially shown. I've been searching around and I guess I'm just not coming up with the right search terms to find what I'm looking for. It seems that databinding is all wonderful and nifty until you need to do something pratical with it, like having two bound controls interact with each other. There just doesn't seem to be a way to discriminate between what triggered the control events. I've also looked at the events available on the binding source component but there doesn't seem to be anything there that is any more useful. I can handle the event that fires after binding is complete, but that's after the problems occur. Anyone have any suggestions?
I would suggest not handling the logic in the form code, but rather in the data class. All you need in the form is a couple of lines to set up the data binding. The data class can then take care of the rest: Form ``` Private _dc As DataClass Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load _dc = New DataClass txtPrice.DataBindings.Add("text", _dc, "Price") chkOverride.DataBindings.Add("checked", _dc, "override") End Sub ``` Data Class ``` Private _originalPrice As Double = 50 Private _price As Double = _originalPrice Public Property Price() As Double Get Return _price End Get Set(ByVal value As Double) If (_price <> value) Then _price = value Override = _price <> _originalPrice End If End Set End Property Private _override As Boolean Public Property Override() As Boolean Get Return _override End Get Set(ByVal value As Boolean) If _override <> value Then _override = value If Not _override Then Price = OriginalPrice End If End Set End Property ``` No need to handle any CheckedChanged or TextChanged events in the form.
203,528
<p>When I build XML up from scratch with <code>XmlDocument</code>, the <code>OuterXml</code> property already has everything nicely indented with line breaks. However, if I call <code>LoadXml</code> on some very "compressed" XML (no line breaks or indention) then the output of <code>OuterXml</code> stays that way. So ...</p> <p>What is the simplest way to get beautified XML output from an instance of <code>XmlDocument</code>?</p>
[ { "answer_id": 203533, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 6, "selected": false, "text": "<p>As adapted from <a href=\"http://blogs.msdn.com/erikaehrli/archive/2005/11/16/IndentXMLFilesandDocuments.aspx\" rel=\"noreferrer\">Erika Ehrli's</a> blog, this should do it:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\ndoc.LoadXml(\"&lt;item&gt;&lt;name&gt;wrench&lt;/name&gt;&lt;/item&gt;\");\n// Save the document to a file and auto-indent the output.\nusing (XmlTextWriter writer = new XmlTextWriter(\"data.xml\", null)) {\n writer.Formatting = Formatting.Indented;\n doc.Save(writer);\n}\n</code></pre>\n" }, { "answer_id": 203534, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 3, "selected": false, "text": "<pre><code>XmlTextWriter xw = new XmlTextWriter(writer);\nxw.Formatting = Formatting.Indented;\n</code></pre>\n" }, { "answer_id": 203581, "author": "Neil C. Obremski", "author_id": 9642, "author_profile": "https://Stackoverflow.com/users/9642", "pm_score": 9, "selected": true, "text": "<p>Based on the other answers, I looked into <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmltextwriter\" rel=\"noreferrer\"><code>XmlTextWriter</code></a> and came up with the following helper method:</p>\n\n<pre><code>static public string Beautify(this XmlDocument doc)\n{\n StringBuilder sb = new StringBuilder();\n XmlWriterSettings settings = new XmlWriterSettings\n {\n Indent = true,\n IndentChars = \" \",\n NewLineChars = \"\\r\\n\",\n NewLineHandling = NewLineHandling.Replace\n };\n using (XmlWriter writer = XmlWriter.Create(sb, settings)) {\n doc.Save(writer);\n }\n return sb.ToString();\n}\n</code></pre>\n\n<p>It's a bit more code than I hoped for, but it works just peachy.</p>\n" }, { "answer_id": 1417071, "author": "Uwe Keim", "author_id": 107625, "author_profile": "https://Stackoverflow.com/users/107625", "pm_score": 4, "selected": false, "text": "<p>If the above Beautify method is being called for an <code>XmlDocument</code> that already contains an <code>XmlProcessingInstruction</code> child node the following exception is thrown:</p>\n\n<blockquote>\n <p>Cannot write XML declaration.\n WriteStartDocument method has already\n written it.</p>\n</blockquote>\n\n<p>This is my modified version of the original one to get rid of the exception:</p>\n\n<pre><code>private static string beautify(\n XmlDocument doc)\n{\n var sb = new StringBuilder();\n var settings =\n new XmlWriterSettings\n {\n Indent = true,\n IndentChars = @\" \",\n NewLineChars = Environment.NewLine,\n NewLineHandling = NewLineHandling.Replace,\n };\n\n using (var writer = XmlWriter.Create(sb, settings))\n {\n if (doc.ChildNodes[0] is XmlProcessingInstruction)\n {\n doc.RemoveChild(doc.ChildNodes[0]);\n }\n\n doc.Save(writer);\n return sb.ToString();\n }\n}\n</code></pre>\n\n<p>It works for me now, probably you would need to scan all child nodes for the <code>XmlProcessingInstruction</code> node, not just the first one?</p>\n\n<hr>\n\n<p><strong>Update April 2015:</strong></p>\n\n<p>Since I had another case where the encoding was wrong, I searched for how to enforce UTF-8 without BOM. I found <a href=\"http://www.timvw.be/2007/01/08/generating-utf-8-with-systemxmlxmlwriter/\" rel=\"noreferrer\">this blog post</a> and created a function based on it:</p>\n\n<pre><code>private static string beautify(string xml)\n{\n var doc = new XmlDocument();\n doc.LoadXml(xml);\n\n var settings = new XmlWriterSettings\n {\n Indent = true,\n IndentChars = \"\\t\",\n NewLineChars = Environment.NewLine,\n NewLineHandling = NewLineHandling.Replace,\n Encoding = new UTF8Encoding(false)\n };\n\n using (var ms = new MemoryStream())\n using (var writer = XmlWriter.Create(ms, settings))\n {\n doc.Save(writer);\n var xmlString = Encoding.UTF8.GetString(ms.ToArray());\n return xmlString;\n }\n}\n</code></pre>\n" }, { "answer_id": 3947518, "author": "Jonathan Mitchem", "author_id": 104523, "author_profile": "https://Stackoverflow.com/users/104523", "pm_score": 4, "selected": false, "text": "<p>A shorter extension method version</p>\n\n<pre><code>public static string ToIndentedString( this XmlDocument doc )\n{\n var stringWriter = new StringWriter(new StringBuilder());\n var xmlTextWriter = new XmlTextWriter(stringWriter) {Formatting = Formatting.Indented};\n doc.Save( xmlTextWriter );\n return stringWriter.ToString();\n}\n</code></pre>\n" }, { "answer_id": 11396054, "author": "Munim", "author_id": 981001, "author_profile": "https://Stackoverflow.com/users/981001", "pm_score": 2, "selected": false, "text": "<p>A simple way is to use:</p>\n\n<pre><code>writer.WriteRaw(space_char);\n</code></pre>\n\n<p>Like this sample code, this code is what I used to create a tree view like structure using XMLWriter :</p>\n\n<pre><code>private void generateXML(string filename)\n {\n using (XmlWriter writer = XmlWriter.Create(filename))\n {\n writer.WriteStartDocument();\n //new line\n writer.WriteRaw(\"\\n\");\n writer.WriteStartElement(\"treeitems\");\n //new line\n writer.WriteRaw(\"\\n\");\n foreach (RootItem root in roots)\n {\n //indent\n writer.WriteRaw(\"\\t\");\n writer.WriteStartElement(\"treeitem\");\n writer.WriteAttributeString(\"name\", root.name);\n writer.WriteAttributeString(\"uri\", root.uri);\n writer.WriteAttributeString(\"fontsize\", root.fontsize);\n writer.WriteAttributeString(\"icon\", root.icon);\n if (root.children.Count != 0)\n {\n foreach (ChildItem child in children)\n {\n //indent\n writer.WriteRaw(\"\\t\");\n writer.WriteStartElement(\"treeitem\");\n writer.WriteAttributeString(\"name\", child.name);\n writer.WriteAttributeString(\"uri\", child.uri);\n writer.WriteAttributeString(\"fontsize\", child.fontsize);\n writer.WriteAttributeString(\"icon\", child.icon);\n writer.WriteEndElement();\n //new line\n writer.WriteRaw(\"\\n\");\n }\n }\n writer.WriteEndElement();\n //new line\n writer.WriteRaw(\"\\n\");\n }\n\n writer.WriteEndElement();\n writer.WriteEndDocument();\n\n }\n\n }\n</code></pre>\n\n<p>This way you can add tab or line breaks in the way you are normally used to, i.e. \\t or \\n</p>\n" }, { "answer_id": 11582762, "author": "JFK", "author_id": 851774, "author_profile": "https://Stackoverflow.com/users/851774", "pm_score": 5, "selected": false, "text": "<p>Or even easier if you have access to Linq</p>\n\n<pre><code>try\n{\n RequestPane.Text = System.Xml.Linq.XElement.Parse(RequestPane.Text).ToString();\n}\ncatch (System.Xml.XmlException xex)\n{\n displayException(\"Problem with formating text in Request Pane: \", xex);\n}\n</code></pre>\n" }, { "answer_id": 16524516, "author": "Nyerguds", "author_id": 395685, "author_profile": "https://Stackoverflow.com/users/395685", "pm_score": 2, "selected": false, "text": "<p>When implementing the suggestions posted here, I had trouble with the text encoding. It seems the encoding of the <code>XmlWriterSettings</code> is ignored, and always overridden by the encoding of the stream. When using a <code>StringBuilder</code>, this is always the text encoding used internally in C#, namely UTF-16.</p>\n\n<p>So here's a version which supports other encodings as well.</p>\n\n<p>IMPORTANT NOTE: The formatting is completely ignored if your <code>XMLDocument</code> object has its <code>preserveWhitespace</code> property enabled when loading the document. This had me stumped for a while, so make sure not to enable that.</p>\n\n<p>My final code:</p>\n\n<pre><code>public static void SaveFormattedXml(XmlDocument doc, String outputPath, Encoding encoding)\n{\n XmlWriterSettings settings = new XmlWriterSettings();\n settings.Indent = true;\n settings.IndentChars = \"\\t\";\n settings.NewLineChars = \"\\r\\n\";\n settings.NewLineHandling = NewLineHandling.Replace;\n\n using (MemoryStream memstream = new MemoryStream())\n using (StreamWriter sr = new StreamWriter(memstream, encoding))\n using (XmlWriter writer = XmlWriter.Create(sr, settings))\n using (FileStream fileWriter = new FileStream(outputPath, FileMode.Create))\n {\n if (doc.ChildNodes.Count &gt; 0 &amp;&amp; doc.ChildNodes[0] is XmlProcessingInstruction)\n doc.RemoveChild(doc.ChildNodes[0]);\n // save xml to XmlWriter made on encoding-specified text writer\n doc.Save(writer);\n // Flush the streams (not sure if this is really needed for pure mem operations)\n writer.Flush();\n // Write the underlying stream of the XmlWriter to file.\n fileWriter.Write(memstream.GetBuffer(), 0, (Int32)memstream.Length);\n }\n}\n</code></pre>\n\n<p>This will save the formatted xml to disk, with the given text encoding.</p>\n" }, { "answer_id": 24659519, "author": "theJerm", "author_id": 118191, "author_profile": "https://Stackoverflow.com/users/118191", "pm_score": 1, "selected": false, "text": "<p>If you have a string of XML, rather than a doc ready for use, you can do it this way:</p>\n\n<pre><code>var xmlString = \"&lt;xml&gt;...&lt;/xml&gt;\"; // Your original XML string that needs indenting.\nxmlString = this.PrettifyXml(xmlString);\n\nprivate string PrettifyXml(string xmlString)\n{\n var prettyXmlString = new StringBuilder();\n\n var xmlDoc = new XmlDocument();\n xmlDoc.LoadXml(xmlString);\n\n var xmlSettings = new XmlWriterSettings()\n {\n Indent = true,\n IndentChars = \" \",\n NewLineChars = \"\\r\\n\",\n NewLineHandling = NewLineHandling.Replace\n };\n\n using (XmlWriter writer = XmlWriter.Create(prettyXmlString, xmlSettings))\n {\n xmlDoc.Save(writer);\n }\n\n return prettyXmlString.ToString();\n}\n</code></pre>\n" }, { "answer_id": 26963811, "author": "rewrew", "author_id": 4029290, "author_profile": "https://Stackoverflow.com/users/4029290", "pm_score": 3, "selected": false, "text": "<pre><code> public static string FormatXml(string xml)\n {\n try\n {\n var doc = XDocument.Parse(xml);\n return doc.ToString();\n }\n catch (Exception)\n {\n return xml;\n }\n }\n</code></pre>\n" }, { "answer_id": 45983263, "author": "d.i.joe", "author_id": 2450402, "author_profile": "https://Stackoverflow.com/users/2450402", "pm_score": 1, "selected": false, "text": "<p>A more simplified approach based on the accepted answer:</p>\n\n<pre><code>static public string Beautify(this XmlDocument doc) {\n StringBuilder sb = new StringBuilder();\n XmlWriterSettings settings = new XmlWriterSettings\n {\n Indent = true\n };\n\n using (XmlWriter writer = XmlWriter.Create(sb, settings)) {\n doc.Save(writer);\n }\n\n return sb.ToString(); \n}\n</code></pre>\n\n<p>Setting the new line is not necessary. Indent characters also has the default two spaces so I preferred not to set it as well.</p>\n" }, { "answer_id": 74262094, "author": "cSharper", "author_id": 19148480, "author_profile": "https://Stackoverflow.com/users/19148480", "pm_score": 0, "selected": false, "text": "<p>Set <strong>PreserveWhitespace</strong> to <strong>true</strong> before <strong>Load</strong>.</p>\n<pre><code>var document = new XmlDocument();\ndocument.PreserveWhitespace = true;\ndocument.Load(filename);\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
When I build XML up from scratch with `XmlDocument`, the `OuterXml` property already has everything nicely indented with line breaks. However, if I call `LoadXml` on some very "compressed" XML (no line breaks or indention) then the output of `OuterXml` stays that way. So ... What is the simplest way to get beautified XML output from an instance of `XmlDocument`?
Based on the other answers, I looked into [`XmlTextWriter`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmltextwriter) and came up with the following helper method: ``` static public string Beautify(this XmlDocument doc) { StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace }; using (XmlWriter writer = XmlWriter.Create(sb, settings)) { doc.Save(writer); } return sb.ToString(); } ``` It's a bit more code than I hoped for, but it works just peachy.
203,548
<p>I've been getting this undefined symbol building with this command line:</p> <pre><code>$ gcc test.cpp Undefined symbols: "___gxx_personality_v0", referenced from: etc... </code></pre> <p>test.cpp is simple and should build fine. What is the deal?</p>
[ { "answer_id": 203550, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 7, "selected": true, "text": "<p>Use</p>\n\n<pre><code>g++ test.cpp\n</code></pre>\n\n<p>instead, since this is c++ code.</p>\n\n<hr>\n\n<p>Or, if you <em>really</em> want to use <code>gcc</code>, add <code>-lstdc++</code> to the command line, like so:</p>\n\n<pre><code>gcc test.cpp -lstdc++\n</code></pre>\n\n<p>Running <code>md5</code> against the <code>a.out</code> produced under each scenario shows that it's the same output.</p>\n\n<p>But, yeah, <code>g++</code> probably makes your world a simpler place.</p>\n" }, { "answer_id": 1626030, "author": "pseudosudo", "author_id": 196678, "author_profile": "https://Stackoverflow.com/users/196678", "pm_score": 2, "selected": false, "text": "<p>The <code>.cpp</code> extension causes <code>gcc</code> to compile your file as a C++ file. (See the <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Overall-Options.html#index-file-name-suffix-71\" rel=\"nofollow noreferrer\">GCC docs</a>.)</p>\n\n<p>Try compiling the same file, but rename it to have a <code>.c</code> extension:</p>\n\n<pre><code>mv test.cpp\ngcc test.c\n</code></pre>\n\n<p>Alternatively, you can explicitly specify the language by passing <code>-x c</code> to the compiler:</p>\n\n<pre><code>gcc -x c -c test.cpp -o test.o\n</code></pre>\n\n<hr>\n\n<p>If you run <code>nm test.o</code> on these C-language versions, you'll notice that <code>___gxx_personality_v0</code> is not listed as a symbol.<br>\n(And if you run the same command on an object file generated with <code>gcc -c test.cpp -o test.o</code>, the <code>___gxx_personality_v0</code> symbol is present.)</p>\n" }, { "answer_id": 4340486, "author": "inket", "author_id": 528645, "author_profile": "https://Stackoverflow.com/users/528645", "pm_score": 2, "selected": false, "text": "<p>Just in case anyone has the same problem as me: The file extension should be a <code>.c</code> not a <code>.C</code> (gcc is case-sensitive).</p>\n" }, { "answer_id": 18518648, "author": "BadPirate", "author_id": 285694, "author_profile": "https://Stackoverflow.com/users/285694", "pm_score": 2, "selected": false, "text": "<p>Had the same problem, but a different solution:</p>\n\n<p>C++ code in static library getting linked, and being referenced by a .m file. Renaming the .m file to .mm fixed the issue.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13728/" ]
I've been getting this undefined symbol building with this command line: ``` $ gcc test.cpp Undefined symbols: "___gxx_personality_v0", referenced from: etc... ``` test.cpp is simple and should build fine. What is the deal?
Use ``` g++ test.cpp ``` instead, since this is c++ code. --- Or, if you *really* want to use `gcc`, add `-lstdc++` to the command line, like so: ``` gcc test.cpp -lstdc++ ``` Running `md5` against the `a.out` produced under each scenario shows that it's the same output. But, yeah, `g++` probably makes your world a simpler place.
203,589
<p>I have an iPhone app that compiles and runs fine in the Simulator on my laptop. Now, I try to build and run the same code in the Simulator on an iMac, and it starts up and lets me click a button, but then I get an assertion failure.</p> <p>Here is what is in the console:</p> <pre><code>*** Assertion failure in -[UILabel setFont:], /SourceCache/UIKit/UIKit-738/UILabel.m:438 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: font != nil' Stack: ( 2493366603, 2432871995, 2493366059, 2459146836, 817183141, 817926218, 837317240, 837317032, 837315376, 837314643, 2492860866, 2492867620, 2492869880, 85304, 85501, 816175835, 816221412, 9096, 8930 ) </code></pre> <p>Here's the stack trace:</p> <pre><code>#0 0x949dbff4 in ___TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___ #1 0x9102ae3b in objc_exception_throw #2 0x94962ad3 in CFRunLoopRunSpecific #3 0x94962cf8 in CFRunLoopRunInMode #4 0x00014d38 in GSEventRunModal #5 0x00014dfd in GSEventRun #6 0x30a5dadb in -[UIApplication _run] #7 0x30a68ce4 in UIApplicationMain #8 0x00002388 in main at main.m:16 </code></pre> <p>My code does not make any direct calls to setFont:. However, this would be the point in the program's execution where some buttons are made visible for the first time.</p> <p>I've Googled. A few people with similar problems say that this gets magically fixed when they edit the NIB, or change their time zone, or other weirdness.</p> <p>Any ideas what the real cause is?</p> <p>(Please no whining about NDA's.)</p> <hr> <p><strong>Update:</strong> If I change the font of some of my buttons from "TimesNewRomanPS-BoldMT" to "Times", then the assertion failure no longer occurs. But why can't I use the desired font, which exists on the iPhone, is installed on the new machine, and is selectable in Interface Builder?</p>
[ { "answer_id": 203663, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": true, "text": "<p>If you've got UILabels in your xib file, they may be somehow corrupt, or you may have set a font to them that doesn't exist on both your machines (you can use command-T when editing a UILabel to bring up the font picker; not sure it's possible to set a non-iPhone font, but it may be). Otherwise, try removing UILabels from your xib file until it runs, and there's your culprit.</p>\n" }, { "answer_id": 597770, "author": "William Denniss", "author_id": 72176, "author_profile": "https://Stackoverflow.com/users/72176", "pm_score": 1, "selected": false, "text": "<p>And if it's not a UILabel, it may be a UIButton (which contains a UILable), etc.</p>\n" }, { "answer_id": 1124578, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Not all are available in the iphone, only certain fonts.</p>\n" }, { "answer_id": 3643959, "author": "user439791", "author_id": 439791, "author_profile": "https://Stackoverflow.com/users/439791", "pm_score": 1, "selected": false, "text": "<p>Had the same issue but in a special situation. Only when code was compiled for iOS 4 but deployed on device with 3.1.3 Removed Arial-Narrow and it worked.</p>\n" }, { "answer_id": 10255142, "author": "user102008", "author_id": 102008, "author_profile": "https://Stackoverflow.com/users/102008", "pm_score": 0, "selected": false, "text": "<p>We ran into this problem because we used <code>[UIFont fontWithName:fontSize:]</code> with the name <code>Helvatica Bold</code> (with a space) instead of <code>Helvetica-Bold</code> (with a dash). <code>Helvatica Bold</code> apparently works on current OS versions, but not on iOS 3.1. <code>Helvetica-Bold</code> seems to be the correct version.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
I have an iPhone app that compiles and runs fine in the Simulator on my laptop. Now, I try to build and run the same code in the Simulator on an iMac, and it starts up and lets me click a button, but then I get an assertion failure. Here is what is in the console: ``` *** Assertion failure in -[UILabel setFont:], /SourceCache/UIKit/UIKit-738/UILabel.m:438 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: font != nil' Stack: ( 2493366603, 2432871995, 2493366059, 2459146836, 817183141, 817926218, 837317240, 837317032, 837315376, 837314643, 2492860866, 2492867620, 2492869880, 85304, 85501, 816175835, 816221412, 9096, 8930 ) ``` Here's the stack trace: ``` #0 0x949dbff4 in ___TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___ #1 0x9102ae3b in objc_exception_throw #2 0x94962ad3 in CFRunLoopRunSpecific #3 0x94962cf8 in CFRunLoopRunInMode #4 0x00014d38 in GSEventRunModal #5 0x00014dfd in GSEventRun #6 0x30a5dadb in -[UIApplication _run] #7 0x30a68ce4 in UIApplicationMain #8 0x00002388 in main at main.m:16 ``` My code does not make any direct calls to setFont:. However, this would be the point in the program's execution where some buttons are made visible for the first time. I've Googled. A few people with similar problems say that this gets magically fixed when they edit the NIB, or change their time zone, or other weirdness. Any ideas what the real cause is? (Please no whining about NDA's.) --- **Update:** If I change the font of some of my buttons from "TimesNewRomanPS-BoldMT" to "Times", then the assertion failure no longer occurs. But why can't I use the desired font, which exists on the iPhone, is installed on the new machine, and is selectable in Interface Builder?
If you've got UILabels in your xib file, they may be somehow corrupt, or you may have set a font to them that doesn't exist on both your machines (you can use command-T when editing a UILabel to bring up the font picker; not sure it's possible to set a non-iPhone font, but it may be). Otherwise, try removing UILabels from your xib file until it runs, and there's your culprit.
203,591
<p>My SQL is a bit rusty -- is there a SQL way to project an input table that looks something like this:</p> <pre><code>Name SlotValue Slots ---- --------- ----- ABC 3 1 ABC 4 2 ABC 6 5 </code></pre> <p>Into a 'projected' result table that looks like this:</p> <pre><code>Name SlotSum Slot ---- ------- ---- ABC 13 1 ABC 10 2 ABC 6 3 ABC 6 4 ABC 6 5 </code></pre> <p>In other words, the result set should contain a number of rows equal to MAX(Slots), enumerated (Slot) from 1 to MAX(Slots), and Sum for each of these 'slots' should reflect the sum of the SlotValues projected out to the 'Slots' position. for the pathological case:</p> <pre><code>Name SlotValue Slots ---- --------- ----- ABC 4 3 </code></pre> <p>we should get:</p> <pre><code>Name SlotSum Slot ---- ------- ---- ABC 4 1 ABC 4 2 ABC 4 3 </code></pre> <p>The summation logic is pretty straightforward -- project each SlotValue out to the number of Slots:</p> <pre><code>SlotValue SlotValue SlotValue Slot Sum --------- --------- --------- ---- --- 3 4 6 1 13 (3+4+6) 0 4 6 2 10 (0+4+6) 0 0 6 3 6 (0+0+6) 0 0 6 4 6 (0+0+6) 0 0 6 5 6 (0+0+6) </code></pre> <p>UPDATE: In the end I used a variant of LOCALGHOST's approach in a stored proc. I was hoping there might be a way to do this without a loop.</p>
[ { "answer_id": 203608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p><img src=\"https://www.lemurproject.org/images/VS_Net_AdditionalIncludes.jpg\" alt=\"alt text\"></p>\n" }, { "answer_id": 203693, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 0, "selected": false, "text": "<p>Strangely I don't see that option. I ended up opening the vcproj file in jedit and writing it in. </p>\n\n<p><a href=\"http://img88.imageshack.us/img88/1128/idontknowmanln2.jpg\" rel=\"nofollow noreferrer\">idontknow http://img88.imageshack.us/img88/1128/idontknowmanln2.jpg</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18482/" ]
My SQL is a bit rusty -- is there a SQL way to project an input table that looks something like this: ``` Name SlotValue Slots ---- --------- ----- ABC 3 1 ABC 4 2 ABC 6 5 ``` Into a 'projected' result table that looks like this: ``` Name SlotSum Slot ---- ------- ---- ABC 13 1 ABC 10 2 ABC 6 3 ABC 6 4 ABC 6 5 ``` In other words, the result set should contain a number of rows equal to MAX(Slots), enumerated (Slot) from 1 to MAX(Slots), and Sum for each of these 'slots' should reflect the sum of the SlotValues projected out to the 'Slots' position. for the pathological case: ``` Name SlotValue Slots ---- --------- ----- ABC 4 3 ``` we should get: ``` Name SlotSum Slot ---- ------- ---- ABC 4 1 ABC 4 2 ABC 4 3 ``` The summation logic is pretty straightforward -- project each SlotValue out to the number of Slots: ``` SlotValue SlotValue SlotValue Slot Sum --------- --------- --------- ---- --- 3 4 6 1 13 (3+4+6) 0 4 6 2 10 (0+4+6) 0 0 6 3 6 (0+0+6) 0 0 6 4 6 (0+0+6) 0 0 6 5 6 (0+0+6) ``` UPDATE: In the end I used a variant of LOCALGHOST's approach in a stored proc. I was hoping there might be a way to do this without a loop.
![alt text](https://www.lemurproject.org/images/VS_Net_AdditionalIncludes.jpg)
203,605
<p>I'm looking for a way to match only fully composed characters in a Unicode string.</p> <p>Is <code>[:print:]</code> dependent upon locale in any regular expression implementation that incorporates this character class? For example, will it match Japanese character 'あ', since it is not a control character, or is <code>[:print:]</code> always going to be ASCII codes 0x20 to 0x7E?</p> <p>Is there any character class, including Perl REs, that can be used to match anything other than a control character? If <code>[:print:]</code> includes only characters in ASCII range I would assume <code>[:cntrl:]</code> does too.</p>
[ { "answer_id": 203606, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>Yes, those expressions are locale dependant.</p>\n" }, { "answer_id": 203623, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "<p>You could always use the character class <code>[^[:cntrl:]]</code> to match non-control characters.</p>\n" }, { "answer_id": 203801, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 4, "selected": true, "text": "<pre><code>echo あ| perl -nle 'BEGIN{binmode STDIN,\":utf8\"} print\"[$_]\"; print /[[:print:]]/ ? \"YES\" : \"NO\"'\n</code></pre>\n\n<p>This mostly works, though it generates a warning about a wide character. But it gives you the idea: you must be sure you're dealing with a real unicode string (check utf8::is_utf8). Or just check <a href=\"http://search.cpan.org/~tty/kurila-1.14_0/pod/perlunicode.pod\" rel=\"noreferrer\" title=\"perlunicode\">perlunicode</a> at all - the whole subject still makes my head spin.</p>\n" }, { "answer_id": 203894, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": "<p>I think you don't want or need locales for that but, but rather Unicode. If you have decoded a text string, <code>\\w</code> will match word characters in any language, <code>\\d</code> matches not just <code>0..9</code> but every Unicode digit etc. In regexes you can query Unicode properties with <code>\\p{PropertyName}</code>. Particularly interesting for you might be <code>\\p{Print}</code>. <a href=\"http://perldoc.perl.org/perluniprops.html\" rel=\"nofollow noreferrer\">Here's a list of all the available Unicode character properties</a>.</p>\n\n<p>I wrote an <a href=\"http://perlgeek.de/en/article/encodings-and-unicode\" rel=\"nofollow noreferrer\">article about the basics and subtleties of Unicode and Perl</a>, it should give you a good idea on what to do that perl will recognize your string as a sequence of characters, not just a sequence of bytes.</p>\n\n<p>Update: with Unicode you don't get language dependent behaviour, but instead sane defaults regardless of language. This may or may not be what you want, but for the distinction of priintable/control character I don't see why you'd need language dependent behaviour.</p>\n" }, { "answer_id": 2024396, "author": "daxim", "author_id": 46395, "author_profile": "https://Stackoverflow.com/users/46395", "pm_score": 2, "selected": false, "text": "<p><code>\\X</code> matches a fully-composed character (sequence). Proof:</p>\n\n<pre><code>#!/usr/bin/env perl\nuse 5.010;\nuse utf8;\nuse Encode qw(encode_utf8);\n\nfor my $string (qw(あ ご ご), \"\\x{3099}\") {\n say encode_utf8 sprintf \"%s $string\", $string =~ /\\A \\X \\z/msx ? 'ok' : 'nok';\n}\n</code></pre>\n\n<p>The test data are: a normal character, a pre-combined character, a combining character sequence and a combining character (which \"doesn't count\" on its own, a simplification of Chapter 3 of Unicode).</p>\n\n<p>Substitute <code>\\X</code> with <code>[[:print:]]</code> to see that Tanktalus' answer produces false matches for the last two cases.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10320/" ]
I'm looking for a way to match only fully composed characters in a Unicode string. Is `[:print:]` dependent upon locale in any regular expression implementation that incorporates this character class? For example, will it match Japanese character 'あ', since it is not a control character, or is `[:print:]` always going to be ASCII codes 0x20 to 0x7E? Is there any character class, including Perl REs, that can be used to match anything other than a control character? If `[:print:]` includes only characters in ASCII range I would assume `[:cntrl:]` does too.
``` echo あ| perl -nle 'BEGIN{binmode STDIN,":utf8"} print"[$_]"; print /[[:print:]]/ ? "YES" : "NO"' ``` This mostly works, though it generates a warning about a wide character. But it gives you the idea: you must be sure you're dealing with a real unicode string (check utf8::is\_utf8). Or just check [perlunicode](http://search.cpan.org/~tty/kurila-1.14_0/pod/perlunicode.pod "perlunicode") at all - the whole subject still makes my head spin.
203,618
<ul> <li>What rules do you use to name your variables?</li> <li>Where are single letter vars allowed?</li> <li>How much info do you put in the name?</li> <li>How about for example code?</li> <li>What are your preferred meaningless variable names? (after foo &amp; bar)</li> <li>Why are they spelled <a href="http://en.wikipedia.org/wiki/Foobar" rel="nofollow noreferrer">"foo" and "bar"</a> rather than <a href="http://en.wikipedia.org/wiki/FUBAR" rel="nofollow noreferrer">FUBAR</a></li> </ul>
[ { "answer_id": 203632, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 0, "selected": false, "text": "<p>I would say try to name them as clearly as possible. Never use single letter variables and only use 'foo' and 'bar' if you're just testing something out (e.g., in interactive mode) and won't use it in production.</p>\n" }, { "answer_id": 203641, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p>locals: fooBar;\nmembers/types/functions FooBar\ninterfaces: IFooBar</p>\n\n<p>As for me, single letters are only valid if the name is classic; i/j/k for only for local loop indexes, x,y,z for vector parts.</p>\n\n<p>vars have names that convey meaning but are short enough to not wrap lines</p>\n\n<p>foo,bar,<em>baz</em>. Pickle is also a favorite.</p>\n" }, { "answer_id": 203642, "author": "JFV", "author_id": 1391, "author_profile": "https://Stackoverflow.com/users/1391", "pm_score": 0, "selected": false, "text": "<p>I like to prefix my variables with what they're going to be: str = String, int = Integer, bool = Boolean, etc.</p>\n\n<p>Using a single letter is quick and easy in Loops: For i = 0 to 4...Loop</p>\n\n<p>Variables are made to be a short but descriptive substitute for what you're using. If the variable is too short, you might not understand what it's for. If it's too long, you'll be typing forever for a variable that represents 5.</p>\n\n<p>Foo &amp; Bar are used for example code to show how the code works. You can use just about any different nonsensical characters to use instead. I usually just use i, x, &amp; y.</p>\n\n<p>My personal opinion of foo bar vs. fu bar is that it's too obvious and no one likes 2-character variables, 3 is much better!</p>\n" }, { "answer_id": 203648, "author": "Tony BenBrahim", "author_id": 80075, "author_profile": "https://Stackoverflow.com/users/80075", "pm_score": 6, "selected": false, "text": "<pre><code>function startEditing(){\n if (user.canEdit(currentDocument)){\n editorControl.setEditMode(true);\n setButtonDown(btnStartEditing);\n }\n }\n</code></pre>\n\n<p>Should read like a narrative work.</p>\n" }, { "answer_id": 203654, "author": "Craig", "author_id": 27294, "author_profile": "https://Stackoverflow.com/users/27294", "pm_score": 4, "selected": false, "text": "<p>Well it all depends on the language you are developing in. As I am currently using C# I tend you use the following.</p>\n\n<p>camelCase for variables.</p>\n\n<p>camelCase for parameters.</p>\n\n<p>PascalCase for properties.</p>\n\n<p>m_PascalCase for member variables.</p>\n\n<p><strong>Where are single letter vars allows?</strong>\nI tend to do this in for loops but feel a bit guilty whenever I do so. But with foreach and lambda expressions for loops are not really that common now. </p>\n\n<p><strong>How much info do you put in the name?</strong>\nIf the code is a bit difficult to understand write a comment. Don't turn a variable name into a comment, i.e .\n<code>int theTotalAccountValueIsStoredHere</code>\nis not required.</p>\n\n<p><strong>what are your preferred meaningless variable names?</strong> <strong>(after foo &amp; bar)</strong>\ni or x. foo and bar are a bit too university text book example for me.</p>\n\n<p><strong>why are they spelled \"foo\" and \"bar\" rather than FUBAR?</strong>\nTradition</p>\n" }, { "answer_id": 203661, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 2, "selected": false, "text": "<ul>\n<li>I only use single character variables for loop control or very short functions.</li>\n</ul>\n<blockquote>\n<pre><code>for(int i = 0; i&lt; endPoint; i++) {...}\n\nint max( int a, int b) {\n if (a &gt; b)\n return a;\n return b;\n}\n</code></pre>\n</blockquote>\n<ul>\n<li>The amount of information depends on the scope of the variable, the more places it could be used, the more information I want to have the name to keep track of its purpose.</li>\n<li>When I write example code, I try to use variable names as I would in real code (although functions might get useless names like foo or bar).</li>\n<li>See <a href=\"http://www.ietf.org/rfc/rfc3092.txt\" rel=\"nofollow noreferrer\">Etymology of &quot;Foo&quot;</a></li>\n</ul>\n" }, { "answer_id": 203666, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 0, "selected": false, "text": "<p>In DSLs and other fluent interfaces often variable- and method-name taken together form a lexical entity. For example, I personally like the (admittedly heretic) naming pattern where the verb is put into the variable name rather than the method name. @see <a href=\"http://www.iam.unibe.ch/~akuhn/blog/2008/07/read-aloud-naming/\" rel=\"nofollow noreferrer\">6th Rule of Variable Naming</a></p>\n\n<p>Also, I like the spartan use of <code>$</code> as variable name for the main variable of a piece of code. For example, a class that pretty prints a tree structure can use <code>$</code> for the StringBuffer inst var. @see <a href=\"http://www.iam.unibe.ch/~akuhn/blog/2008/09/this-is-verbose/\" rel=\"nofollow noreferrer\">This is Verbose!</a></p>\n\n<p>Otherwise I refer to the Programmer's Phrasebook by Einar Hoest. @see <a href=\"http://www.nr.no/~einarwh/phrasebook/\" rel=\"nofollow noreferrer\">http://www.nr.no/~einarwh/phrasebook/</a></p>\n" }, { "answer_id": 203671, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 1, "selected": false, "text": "<p><b>What rules do you use to name your variables?</b> I've switched between underscore between words (load_vars), camel casing (loadVars) and no spaces (loadvars). Classes are always CamelCase, capitalized. </p>\n\n<p><b> Where are single letter vars allows?</b> Loops, mostly. Temporary vars in throwaway code.</p>\n\n<p><b> How much info do you put in the name?</b> Enough to remind me what it is while I'm coding. (Yes this can lead to problems later!)</p>\n\n<p><b> what are your preferred meaningless variable names? (after foo &amp; bar)</b> temp, res, r. I actually don't use foo and bar a good amount.</p>\n" }, { "answer_id": 203682, "author": "hlfcoding", "author_id": 65465, "author_profile": "https://Stackoverflow.com/users/65465", "pm_score": -1, "selected": false, "text": "<p><strong>Updated</strong></p>\n\n<p>First off, naming depends on existing conventions, whether from language, framework, library, or project. (When in Rome...) Example: Use the <a href=\"http://docs.jquery.com/JQuery_Core_Style_Guidelines\" rel=\"nofollow noreferrer\">jQuery style</a> for jQuery plugins, use the <a href=\"https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html\" rel=\"nofollow noreferrer\">Apple style</a> for iOS apps. The former example requires more vigilance (since JavaScript can get messy and isn't automatically checked), while the latter example is simpler since the standard has been well-enforced and followed. YMMV depending on the leaders, the community, and especially the tools.</p>\n\n<p><strong>I will set aside all my naming habits to follow any existing conventions.</strong></p>\n\n<hr>\n\n<p>In general, I follow these principles, all of which center around programming being another form of <em>interpersonal communication through written language</em>.</p>\n\n<ul>\n<li><p><strong>Readability</strong> - important parts should have solid names; but these names should not be a replacement for proper documentation of <em>intent</em>. The test for code readability is if you can come back to it months later and still be understanding enough to not toss the entire thing upon first impression. This means avoiding abbreviation; see <a href=\"http://www.folklore.org/StoryView.py?project=Macintosh&amp;story=Hungarian.txt\" rel=\"nofollow noreferrer\">the case against Hungarian notation</a>.</p></li>\n<li><p><strong>Writeability</strong> - common areas and boilerplate should be kept simple (esp. if there's no IDE), so code is easier and more fun to write. This is a bit inspired by <a href=\"http://doc.cat-v.org/bell_labs/pikestyle\" rel=\"nofollow noreferrer\">Rob Pyke's style</a>.</p></li>\n<li><p><strong>Maintainability</strong> - if I add the type to my name like <code>arrItems</code>, then it would suck if I changed that property to be an instance of a <code>CustomSet</code> class that extends <code>Array</code>. Type notes should be kept in documentation, and only if appropriate (for APIs and such).</p></li>\n<li><p><strong>Standard, common naming</strong> - For dumb environments (text editors): Classes should be in <code>ProperCase</code>, variables should be short and if needed be in <code>snake_case</code> and functions should be in <code>camelCase</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>For JavaScript, it's a classic case of the restraints of the language and the tools affecting naming. It helps to distinguish variables from functions through different naming, since there's no IDE to hold your hand while <code>this</code> and <code>prototype</code> and other boilerplate obscure your vision and confuse your differentiation skills. It's also not uncommon to see all the unimportant or globally-derived vars in a scope be abbreviated. The language has no <code>import [path] as [alias];</code>, so local vars become aliases. And then there's the slew of different whitespacing conventions. The only solution here (and anywhere, really) is proper documentation of intent (and identity).</p>\n\n<p>Also, the language itself is based around function level scope and closures, so that amount of flexibility can make blocks with variables in 2+ scope levels feel very messy, so I've seen naming where <code>_</code> is prepended for each level in the scope chain to the vars in that scope.</p>\n" }, { "answer_id": 203688, "author": "HappyCodeMonkey", "author_id": 15875, "author_profile": "https://Stackoverflow.com/users/15875", "pm_score": 0, "selected": false, "text": "<p>I always use single letter variables in for loops, it's just nicer-looking and easier to read. </p>\n\n<p>A lot of it depends on the language you're programming in too, I don't name variables the same in C++ as I do in Java (Java lends itself better to the excessively long variable names imo, but this could just a personal preference. Or it may have something to do with how Java built-ins are named...).</p>\n" }, { "answer_id": 203725, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 4, "selected": false, "text": "<p>One rule I always follow is this: if a variable encodes a value that is in some particular units, then those units have to be part of the variable name. Example:</p>\n\n<pre><code>int postalCodeDistanceMiles;\ndecimal reactorCoreTemperatureKelvin;\ndecimal altitudeMsl;\nint userExperienceWongBakerPainScale\n</code></pre>\n\n<p>I will NOT be responsible for crashing any Mars landers (or the equivalent failure in my boring CRUD business applications).</p>\n" }, { "answer_id": 203734, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 0, "selected": false, "text": "<p>I learned not to ever use single-letter variable names back in my VB3 days. The problem is that if you want to search everywhere that a variable is used, it's kinda hard to search on a single letter!</p>\n\n<p>The newer versions of Visual Studio have intelligent variable searching functions that avoid this problem, but old habits and all that. Anyway, I prefer to err on the side of ridiculous.</p>\n\n<pre><code>for (int firstStageRocketEngineIndex = 0; firstStageRocketEngineIndex &lt; firstStageRocketEngines.Length; firstStageRocketEngineIndex++)\n{\n firstStageRocketEngines[firstStageRocketEngineIndex].Ignite();\n Thread.Sleep(100); // Don't start them all at once. That would be bad.\n}\n</code></pre>\n" }, { "answer_id": 203743, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 1, "selected": false, "text": "<p>What rules do you use to name your variables?</p>\n\n<ul>\n<li>I need to be able to understand it in a year's time. Should also conform with preexisting style.</li>\n</ul>\n\n<p>Where are single letter vars allows?</p>\n\n<ul>\n<li>ultra-obvious things. E.g. char c; c = getc(); Loop indicies(i,j,k).</li>\n</ul>\n\n<p>How much info do you put in the name?</p>\n\n<ul>\n<li>Plenty and lots.</li>\n</ul>\n\n<p>how about for example code?</p>\n\n<ul>\n<li>Same as above.</li>\n</ul>\n\n<p>what are your preferred meaningless variable names? (after foo &amp; bar)</p>\n\n<ul>\n<li>I don't like having meaningless variable names. If a variable doesn't mean anything, why is it in my code?</li>\n</ul>\n\n<p>why are they spelled \"foo\" and \"bar\" rather than FUBAR</p>\n\n<ul>\n<li>Tradition.</li>\n</ul>\n" }, { "answer_id": 203753, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "<p>Pretty much every modern language that had wide use has its own coding standards. These are a great starting point. If all else fails, just use whatever is recommended. There are exceptions of course, but these are general guidelines. If your team prefers certain variations, as long as you agree with them, then that's fine as well.</p>\n\n<p>But at the end of the day it's not necessarily what standards you use, but the fact that you have them in the first place and that they are adhered to.</p>\n" }, { "answer_id": 203810, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": false, "text": "<p>These are all C# conventions.</p>\n\n<p><strong>Variable-name casing</strong></p>\n\n<p>Case indicates scope. Pascal-cased variables are fields of the owning class. Camel-cased variables are local to the current method. </p>\n\n<p>I have only one prefix-character convention. Backing fields for class properties are Pascal-cased and prefixed with an underscore:</p>\n\n<pre><code>private int _Foo;\npublic int Foo { get { return _Foo; } set { _Foo = value; } }\n</code></pre>\n\n<p>There's some C# variable-naming convention I've seen out there - I'm pretty sure it was a Microsoft document - that inveighs against using an underscore prefix. That seems crazy to me. If I look in my code and see something like</p>\n\n<pre><code>_Foo = GetResult();\n</code></pre>\n\n<p>the very first thing that I ask myself is, \"Did I have a good reason not to use a property accessor to update that field?\" The answer is often \"Yes, and you'd better know what that is before you start monkeying around with this code.\"</p>\n\n<p><strong>Single-letter (and short) variable names</strong></p>\n\n<p>While I tend to agree with the dictum that variable names should be meaningful, in practice there are lots of circumstances under which making their names meaningful adds nothing to the code's readability or maintainability.</p>\n\n<p>Loop iterators and array indices are the obvious places to use short and arbitrary variable names. Less obvious, but no less appropriate in my book, are nonce usages, e.g.:</p>\n\n<pre><code>XmlWriterSettings xws = new XmlWriterSettings();\nxws.Indent = true;\nXmlWriter xw = XmlWriter.Create(outputStream, xws);\n</code></pre>\n\n<p>That's from C# 2.0 code; if I wrote it today, of course, I wouldn't need the nonce variable:</p>\n\n<pre><code>XmlWriter xw = XmlWriter.Create(\n outputStream, \n new XmlWriterSettings() { Indent=true; });\n</code></pre>\n\n<p>But there are still plenty of places in C# code where I have to create an object that you're just going to pass elsewhere and then throw away.</p>\n\n<p>A lot of developers would use a name like <code>xwsTemp</code> in those circumstances. I find that the <code>Temp</code> suffix is redundant. The fact that I named the variable <code>xws</code> in its declaration (and I'm only using it within visual range of that declaration; that's important) tells me that it's a temporary variable.</p>\n\n<p>Another place I'll use short variable names is in a method that's making heavy use of a single object. Here's a piece of production code:</p>\n\n<pre><code> internal void WriteXml(XmlWriter xw)\n {\n if (!Active)\n {\n return;\n }\n xw.WriteStartElement(Row.Table.TableName);\n\n xw.WriteAttributeString(\"ID\", Row[\"ID\"].ToString());\n xw.WriteAttributeString(\"RowState\", Row.RowState.ToString());\n\n for (int i = 0; i &lt; ColumnManagers.Length; i++)\n {\n ColumnManagers[i].Value = Row.ItemArray[i];\n xw.WriteElementString(ColumnManagers[i].ColumnName, ColumnManagers[i].ToXmlString());\n }\n ...\n</code></pre>\n\n<p>There's no way in the world that code would be easier to read (or safer to modify) if I gave the XmlWriter a longer name.</p>\n\n<p>Oh, how do I know that <code>xw</code> isn't a temporary variable? Because I can't see its declaration. I only use temporary variables within 4 or 5 lines of their declaration. If I'm going to need one for more code than that, I either give it a meaningful name or refactor the code using it into a method that - hey, what a coincidence - takes the short variable as an argument.</p>\n\n<p><strong>How much info do you put in the name?</strong></p>\n\n<p>Enough. </p>\n\n<p>That turns out to be something of a black art. There's plenty of information I <em>don't</em> have to put into the name. I know when a variable's the backing field of a property accessor, or temporary, or an argument to the current method, because my naming conventions tell me that. So my names don't.</p>\n\n<p>Here's why it's not that important.</p>\n\n<p>In practice, I don't need to spend much energy figuring out variable names. I put all of that cognitive effort into naming types, properties and methods. This is a <em>much</em> bigger deal than naming variables, because these names are very often public in scope (or at least visible throughout the namespace). Names within a namespace need to convey meaning <em>the same way</em>.</p>\n\n<p>There's only one variable in this block of code:</p>\n\n<pre><code> RowManager r = (RowManager)sender;\n\n // if the settings allow adding a new row, add one if the context row\n // is the last sibling, and it is now active.\n if (Settings.AllowAdds &amp;&amp; r.IsLastSibling &amp;&amp; r.Active)\n {\n r.ParentRowManager.AddNewChildRow(r.RecordTypeRow, false);\n }\n</code></pre>\n\n<p>The property names almost make the comment redundant. (Almost. There's actually a reason why the property is called <code>AllowAdds</code> and not <code>AllowAddingNewRows</code> that a lot of thought went into, but it doesn't apply to this particular piece of code, which is why there's a comment.) The variable name? Who cares?</p>\n" }, { "answer_id": 203836, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 0, "selected": false, "text": "<p>It's pretty much unimportant how you name variables. You really don't need any rules, other than those specified by the language, or at minimum, those enforced by your compiler.</p>\n\n<p>It's considered polite to pick names you think your teammates can figure out, but style rules don't really help with that as much as people think.</p>\n" }, { "answer_id": 203906, "author": "AshtonKJ", "author_id": 24793, "author_profile": "https://Stackoverflow.com/users/24793", "pm_score": 2, "selected": false, "text": "<p><strong>What rules do you use to name your variables?</strong></p>\n\n<p>Typically, as I am a C# developer, I follow the variable naming conventions as specified by the <a href=\"http://www.idesign.net/idesign/download/IDesign%20CSharp%20Coding%20Standard.zip\" rel=\"nofollow noreferrer\">IDesign C# Coding Standard</a> for two reasons</p>\n\n<p>1) I like it, and find it easy to read.\n2) It is the default that comes with the <a href=\"http://joel.fjorden.se/static.php?page=CodeStyleEnforcer\" rel=\"nofollow noreferrer\" title=\"Code Style Enforcer Addin\">Code Style Enforcer AddIn for Visual Studio 2005 / 2008</a> which I use extensively these days.</p>\n\n<p><strong>Where are single letter vars allows?</strong></p>\n\n<p>There are a few places where I will allow single letter variables. Usually these are simple loop indexers, OR mathematical concepts like X,Y,Z coordinates. Other than that, never! (Everywhere else I have used them, I have typically been bitten by them when rereading the code).</p>\n\n<p><strong>How much info do you put in the name?</strong></p>\n\n<p>Enough to know PRECISELY what the variable is being used for. As Robert Martin says: </p>\n\n<blockquote>\n <p>The name of a variable, function, or\n class, should answer all the big\n questions. It should tell you why it\n exists, what it does, and how it is\n used. If a name requires a comment,\n then the name does not reveal its\n intent.\n From <em>Clean Code - A Handbook of Agile Software Craftsmanship</em></p>\n</blockquote>\n" }, { "answer_id": 203986, "author": "CaRDiaK", "author_id": 15628, "author_profile": "https://Stackoverflow.com/users/15628", "pm_score": 1, "selected": false, "text": "<p>The rules I adhere to are; </p>\n\n<p>Does the name fully and accurately describe what the variable represents? </p>\n\n<p>Does the name refer to the real-world problem rather than the programming language solution? </p>\n\n<p>Is the name long enough that you don't have to puzzle it out? </p>\n\n<p>Are computed value qualifiers, if any, at the end of the name?</p>\n\n<p>Are they specifically instantiated only at the point once required?</p>\n" }, { "answer_id": 204253, "author": "Ronald Conco", "author_id": 16092, "author_profile": "https://Stackoverflow.com/users/16092", "pm_score": -1, "selected": false, "text": "<p>I do a lot of php in nowadays, It was not always like that though and I have learned a couple of tricks when it comes to variable naming.</p>\n\n<p>//this is my string variable\n$strVar = \"\"; </p>\n\n<p>//this would represent an array\n$arrCards = array();</p>\n\n<p>//this is for an integer\n$intTotal = NULL:</p>\n\n<p>//object\n$objDB = new database_class();</p>\n\n<p>//boolean\n$blValid = true; </p>\n" }, { "answer_id": 215184, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>Since I work as a contractor, moving among different companies and projects, I prefer to avoid custom naming conventions. They make it more difficult for a new developer, or a maintenance developer, to become acquainted with (and follow) the standard being used.</p>\n\n<p>So, while one can find points in them to disagree with, I look to <a href=\"http://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"nofollow noreferrer\">the official Microsoft Net guidelines</a> for a consistent set of naming conventions. </p>\n\n<p>With some exceptions (Hungarian notation), I think consistent usage may be more useful than any arbitrary set of rules. That is, do it the same way every time.</p>\n\n<p>.</p>\n" }, { "answer_id": 217921, "author": "Alexander K", "author_id": 17592, "author_profile": "https://Stackoverflow.com/users/17592", "pm_score": 1, "selected": false, "text": "<p><strong>What rules do you use to name your variables?</strong>\ncamelCase for all important variables, CamelCase for all classes</p>\n\n<p><strong>Where are single letter vars allows?</strong>\n In loop constructs and in mathematical funktions where the single letter var name is consistent with the mathematical definition.</p>\n\n<p><strong>How much info do you put in the name?</strong>\n You should be able to read the code like a book. Function names should tell you what the function does (scalarProd(), addCustomer(), etc)</p>\n\n<p><strong>How about for example code?</strong></p>\n\n<p><strong>what are your preferred meaningless variable names? (after foo &amp; bar)</strong>\n temp, tmp, input, I never really use foo and bar.</p>\n" }, { "answer_id": 267592, "author": "Randy Stegbauer", "author_id": 34301, "author_profile": "https://Stackoverflow.com/users/34301", "pm_score": 2, "selected": false, "text": "<p>I never use meaningless variable names like foo or bar, unless, of course, the code is truly throw-away.</p>\n\n<p>For loop variables, I double up the letter so that it's easier to search for the variable within the file. For example,</p>\n\n<pre><code>for (int ii=0; ii &lt; array.length; ii++)\n{\n int element = array[ii];\n printf(\"%d\", element);\n}\n</code></pre>\n" }, { "answer_id": 18560003, "author": "user2650087", "author_id": 2650087, "author_profile": "https://Stackoverflow.com/users/2650087", "pm_score": 0, "selected": false, "text": "<ol>\n<li><strong>Use variables that describes clearly what it contains.</strong> If the class is going to get big, or if it is in the public scope the variable name needs to be described more accurately. Of course good naming makes you and other people understand the code better.</li>\n</ol>\n<ul>\n<li>for example: use &quot;employeeNumber&quot; insetead of just &quot;number&quot;.</li>\n<li>use Btn or Button in the end of the name of variables reffering to buttons, str for strings and so on.</li>\n</ul>\n<ol start=\"2\">\n<li><strong>Start variables with lower case, start classes with uppercase.</strong></li>\n</ol>\n<ul>\n<li>example of class &quot;MyBigClass&quot;, example of variable &quot;myStringVariable&quot;</li>\n</ul>\n<ol start=\"3\">\n<li><strong>Use upper case to indicate a new word for better readability.</strong> Don't use &quot;_&quot;, because it looks uglier and takes longer time to write.</li>\n</ol>\n<ul>\n<li>for example: use &quot;employeeName&quot;.</li>\n</ul>\n<ol start=\"4\">\n<li><strong>Only use single character variables in loops.</strong></li>\n</ol>\n" }, { "answer_id": 45758724, "author": "Igor Fomenko", "author_id": 6798809, "author_profile": "https://Stackoverflow.com/users/6798809", "pm_score": 0, "selected": false, "text": "<p>I work in MathCAD and I'm happy because MathCAD gives me increadable possibilities in naming and I use them a lot. And I can`t understand how to programm without this.\nTo differ one var from another I have to include a lot of information in the name,for example:</p>\n\n<p>1.On the first place - that is it -N for quantity,F for force and so on</p>\n\n<p>2.On the second - additional indices - for direction of force for example</p>\n\n<p>3.On the third - indexation inside vector or matrix var,for convinience I put var name in {} or [] brackets to show its dimensions.</p>\n\n<p>So,as conclusion my var name is like\nN.dirs / Fx i.row / {F}.w.(i,j.k) / {F}.w.(k,i.j).\nSometimes I have to add name of coordinate system for vector values\n{F}.{GCS}.w.(i,j.k) / {F}.{LCS}.w.(i,j.k)</p>\n\n<p>And as final step I add name of the external module in BOLD at the end of external function or var like Row.MTX.f([M]) because MathCAD doesn't have help string for function.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
* What rules do you use to name your variables? * Where are single letter vars allowed? * How much info do you put in the name? * How about for example code? * What are your preferred meaningless variable names? (after foo & bar) * Why are they spelled ["foo" and "bar"](http://en.wikipedia.org/wiki/Foobar) rather than [FUBAR](http://en.wikipedia.org/wiki/FUBAR)
``` function startEditing(){ if (user.canEdit(currentDocument)){ editorControl.setEditMode(true); setButtonDown(btnStartEditing); } } ``` Should read like a narrative work.
203,620
<p>I need ideas on how to go about table layout problem. I want to set different width of the columns dependent on the picked language.</p>
[ { "answer_id": 203626, "author": "Nrj", "author_id": 11614, "author_profile": "https://Stackoverflow.com/users/11614", "pm_score": 1, "selected": false, "text": "<p>Use if-else inside scriplet based on the currently selected language and place appropriate \"td\" tags.</p>\n\n<p>Hope this is what you are looking for !</p>\n" }, { "answer_id": 203647, "author": "cdeszaq", "author_id": 20770, "author_profile": "https://Stackoverflow.com/users/20770", "pm_score": 2, "selected": true, "text": "<p>A variable switch, such as:</p>\n\n<pre><code>&lt;%\ndim columnWidth\nif session(\"lang\") = \"eng\" then\n columnWidth = 50\nelse\n columnWidth = 100\nend if\n%&gt;\n\n&lt;table&gt;\n &lt;tr&gt;\n &lt;td width=\"&lt;%= columnWidth %&gt;px\"&gt;[content]&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>For c#, the code would be:</p>\n\n<pre><code>&lt;%\nprivate int columnWidth;\nif (session(\"lang\") == \"eng\") {\n columnWidth = 50;\n} else {\n columnWidth = 100;\n}\n%&gt;\n</code></pre>\n" }, { "answer_id": 203656, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 2, "selected": false, "text": "<p>You can have language specific CSS, and then simply load the appropriate CSS based on language.</p>\n\n<p>In the CSS you can add styles to your table for defining the layout.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
I need ideas on how to go about table layout problem. I want to set different width of the columns dependent on the picked language.
A variable switch, such as: ``` <% dim columnWidth if session("lang") = "eng" then columnWidth = 50 else columnWidth = 100 end if %> <table> <tr> <td width="<%= columnWidth %>px">[content]</td> </tr> </table> ``` For c#, the code would be: ``` <% private int columnWidth; if (session("lang") == "eng") { columnWidth = 50; } else { columnWidth = 100; } %> ```
203,629
<p>Has anyone used OSGi and JSF together?</p> <p>I ask because JSF uses class-loader magic to find custom components. From a tutorial (emphasis mine):</p> <blockquote> <p>This configuration file will end up being META-INF/faces-config.xml in the .jar file that represents this component. <strong>JSF will look for such a file name in each of the .jar files that are loaded at runtime</strong> (in the WEB-INF/lib directory for .war files) and use each of them in its configuration. In this way, multiple component .jar files can be combined into one web application, and all of the components described in each .jar will be available to the application.</p> </blockquote> <p>I would like to be able to have JSF custom components as OSGi bundles (i.e. custom components are in different OSGi bundles than the JSF runtime) and for JSF to be able to find these at runtime.</p> <p>Has anyone done anything similar?</p>
[ { "answer_id": 203626, "author": "Nrj", "author_id": 11614, "author_profile": "https://Stackoverflow.com/users/11614", "pm_score": 1, "selected": false, "text": "<p>Use if-else inside scriplet based on the currently selected language and place appropriate \"td\" tags.</p>\n\n<p>Hope this is what you are looking for !</p>\n" }, { "answer_id": 203647, "author": "cdeszaq", "author_id": 20770, "author_profile": "https://Stackoverflow.com/users/20770", "pm_score": 2, "selected": true, "text": "<p>A variable switch, such as:</p>\n\n<pre><code>&lt;%\ndim columnWidth\nif session(\"lang\") = \"eng\" then\n columnWidth = 50\nelse\n columnWidth = 100\nend if\n%&gt;\n\n&lt;table&gt;\n &lt;tr&gt;\n &lt;td width=\"&lt;%= columnWidth %&gt;px\"&gt;[content]&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>For c#, the code would be:</p>\n\n<pre><code>&lt;%\nprivate int columnWidth;\nif (session(\"lang\") == \"eng\") {\n columnWidth = 50;\n} else {\n columnWidth = 100;\n}\n%&gt;\n</code></pre>\n" }, { "answer_id": 203656, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 2, "selected": false, "text": "<p>You can have language specific CSS, and then simply load the appropriate CSS based on language.</p>\n\n<p>In the CSS you can add styles to your table for defining the layout.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
Has anyone used OSGi and JSF together? I ask because JSF uses class-loader magic to find custom components. From a tutorial (emphasis mine): > > This configuration file will end up > being META-INF/faces-config.xml in the > .jar file that represents this > component. **JSF will look for such a > file name in each of the .jar files > that are loaded at runtime** (in the > WEB-INF/lib directory for .war files) > and use each of them in its > configuration. In this way, multiple > component .jar files can be combined > into one web application, and all of > the components described in each .jar > will be available to the application. > > > I would like to be able to have JSF custom components as OSGi bundles (i.e. custom components are in different OSGi bundles than the JSF runtime) and for JSF to be able to find these at runtime. Has anyone done anything similar?
A variable switch, such as: ``` <% dim columnWidth if session("lang") = "eng" then columnWidth = 50 else columnWidth = 100 end if %> <table> <tr> <td width="<%= columnWidth %>px">[content]</td> </tr> </table> ``` For c#, the code would be: ``` <% private int columnWidth; if (session("lang") == "eng") { columnWidth = 50; } else { columnWidth = 100; } %> ```
203,677
<p>Just got a question about generics, why doesn't this compile when using a generic List? If its not possible, anyway around it? Much appreciate any answer.</p> <pre><code>// Interface used in the ServiceAsync inteface. public interface BaseObject { public String getId(); } // Class that implements the interface public class _ModelDto implements BaseObject, IsSerializable { protected String id; public void setId(String id) { this.id = id; } public String getId() { return id; } } // Interface used in the ServiceAsync inteface. public interface MyAsync&lt;T&gt; { // Nothing here. } // Service interface use both interfaces above. public interface ServiceAsync { public void getList(MyAsync&lt;List&lt;? extends BaseObject&gt;&gt; callback); } public class MyClass { ServiceAsync service = (some implementation); MyAsync&lt;List&lt;_ModelDto&gt;&gt; callBack = new MyAsync&lt;List&lt;_ModelDto&gt;&gt;() { }; service.getList(callBack); // This does not compile, says arguments are not applicable???? } </code></pre>
[ { "answer_id": 203741, "author": "Aaron", "author_id": 3752, "author_profile": "https://Stackoverflow.com/users/3752", "pm_score": 2, "selected": false, "text": "<p>The '?' in generic types can be pretty confusing. Honestly I'm not sure why this won't compile. It has to do with using the '?' in a nested generic type. But I do know some ways to work around it.</p>\n\n<p>Is there a reason that the declaration of the MyAsync in MyClass has to reference _ModelDto? It would work if you changed it to look like this:</p>\n\n<pre><code> ServiceAsync service = (some implementation);\n MyAsync&lt;List&lt;? extends BaseObject&gt;&gt; callBack = new MyAsync&lt;List&lt;? extends BaseObject&gt;&gt;() \n {\n\n };\n\n service.getList(callBack);\n</code></pre>\n\n<p>If you need to reference the type _ModelDto directly you could change the definition of ServiceAsync and it will fix the problem.<br/>\nChange it to look like this:</p>\n\n<pre><code>public interface ServiceAsync&lt;T extends BaseObject&gt;\n{\n public void getList(MyAsync&lt;List&lt;T&gt;&gt; callback);\n}\n</code></pre>\n\n<p><br/>\nThen add the parameter type to the declaration in MyClass</p>\n\n<pre><code>public class MyClass \n{\n public void method() \n {\n ServiceAsync&lt;_ModelDto&gt; service = (some implementation);\n MyAsync&lt;List&lt;_ModelDto&gt;&gt; callBack = new MyAsync&lt;List&lt;_ModelDto&gt;&gt;() \n {\n\n };\n\n service.getList(callBack);\n }\n}\n</code></pre>\n" }, { "answer_id": 203777, "author": "Kris Nuttycombe", "author_id": 390636, "author_profile": "https://Stackoverflow.com/users/390636", "pm_score": 3, "selected": false, "text": "<p>The fact that your MyAsync interface doesn't contain any method signatures and doesn't have a particularly informative name is a code smell from my perspective, but I'll assume that this is just a dummy example. As it is written, getList() couldn't ever have any reasonable implementation that used the callback in any way; remember that type erasure will erase this method signature to <code>getList(MyAsync callback);</code></p>\n\n<p>The reason that this doesn't compile is that your bound is wrong. <code>MyAsync&lt;List&lt;? extends BaseObject&gt;&gt;</code> gives T as <code>List&lt;? extends BaseObject&gt;</code>, a list of some unknown type.</p>\n\n<p>It looks to me like what you want is for the getList method itself to be generic:</p>\n\n<pre><code>public interface ServiceAsync {\n public &lt;T extends BaseObject&gt; void getList(MyAsync&lt;List&lt;T&gt;&gt; callback);\n}\n\npublic class MyClass {\n public void foo() {\n ServiceAsync service = null;\n MyAsync&lt;List&lt;_ModelDto&gt;&gt; callBack = new MyAsync&lt;List&lt;_ModelDto&gt;&gt;() {};\n\n service.getList (callBack); // This compiles\n }\n}\n</code></pre>\n" }, { "answer_id": 204456, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 2, "selected": true, "text": "<p>This has got to do with the subtyping rules for parametrized types. I'll explain it in three steps:</p>\n\n<h2>Non-nested case</h2>\n\n<p>When you have the following subtype relation (where <code>&lt;:</code> is the symbol for \"is a subtype of\"):</p>\n\n<pre><code>_ModelDto &lt;: BaseObject\n</code></pre>\n\n<p>The following relation does <strong>not</strong> hold:</p>\n\n<pre><code>List&lt;_ModelDto&gt; &lt;: List&lt;BaseObject&gt;\n</code></pre>\n\n<p>But the following relations do:</p>\n\n<pre><code>List&lt;_ModelDto&gt; &lt;: List&lt;? extends _ModelDto&gt; &lt;: List&lt;? extends BaseObject&gt;\n</code></pre>\n\n<p>This is the reason why Java has wildcards: to enable these kind of subtype relations. All of this is explained in the <a href=\"http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf\" rel=\"nofollow noreferrer\">Generics tutorial</a>. If you understand this, we can continue with the nested case...</p>\n\n<h2>Nested case</h2>\n\n<p>Let's do exactly the same, but with one more level of nesting. Starting from the subtype relation:</p>\n\n<pre><code>List&lt;_ModelDto&gt; &lt;: List&lt;? extends BaseObject&gt;\n</code></pre>\n\n<p>The following relation does <strong>not</strong> hold, for exactly the same reasons as above:</p>\n\n<pre><code>MyAsync&lt;List&lt;_ModelDto&gt;&gt; &lt;: MyAsync&lt;List&lt;? extends BaseObject&gt;&gt;\n</code></pre>\n\n<p>This is <em>precisely</em> the conversion you are trying to do when calling <code>service.getList(callBack)</code>, and since the subtype relation does not hold, the conversion fails.</p>\n\n<p>However, as above, you <strong>do</strong> have the following relations:</p>\n\n<pre><code>MyAsync&lt;List&lt;_ModelDto&gt;&gt;\n &lt;: MyAsync&lt;? extends List&lt;_ModelDto&gt;&gt;\n &lt;: MyAsync&lt;? extends List&lt;? extends BaseObject&gt;&gt;\n</code></pre>\n\n<h2>Solution</h2>\n\n<p>So you should write the signature of <code>getList</code> as follows to make the call work:</p>\n\n<pre><code>public void getList(MyAsync&lt;? extends List&lt;? extends BaseObject&gt;&gt; callback);\n</code></pre>\n\n<p>The difference will be that the body of <code>getList</code> will be constrained with how it can use the <code>callback</code>. If <code>MyAsync</code> contains the following members:</p>\n\n<pre><code>public interface MyAsync&lt;T&gt; {\n T get();\n void set(T t);\n}\n</code></pre>\n\n<p>Then, the body of <code>getList</code> will be able to <code>get</code> a list from the callback. However, it cannot <code>set</code> the list (except setting it to <code>null</code>), because it does not know exactly what kind of list is represented by the <code>?</code>.</p>\n\n<p>In contrast, with your original signature, <code>set</code> is available, and that is why the compiler cannot allow your argument.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28108/" ]
Just got a question about generics, why doesn't this compile when using a generic List? If its not possible, anyway around it? Much appreciate any answer. ``` // Interface used in the ServiceAsync inteface. public interface BaseObject { public String getId(); } // Class that implements the interface public class _ModelDto implements BaseObject, IsSerializable { protected String id; public void setId(String id) { this.id = id; } public String getId() { return id; } } // Interface used in the ServiceAsync inteface. public interface MyAsync<T> { // Nothing here. } // Service interface use both interfaces above. public interface ServiceAsync { public void getList(MyAsync<List<? extends BaseObject>> callback); } public class MyClass { ServiceAsync service = (some implementation); MyAsync<List<_ModelDto>> callBack = new MyAsync<List<_ModelDto>>() { }; service.getList(callBack); // This does not compile, says arguments are not applicable???? } ```
This has got to do with the subtyping rules for parametrized types. I'll explain it in three steps: Non-nested case --------------- When you have the following subtype relation (where `<:` is the symbol for "is a subtype of"): ``` _ModelDto <: BaseObject ``` The following relation does **not** hold: ``` List<_ModelDto> <: List<BaseObject> ``` But the following relations do: ``` List<_ModelDto> <: List<? extends _ModelDto> <: List<? extends BaseObject> ``` This is the reason why Java has wildcards: to enable these kind of subtype relations. All of this is explained in the [Generics tutorial](http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf). If you understand this, we can continue with the nested case... Nested case ----------- Let's do exactly the same, but with one more level of nesting. Starting from the subtype relation: ``` List<_ModelDto> <: List<? extends BaseObject> ``` The following relation does **not** hold, for exactly the same reasons as above: ``` MyAsync<List<_ModelDto>> <: MyAsync<List<? extends BaseObject>> ``` This is *precisely* the conversion you are trying to do when calling `service.getList(callBack)`, and since the subtype relation does not hold, the conversion fails. However, as above, you **do** have the following relations: ``` MyAsync<List<_ModelDto>> <: MyAsync<? extends List<_ModelDto>> <: MyAsync<? extends List<? extends BaseObject>> ``` Solution -------- So you should write the signature of `getList` as follows to make the call work: ``` public void getList(MyAsync<? extends List<? extends BaseObject>> callback); ``` The difference will be that the body of `getList` will be constrained with how it can use the `callback`. If `MyAsync` contains the following members: ``` public interface MyAsync<T> { T get(); void set(T t); } ``` Then, the body of `getList` will be able to `get` a list from the callback. However, it cannot `set` the list (except setting it to `null`), because it does not know exactly what kind of list is represented by the `?`. In contrast, with your original signature, `set` is available, and that is why the compiler cannot allow your argument.
203,695
<p>When you create an instance of a class with the <code>new</code> operator, memory gets allocated on the heap. When you create an instance of a struct with the <code>new</code> operator where does the memory get allocated, on the heap or on the stack ?</p>
[ { "answer_id": 203698, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 3, "selected": false, "text": "<p>As with all value types, structs always go where they were <em>declared</em>.</p>\n\n<p>See this question <a href=\"https://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class\">here</a> for more details on when to use structs.\nAnd this question <a href=\"https://stackoverflow.com/questions/37931/whats-the-use-of-value-types-in-net\">here</a> for some more info on structs.</p>\n\n<p><strong>Edit:</strong> I had mistankely answered that they <em>ALWAYS</em> go in the stack. This is <a href=\"http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91\" rel=\"nofollow noreferrer\">incorrect</a>.</p>\n" }, { "answer_id": 203699, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 1, "selected": false, "text": "<p>Structs get allocated to the stack. Here is a helpful explanation:</p>\n\n<p><a href=\"http://www.developerfusion.com/article/4341/the-quick-dirty-net-guide-to-cvb-oop/7/\" rel=\"nofollow noreferrer\">Structs</a></p>\n\n<blockquote>\n <p>Additionally, classes when instantiated within .NET allocate memory on\n the heap or .NET's reserved memory space. Whereas structs yield more\n efficiency when instantiated due to allocation on the stack.\n Furthermore, it should be noted that passing parameters within structs\n are done so by value.</p>\n</blockquote>\n" }, { "answer_id": 203783, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 5, "selected": false, "text": "<p>The memory containing a struct's fields can be allocated on either the stack or the heap depending on the circumstances. If the struct-type variable is a local variable or parameter that is not captured by some anonymous delegate or iterator class, then it will be allocated on the stack. If the variable is part of some class, then it will be allocated within the class on the heap.</p>\n\n<p>If the struct is allocated on the heap, then calling the new operator is not actually necessary to allocate the memory. The only purpose would be to set the field values according to whatever is in the constructor. If the constructor is not called, then all the fields will get their default values (0 or null).</p>\n\n<p>Similarly for structs allocated on the stack, except that C# requires all local variables to be set to some value before they are used, so you have to call either a custom constructor or the default constructor (a constructor that takes no parameters is always available for structs).</p>\n" }, { "answer_id": 203799, "author": "bashmohandes", "author_id": 28120, "author_profile": "https://Stackoverflow.com/users/28120", "pm_score": 1, "selected": false, "text": "<p>Pretty much the structs which are considered Value types, are allocated on stack, while objects get allocated on heap, while the object reference (pointer) gets allocated on the stack.</p>\n" }, { "answer_id": 204009, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p>Okay, let's see if I can make this any clearer.</p>\n\n<p>Firstly, Ash is right: the question is <em>not</em> about where value type <em>variables</em> are allocated. That's a different question - and one to which the answer isn't just \"on the stack\". It's more complicated than that (and made even more complicated by C# 2). I have an <a href=\"https://jonskeet.uk/csharp/memory.html\" rel=\"noreferrer\">article on the topic</a> and will expand on it if requested, but let's deal with just the <code>new</code> operator.</p>\n\n<p>Secondly, all of this really depends on what level you're talking about. I'm looking at what the compiler does with the source code, in terms of the IL it creates. It's more than possible that the JIT compiler will do clever things in terms of optimising away quite a lot of \"logical\" allocation.</p>\n\n<p>Thirdly, I'm ignoring generics, mostly because I don't actually know the answer, and partly because it would complicate things too much.</p>\n\n<p>Finally, all of this is just with the current implementation. The C# spec doesn't specify much of this - it's effectively an implementation detail. There are those who believe that managed code developers really shouldn't care. I'm not sure I'd go that far, but it's worth imagining a world where in fact all local variables live on the heap - which would still conform with the spec.</p>\n\n<hr/>\n\n<p>There are two different situations with the <code>new</code> operator on value types: you can either call a parameterless constructor (e.g. <code>new Guid()</code>) or a parameterful constructor (e.g. <code>new Guid(someString)</code>). These generate significantly different IL. To understand why, you need to compare the C# and CLI specs: according to C#, all value types have a parameterless constructor. According to the CLI spec, <em>no</em> value types have parameterless constructors. (Fetch the constructors of a value type with reflection some time - you won't find a parameterless one.)</p>\n\n<p>It makes sense for C# to treat the \"initialize a value with zeroes\" as a constructor, because it keeps the language consistent - you can think of <code>new(...)</code> as <em>always</em> calling a constructor. It makes sense for the CLI to think of it differently, as there's no real code to call - and certainly no type-specific code.</p>\n\n<p>It also makes a difference what you're going to do with the value after you've initialized it. The IL used for</p>\n\n<pre><code>Guid localVariable = new Guid(someString);\n</code></pre>\n\n<p>is different to the IL used for:</p>\n\n<pre><code>myInstanceOrStaticVariable = new Guid(someString);\n</code></pre>\n\n<p>In addition, if the value is used as an intermediate value, e.g. an argument to a method call, things are slightly different again. To show all these differences, here's a short test program. It doesn't show the difference between static variables and instance variables: the IL would differ between <code>stfld</code> and <code>stsfld</code>, but that's all.</p>\n\n<pre><code>using System;\n\npublic class Test\n{\n static Guid field;\n\n static void Main() {}\n static void MethodTakingGuid(Guid guid) {}\n\n\n static void ParameterisedCtorAssignToField()\n {\n field = new Guid(\"\");\n }\n\n static void ParameterisedCtorAssignToLocal()\n {\n Guid local = new Guid(\"\");\n // Force the value to be used\n local.ToString();\n }\n\n static void ParameterisedCtorCallMethod()\n {\n MethodTakingGuid(new Guid(\"\"));\n }\n\n static void ParameterlessCtorAssignToField()\n {\n field = new Guid();\n }\n\n static void ParameterlessCtorAssignToLocal()\n {\n Guid local = new Guid();\n // Force the value to be used\n local.ToString();\n }\n\n static void ParameterlessCtorCallMethod()\n {\n MethodTakingGuid(new Guid());\n }\n}\n</code></pre>\n\n<p>Here's the IL for the class, excluding irrelevant bits (such as nops):</p>\n\n<pre><code>.class public auto ansi beforefieldinit Test extends [mscorlib]System.Object \n{\n // Removed Test's constructor, Main, and MethodTakingGuid.\n\n .method private hidebysig static void ParameterisedCtorAssignToField() cil managed\n {\n .maxstack 8\n L_0001: ldstr \"\"\n L_0006: newobj instance void [mscorlib]System.Guid::.ctor(string)\n L_000b: stsfld valuetype [mscorlib]System.Guid Test::field\n L_0010: ret \n }\n\n .method private hidebysig static void ParameterisedCtorAssignToLocal() cil managed\n {\n .maxstack 2\n .locals init ([0] valuetype [mscorlib]System.Guid guid) \n L_0001: ldloca.s guid \n L_0003: ldstr \"\" \n L_0008: call instance void [mscorlib]System.Guid::.ctor(string) \n // Removed ToString() call\n L_001c: ret\n }\n\n .method private hidebysig static void ParameterisedCtorCallMethod() cil managed \n { \n .maxstack 8\n L_0001: ldstr \"\"\n L_0006: newobj instance void [mscorlib]System.Guid::.ctor(string)\n L_000b: call void Test::MethodTakingGuid(valuetype [mscorlib]System.Guid)\n L_0011: ret \n }\n\n .method private hidebysig static void ParameterlessCtorAssignToField() cil managed\n {\n .maxstack 8\n L_0001: ldsflda valuetype [mscorlib]System.Guid Test::field\n L_0006: initobj [mscorlib]System.Guid\n L_000c: ret \n }\n\n .method private hidebysig static void ParameterlessCtorAssignToLocal() cil managed\n {\n .maxstack 1\n .locals init ([0] valuetype [mscorlib]System.Guid guid)\n L_0001: ldloca.s guid\n L_0003: initobj [mscorlib]System.Guid\n // Removed ToString() call\n L_0017: ret \n }\n\n .method private hidebysig static void ParameterlessCtorCallMethod() cil managed\n {\n .maxstack 1\n .locals init ([0] valuetype [mscorlib]System.Guid guid) \n L_0001: ldloca.s guid\n L_0003: initobj [mscorlib]System.Guid\n L_0009: ldloc.0 \n L_000a: call void Test::MethodTakingGuid(valuetype [mscorlib]System.Guid)\n L_0010: ret \n }\n\n .field private static valuetype [mscorlib]System.Guid field\n}\n</code></pre>\n\n<p>As you can see, there are lots of different instructions used for calling the constructor:</p>\n\n<ul>\n<li><code>newobj</code>: Allocates the value on the stack, calls a parameterised constructor. Used for intermediate values, e.g. for assignment to a field or use as a method argument.</li>\n<li><code>call instance</code>: Uses an already-allocated storage location (whether on the stack or not). This is used in the code above for assigning to a local variable. If the same local variable is assigned a value several times using several <code>new</code> calls, it just initializes the data over the top of the old value - it <em>doesn't</em> allocate more stack space each time.</li>\n<li><code>initobj</code>: Uses an already-allocated storage location and just wipes the data. This is used for all our parameterless constructor calls, including those which assign to a local variable. For the method call, an intermediate local variable is effectively introduced, and its value wiped by <code>initobj</code>.</li>\n</ul>\n\n<p>I hope this shows how complicated the topic is, while shining a bit of light on it at the same time. In <em>some</em> conceptual senses, every call to <code>new</code> allocates space on the stack - but as we've seen, that isn't what really happens even at the IL level. I'd like to highlight one particular case. Take this method:</p>\n\n<pre><code>void HowManyStackAllocations()\n{\n Guid guid = new Guid();\n // [...] Use guid\n guid = new Guid(someBytes);\n // [...] Use guid\n guid = new Guid(someString);\n // [...] Use guid\n}\n</code></pre>\n\n<p>That \"logically\" has 4 stack allocations - one for the variable, and one for each of the three <code>new</code> calls - but in fact (for that specific code) the stack is only allocated once, and then the same storage location is reused.</p>\n\n<p>EDIT: Just to be clear, this is only true in some cases... in particular, the value of <code>guid</code> won't be visible if the <code>Guid</code> constructor throws an exception, which is why the C# compiler is able to reuse the same stack slot. See Eric Lippert's <a href=\"https://ericlippert.com/2010/10/11/debunking-another-myth-about-value-types/\" rel=\"noreferrer\">blog post on value type construction</a> for more details and a case where it <em>doesn't</em> apply.</p>\n\n<p>I've learned a lot in writing this answer - please ask for clarification if any of it is unclear!</p>\n" }, { "answer_id": 204102, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 4, "selected": false, "text": "<p>To put it compactly, new is a misnomer for structs, calling new simply calls the constructor. The only storage location for the struct is the location it is defined.</p>\n\n<p>If it is a member variable it is stored directly in whatever it is defined in, if it is a local variable or parameter it is stored on the stack.</p>\n\n<p>Contrast this to classes, which have a reference wherever the struct would have been stored in its entirety, while the reference points somewhere on the heap. (Member within, local/parameter on stack)</p>\n\n<p>It may help to look a bit into C++, where there is not real distinction between class/struct. (There are similar names in the language, but they only refer to the default accessibility of things) When you call new you get a pointer to the heap location, while if you have a non-pointer reference it is stored directly on the stack or within the other object, ala structs in C#.</p>\n" }, { "answer_id": 404509, "author": "user18579", "author_id": 18579, "author_profile": "https://Stackoverflow.com/users/18579", "pm_score": 2, "selected": false, "text": "<p>I'm probably missing something here but why do we care about allocation?</p>\n\n<p>Value types are passed by value ;) and thus can't be mutated at a different scope than where they are defined. To be able to mutate the value you have to add the [ref] keyword.</p>\n\n<p>Reference types are passed by reference and can be mutated.</p>\n\n<p>There are of course immutable reference types strings being the most popular one.</p>\n\n<p>Array layout/initialization:\nValue types -> zero memory [name,zip][name,zip]\nReference types -> zero memory -> null [ref][ref]</p>\n" }, { "answer_id": 12329123, "author": "Sujit", "author_id": 792713, "author_profile": "https://Stackoverflow.com/users/792713", "pm_score": 2, "selected": false, "text": "<p>A <code>class</code> or <code>struct</code> declaration is like a blueprint that is used to create instances or objects at run time. If you define a <code>class</code> or <code>struct</code> called Person, Person is the name of the type. If you declare and initialize a variable p of type Person, p is said to be an object or instance of Person. Multiple instances of the same Person type can be created, and each instance can have different values in its <code>properties</code> and <code>fields</code>.</p>\n\n<p>A <code>class</code> is a reference type. When an object of the <code>class</code> is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.</p>\n\n<p>A <code>struct</code> is a value type. When a <code>struct</code> is created, the variable to which the <code>struct</code> is assigned holds the struct's actual data. When the <code>struct</code> is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.</p>\n\n<p>In general, <code>classes</code> are used to model more complex behavior, or data that is intended to be modified after a <code>class</code> object is created. <code>Structs</code> are best suited for small data structures that contain primarily data that is not intended to be modified after the <code>struct</code> is created.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms173109.aspx\">for more...</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18709/" ]
When you create an instance of a class with the `new` operator, memory gets allocated on the heap. When you create an instance of a struct with the `new` operator where does the memory get allocated, on the heap or on the stack ?
Okay, let's see if I can make this any clearer. Firstly, Ash is right: the question is *not* about where value type *variables* are allocated. That's a different question - and one to which the answer isn't just "on the stack". It's more complicated than that (and made even more complicated by C# 2). I have an [article on the topic](https://jonskeet.uk/csharp/memory.html) and will expand on it if requested, but let's deal with just the `new` operator. Secondly, all of this really depends on what level you're talking about. I'm looking at what the compiler does with the source code, in terms of the IL it creates. It's more than possible that the JIT compiler will do clever things in terms of optimising away quite a lot of "logical" allocation. Thirdly, I'm ignoring generics, mostly because I don't actually know the answer, and partly because it would complicate things too much. Finally, all of this is just with the current implementation. The C# spec doesn't specify much of this - it's effectively an implementation detail. There are those who believe that managed code developers really shouldn't care. I'm not sure I'd go that far, but it's worth imagining a world where in fact all local variables live on the heap - which would still conform with the spec. --- There are two different situations with the `new` operator on value types: you can either call a parameterless constructor (e.g. `new Guid()`) or a parameterful constructor (e.g. `new Guid(someString)`). These generate significantly different IL. To understand why, you need to compare the C# and CLI specs: according to C#, all value types have a parameterless constructor. According to the CLI spec, *no* value types have parameterless constructors. (Fetch the constructors of a value type with reflection some time - you won't find a parameterless one.) It makes sense for C# to treat the "initialize a value with zeroes" as a constructor, because it keeps the language consistent - you can think of `new(...)` as *always* calling a constructor. It makes sense for the CLI to think of it differently, as there's no real code to call - and certainly no type-specific code. It also makes a difference what you're going to do with the value after you've initialized it. The IL used for ``` Guid localVariable = new Guid(someString); ``` is different to the IL used for: ``` myInstanceOrStaticVariable = new Guid(someString); ``` In addition, if the value is used as an intermediate value, e.g. an argument to a method call, things are slightly different again. To show all these differences, here's a short test program. It doesn't show the difference between static variables and instance variables: the IL would differ between `stfld` and `stsfld`, but that's all. ``` using System; public class Test { static Guid field; static void Main() {} static void MethodTakingGuid(Guid guid) {} static void ParameterisedCtorAssignToField() { field = new Guid(""); } static void ParameterisedCtorAssignToLocal() { Guid local = new Guid(""); // Force the value to be used local.ToString(); } static void ParameterisedCtorCallMethod() { MethodTakingGuid(new Guid("")); } static void ParameterlessCtorAssignToField() { field = new Guid(); } static void ParameterlessCtorAssignToLocal() { Guid local = new Guid(); // Force the value to be used local.ToString(); } static void ParameterlessCtorCallMethod() { MethodTakingGuid(new Guid()); } } ``` Here's the IL for the class, excluding irrelevant bits (such as nops): ``` .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { // Removed Test's constructor, Main, and MethodTakingGuid. .method private hidebysig static void ParameterisedCtorAssignToField() cil managed { .maxstack 8 L_0001: ldstr "" L_0006: newobj instance void [mscorlib]System.Guid::.ctor(string) L_000b: stsfld valuetype [mscorlib]System.Guid Test::field L_0010: ret } .method private hidebysig static void ParameterisedCtorAssignToLocal() cil managed { .maxstack 2 .locals init ([0] valuetype [mscorlib]System.Guid guid) L_0001: ldloca.s guid L_0003: ldstr "" L_0008: call instance void [mscorlib]System.Guid::.ctor(string) // Removed ToString() call L_001c: ret } .method private hidebysig static void ParameterisedCtorCallMethod() cil managed { .maxstack 8 L_0001: ldstr "" L_0006: newobj instance void [mscorlib]System.Guid::.ctor(string) L_000b: call void Test::MethodTakingGuid(valuetype [mscorlib]System.Guid) L_0011: ret } .method private hidebysig static void ParameterlessCtorAssignToField() cil managed { .maxstack 8 L_0001: ldsflda valuetype [mscorlib]System.Guid Test::field L_0006: initobj [mscorlib]System.Guid L_000c: ret } .method private hidebysig static void ParameterlessCtorAssignToLocal() cil managed { .maxstack 1 .locals init ([0] valuetype [mscorlib]System.Guid guid) L_0001: ldloca.s guid L_0003: initobj [mscorlib]System.Guid // Removed ToString() call L_0017: ret } .method private hidebysig static void ParameterlessCtorCallMethod() cil managed { .maxstack 1 .locals init ([0] valuetype [mscorlib]System.Guid guid) L_0001: ldloca.s guid L_0003: initobj [mscorlib]System.Guid L_0009: ldloc.0 L_000a: call void Test::MethodTakingGuid(valuetype [mscorlib]System.Guid) L_0010: ret } .field private static valuetype [mscorlib]System.Guid field } ``` As you can see, there are lots of different instructions used for calling the constructor: * `newobj`: Allocates the value on the stack, calls a parameterised constructor. Used for intermediate values, e.g. for assignment to a field or use as a method argument. * `call instance`: Uses an already-allocated storage location (whether on the stack or not). This is used in the code above for assigning to a local variable. If the same local variable is assigned a value several times using several `new` calls, it just initializes the data over the top of the old value - it *doesn't* allocate more stack space each time. * `initobj`: Uses an already-allocated storage location and just wipes the data. This is used for all our parameterless constructor calls, including those which assign to a local variable. For the method call, an intermediate local variable is effectively introduced, and its value wiped by `initobj`. I hope this shows how complicated the topic is, while shining a bit of light on it at the same time. In *some* conceptual senses, every call to `new` allocates space on the stack - but as we've seen, that isn't what really happens even at the IL level. I'd like to highlight one particular case. Take this method: ``` void HowManyStackAllocations() { Guid guid = new Guid(); // [...] Use guid guid = new Guid(someBytes); // [...] Use guid guid = new Guid(someString); // [...] Use guid } ``` That "logically" has 4 stack allocations - one for the variable, and one for each of the three `new` calls - but in fact (for that specific code) the stack is only allocated once, and then the same storage location is reused. EDIT: Just to be clear, this is only true in some cases... in particular, the value of `guid` won't be visible if the `Guid` constructor throws an exception, which is why the C# compiler is able to reuse the same stack slot. See Eric Lippert's [blog post on value type construction](https://ericlippert.com/2010/10/11/debunking-another-myth-about-value-types/) for more details and a case where it *doesn't* apply. I've learned a lot in writing this answer - please ask for clarification if any of it is unclear!
203,707
<p>The following two forms of jQuery selectors seem to do the same thing:</p> <ul> <li>$("div > ul.posts") </li> <li>$("div ul.posts")</li> </ul> <p>which is to select all the "ul" elements of class "posts" under "div" elements.</p> <p>Is there any difference?</p>
[ { "answer_id": 203710, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "<p>The first only selects ul.posts whose parentNode is div.</p>\n\n<p>The second would also select:</p>\n\n<pre><code>&lt;div&gt;\n &lt;blockquote&gt;\n &lt;ul class=\"posts\"&gt;&lt;/ul&gt;\n &lt;/blockquote&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 203713, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 6, "selected": true, "text": "<p>Concerning <code>$(\"div &gt; ul.posts\")</code>, only direct descendants of <code>DIV</code>s will be selected.</p>\n\n<pre><code>&lt;div&gt;\n &lt;ul class=\"posts\"&gt; &lt;!--SELECTED--&gt;\n &lt;li&gt;List Item&lt;/li&gt;\n &lt;ul class=\"posts\"&gt; &lt;!--NOT SELECTED--&gt;\n &lt;li&gt;Sub list item&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/ul&gt;\n\n &lt;fieldset&gt;\n &lt;ul class=\"posts\"&gt; &lt;!--NOT SELECTED--&gt;\n &lt;li&gt;List item&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/fieldset&gt;\n\n &lt;ul class=\"posts\"&gt; &lt;!--SELECTED--&gt;\n &lt;li&gt;List item&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>while <code>$(\"div ul.posts\")</code> will select all descendants matching the criteria. So all and any <code>ul.posts</code> will be selected, whatever their nesting level is as long as somewhere along the chain, they are within a <code>div</code>.</p>\n" }, { "answer_id": 3076118, "author": "robbysalz", "author_id": 371081, "author_profile": "https://Stackoverflow.com/users/371081", "pm_score": 1, "selected": false, "text": "<p>Oh. So \"ancestor descendant\" refers to all specified elements under a parent, no matter how deeply nested</p>\n\n<p>While \"parent child\" refers only to the first specified element even if it occurs again somewhere else under the parent</p>\n" }, { "answer_id": 7082050, "author": "Chris", "author_id": 444178, "author_profile": "https://Stackoverflow.com/users/444178", "pm_score": 0, "selected": false, "text": "<p>I'm just adding a familiar reference here. I realize it's years after the original question but it was on the first page on Google and maybe this will help someone else.</p>\n\n<p>Think of real-world ancestors and parents. Parent and Child are always one generation apart, but ancestors and their descendants can be hundreds of years apart. The <code>&gt;</code> symbol helps symbolize the direct relation between parent and child. </p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6225/" ]
The following two forms of jQuery selectors seem to do the same thing: * $("div > ul.posts") * $("div ul.posts") which is to select all the "ul" elements of class "posts" under "div" elements. Is there any difference?
Concerning `$("div > ul.posts")`, only direct descendants of `DIV`s will be selected. ``` <div> <ul class="posts"> <!--SELECTED--> <li>List Item</li> <ul class="posts"> <!--NOT SELECTED--> <li>Sub list item</li> </ul> </ul> <fieldset> <ul class="posts"> <!--NOT SELECTED--> <li>List item</li> </ul> </fieldset> <ul class="posts"> <!--SELECTED--> <li>List item</li> </ul> </div> ``` while `$("div ul.posts")` will select all descendants matching the criteria. So all and any `ul.posts` will be selected, whatever their nesting level is as long as somewhere along the chain, they are within a `div`.
203,739
<pre><code>&quot;foo&quot; instanceof String //=&gt; false &quot;foo&quot; instanceof Object //=&gt; false true instanceof Boolean //=&gt; false true instanceof Object //=&gt; false false instanceof Boolean //=&gt; false false instanceof Object //=&gt; false 12.21 instanceof Number //=&gt; false /foo/ instanceof RegExp //=&gt; true // the tests against Object really don't make sense </code></pre> <p>Array literals and Object literals match...</p> <pre><code>[0,1] instanceof Array //=&gt; true {0:1} instanceof Object //=&gt; true </code></pre> <p>Why don't all of them? Or, why don't they all <em>not</em>?<br /> And, what are they an instance of, then?</p> <p>It's the same in FF3, IE7, Opera, and Chrome. So, at least it's consistent.</p>
[ { "answer_id": 203757, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 10, "selected": true, "text": "<p>Primitives are a different kind of type than objects created from within Javascript. From the <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/instanceof_Operator\" rel=\"noreferrer\">Mozilla API docs</a>:</p>\n\n<pre><code>var color1 = new String(\"green\");\ncolor1 instanceof String; // returns true\nvar color2 = \"coral\";\ncolor2 instanceof String; // returns false (color2 is not a String object)\n</code></pre>\n\n<p>I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use <code>typeof \"foo\" === \"string\"</code> instead of <code>instanceof</code>.</p>\n\n<p>An easy way to remember things like this is asking yourself \"I wonder what would be sane and easy to learn\"? Whatever the answer is, Javascript does the other thing.</p>\n" }, { "answer_id": 1185835, "author": "user144049", "author_id": 144049, "author_profile": "https://Stackoverflow.com/users/144049", "pm_score": 5, "selected": false, "text": "<p>You can use constructor property:</p>\n\n<pre><code>'foo'.constructor == String // returns true\ntrue.constructor == Boolean // returns true\n</code></pre>\n" }, { "answer_id": 2274632, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Or you can just make your own function like so:</p>\n\n<pre><code>function isInstanceOf(obj, clazz){\n return (obj instanceof eval(\"(\"+clazz+\")\")) || (typeof obj == clazz.toLowerCase());\n};\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>isInstanceOf('','String');\nisInstanceOf(new String(), 'String');\n</code></pre>\n\n<p>These should both return true.</p>\n" }, { "answer_id": 7772724, "author": "axkibe", "author_id": 588779, "author_profile": "https://Stackoverflow.com/users/588779", "pm_score": 7, "selected": false, "text": "<p>I use:</p>\n\n<pre><code>function isString(s) {\n return typeof(s) === 'string' || s instanceof String;\n}\n</code></pre>\n\n<p>Because in JavaScript strings can be literals or objects.</p>\n" }, { "answer_id": 18057157, "author": "Aadit M Shah", "author_id": 783743, "author_profile": "https://Stackoverflow.com/users/783743", "pm_score": 6, "selected": false, "text": "<p>In JavaScript everything is an object (or may at least be treated as an object), except <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Primitive\" rel=\"noreferrer\">primitives</a> (booleans, null, numbers, strings and the value <code>undefined</code> (and symbol in ES6)):</p>\n\n<pre><code>console.log(typeof true); // boolean\nconsole.log(typeof 0); // number\nconsole.log(typeof \"\"); // string\nconsole.log(typeof undefined); // undefined\nconsole.log(typeof null); // object\nconsole.log(typeof []); // object\nconsole.log(typeof {}); // object\nconsole.log(typeof function () {}); // function\n</code></pre>\n\n<p>As you can see objects, arrays and the value <code>null</code> are all considered objects (<code>null</code> is a reference to an object which doesn't exist). Functions are distinguished because they are a special type of <em>callable</em> objects. However they are still objects.</p>\n\n<p>On the other hand the literals <code>true</code>, <code>0</code>, <code>\"\"</code> and <code>undefined</code> are not objects. They are primitive values in JavaScript. However booleans, numbers and strings also have constructors <code>Boolean</code>, <code>Number</code> and <code>String</code> respectively which wrap their respective primitives to provide added functionality:</p>\n\n<pre><code>console.log(typeof new Boolean(true)); // object\nconsole.log(typeof new Number(0)); // object\nconsole.log(typeof new String(\"\")); // object\n</code></pre>\n\n<p>As you can see when primitive values are wrapped within the <code>Boolean</code>, <code>Number</code> and <code>String</code> constructors respectively they become objects. The <code>instanceof</code> operator only works for objects (which is why it returns <code>false</code> for primitive values):</p>\n\n<pre><code>console.log(true instanceof Boolean); // false\nconsole.log(0 instanceof Number); // false\nconsole.log(\"\" instanceof String); // false\nconsole.log(new Boolean(true) instanceof Boolean); // true\nconsole.log(new Number(0) instanceof Number); // true\nconsole.log(new String(\"\") instanceof String); // true\n</code></pre>\n\n<p>As you can see both <code>typeof</code> and <code>instanceof</code> are insufficient to test whether a value is a boolean, a number or a string - <code>typeof</code> only works for primitive booleans, numbers and strings; and <code>instanceof</code> doesn't work for primitive booleans, numbers and strings.</p>\n\n<p>Fortunately there's a simple solution to this problem. The default implementation of <code>toString</code> (i.e. as it's natively defined on <code>Object.prototype.toString</code>) returns the internal <code>[[Class]]</code> property of both primitive values and objects:</p>\n\n<pre><code>function classOf(value) {\n return Object.prototype.toString.call(value);\n}\n\nconsole.log(classOf(true)); // [object Boolean]\nconsole.log(classOf(0)); // [object Number]\nconsole.log(classOf(\"\")); // [object String]\nconsole.log(classOf(new Boolean(true))); // [object Boolean]\nconsole.log(classOf(new Number(0))); // [object Number]\nconsole.log(classOf(new String(\"\"))); // [object String]\n</code></pre>\n\n<p>The internal <code>[[Class]]</code> property of a value is much more useful than the <code>typeof</code> the value. We can use <code>Object.prototype.toString</code> to create our own (more useful) version of the <code>typeof</code> operator as follows:</p>\n\n<pre><code>function typeOf(value) {\n return Object.prototype.toString.call(value).slice(8, -1);\n}\n\nconsole.log(typeOf(true)); // Boolean\nconsole.log(typeOf(0)); // Number\nconsole.log(typeOf(\"\")); // String\nconsole.log(typeOf(new Boolean(true))); // Boolean\nconsole.log(typeOf(new Number(0))); // Number\nconsole.log(typeOf(new String(\"\"))); // String\n</code></pre>\n\n<p>Hope this article helped. To know more about the differences between primitives and wrapped objects read the following blog post: <a href=\"http://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/\" rel=\"noreferrer\" title=\"The Secret Life of JavaScript Primitives | JavaScript, JavaScript...\">The Secret Life of JavaScript Primitives</a></p>\n" }, { "answer_id": 27899344, "author": "mko", "author_id": 456218, "author_profile": "https://Stackoverflow.com/users/456218", "pm_score": -1, "selected": false, "text": "<p>For me the confusion caused by </p>\n\n<pre><code>\"str\".__proto__ // #1\n=&gt; String\n</code></pre>\n\n<p>So <code>\"str\" istanceof String</code> should return <code>true</code> because how istanceof works as below:</p>\n\n<pre><code>\"str\".__proto__ == String.prototype // #2\n=&gt; true\n</code></pre>\n\n<p>Results of expression <strong>#1</strong> and <strong>#2</strong> conflict each other, so there should be one of them wrong.</p>\n\n<p><strong>#1 is wrong</strong></p>\n\n<p>I figure out that it caused by the <code>__proto__</code> is non standard property, so use the standard one:<code>Object.getPrototypeOf</code></p>\n\n<pre><code>Object.getPrototypeOf(\"str\") // #3\n=&gt; TypeError: Object.getPrototypeOf called on non-object\n</code></pre>\n\n<p>Now there's no confusion between expression <strong>#2</strong> and <strong>#3</strong></p>\n" }, { "answer_id": 42868539, "author": "Robby Harris", "author_id": 7729688, "author_profile": "https://Stackoverflow.com/users/7729688", "pm_score": 1, "selected": false, "text": "<p>I believe I have come up with a viable solution:</p>\n\n<pre><code>Object.getPrototypeOf('test') === String.prototype //true\nObject.getPrototypeOf(1) === String.prototype //false\n</code></pre>\n" }, { "answer_id": 45837316, "author": "saurabhgoyal795", "author_id": 7539786, "author_profile": "https://Stackoverflow.com/users/7539786", "pm_score": 4, "selected": false, "text": "<pre><code> typeof(text) === 'string' || text instanceof String; \n</code></pre>\n\n<p>you can use this, it will work for both case as </p>\n\n<ol>\n<li><p><code>var text=\"foo\";</code> // typeof will work</p></li>\n<li><p><code>String text= new String(\"foo\");</code> // instanceof will work</p></li>\n</ol>\n" }, { "answer_id": 56655832, "author": "HKTonyLee", "author_id": 474197, "author_profile": "https://Stackoverflow.com/users/474197", "pm_score": 2, "selected": false, "text": "<p>This is defined in the ECMAScript specification <a href=\"https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance\" rel=\"nofollow noreferrer\">Section 7.3.19 Step 3</a>: <code>If Type(O) is not Object, return false.</code></p>\n\n<p>In other word, if the <code>Obj</code> in <code>Obj instanceof Callable</code> is not an object, the <code>instanceof</code> will short-circuit to <code>false</code> directly.</p>\n" }, { "answer_id": 66213427, "author": "Belhadjer Samir", "author_id": 13762673, "author_profile": "https://Stackoverflow.com/users/13762673", "pm_score": 2, "selected": false, "text": "<p>The primitive wrapper types are reference types that are automatically created behind the scenes whenever strings, num­bers, or Booleans\nare read.For example :</p>\n<pre><code>var name = &quot;foo&quot;;\nvar firstChar = name.charAt(0);\nconsole.log(firstChar);\n</code></pre>\n<p>This is what happens behind the scenes:</p>\n<pre><code>// what the JavaScript engine does\nvar name = &quot;foo&quot;;\nvar temp = new String(name);\nvar firstChar = temp.charAt(0);\ntemp = null;\nconsole.log(firstChar);\n</code></pre>\n<p>Because the second line uses a string (a primitive) like an object,\nthe JavaScript engine creates an instance of String so that charAt(0) will\nwork.The String object exists only for one statement before it’s destroyed\ncheck <a href=\"https://dev.to/benjaminmock/do-you-know-what-autoboxing-in-js-is-enl\" rel=\"nofollow noreferrer\">this</a></p>\n<p>The <strong>instanceof</strong> operator returns false because a temporary object is\ncreated only when a value is read. Because instanceof doesn’t actually read\nanything, no temporary objects are created, and it tells us the ­values aren’t\ninstances of primitive wrapper types. You can create primitive wrapper\ntypes manually</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15031/" ]
``` "foo" instanceof String //=> false "foo" instanceof Object //=> false true instanceof Boolean //=> false true instanceof Object //=> false false instanceof Boolean //=> false false instanceof Object //=> false 12.21 instanceof Number //=> false /foo/ instanceof RegExp //=> true // the tests against Object really don't make sense ``` Array literals and Object literals match... ``` [0,1] instanceof Array //=> true {0:1} instanceof Object //=> true ``` Why don't all of them? Or, why don't they all *not*? And, what are they an instance of, then? It's the same in FF3, IE7, Opera, and Chrome. So, at least it's consistent.
Primitives are a different kind of type than objects created from within Javascript. From the [Mozilla API docs](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/instanceof_Operator): ``` var color1 = new String("green"); color1 instanceof String; // returns true var color2 = "coral"; color2 instanceof String; // returns false (color2 is not a String object) ``` I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use `typeof "foo" === "string"` instead of `instanceof`. An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"? Whatever the answer is, Javascript does the other thing.
203,754
<p>I have a thread running in the background that is reading events from an input device in a blocking fashion, now when I exit the application I want to clean up the thread properly, but I can't just run a pthread_join() because the thread would never exit due to the blocking IO.</p> <p>How do I properly solve that situation? Should I send a pthread_kill(theard, SIGIO) or a pthread_kill(theard, SIGALRM) to break the block? Is either of that even the right signal? Or is there another way to solve this situation and let that child thread exit the blocking read?</p> <p>Currently a bit puzzled since none of my googling turned up a solution.</p> <p>This is on Linux and using pthreads.</p> <p>Edit: I played around a bit with SIGIO and SIGALRM, when I don't install a signal handler they break the blocking IO up, but give a message on the console ("I/O possible") but when I install a signal handler, to avoid that message, they no longer break the blocking IO, so the thread doesn't terminate. So I am kind of back to step one.</p>
[ { "answer_id": 203819, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 2, "selected": false, "text": "<p>I think, as you said, the only way would be to send a signal then catch and deal with it appropriately. Alternatives might be SIGTERM, SIGUSR1, SIGQUIT, SIGHUP, SIGINT, etc.</p>\n\n<p>You could also use select() on your input descriptor so that you only read when it is ready. You could use select() with a timeout of, say, one second and then check if that thread should finish.</p>\n" }, { "answer_id": 203900, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 2, "selected": false, "text": "<p>One solution that occurred to me the last time I had an issue like this was to create a file (eg. a pipe) that existed only for the purpose of waking up blocking threads.</p>\n\n<p>The idea would be to create a file from the main loop (or 1 per thread, as timeout suggests - this would give you finer control over which threads are woken). All of the threads that are blocking on file I/O would do a select(), using the file(s) that they are trying to operate on, as well as the file created by the main loop (as a member of the read file descriptor set). This should make all of the select() calls return.</p>\n\n<p>Code to handle this \"event\" from the main loop would need to be added to each of the threads.</p>\n\n<p>If the main loop needed to wake up all of the threads it could either write to the file or close it.</p>\n\n<hr>\n\n<p>I can't say for sure if this works, as a restructure meant that the need to try it vanished.</p>\n" }, { "answer_id": 203902, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Your <code>select()</code> could have a timeout, even if it is infrequent, in order to exit the thread gracefully on a certain condition. I know, polling sucks...</p>\n\n<p>Another alternative is to have a pipe for each child and add that to the list of file descriptors being watched by the thread. Send a byte to the pipe from the parent when you want that child to exit. No polling at the cost of a pipe per thread.</p>\n" }, { "answer_id": 203907, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 3, "selected": false, "text": "<p>Depends how it's waiting for IO.</p>\n\n<p>If the thread is in the \"Uninterruptible IO\" state (shown as \"D\" in top), then there really is absolutely nothing you can do about it. Threads normally only enter this state briefly, doing something such as waiting for a page to be swapped in (or demand-loaded, e.g. from mmap'd file or shared library etc), however a failure (particularly of a NFS server) could cause it to stay in that state for longer.</p>\n\n<p>There is genuinely no way of escaping from this \"D\" state. The thread will not respond to signals (you can send them, but they will be queued).</p>\n\n<p>If it's a normal IO function such as read(), write() or a waiting function like select() or poll(), signals would be delivered normally.</p>\n" }, { "answer_id": 203959, "author": "David Holm", "author_id": 22247, "author_profile": "https://Stackoverflow.com/users/22247", "pm_score": 1, "selected": false, "text": "<p>I always add a \"<em>kill</em>\" function related to the thread function which I run before join that ensures the thread will be joinable within reasonable time. When a thread uses blocking IO I try to utilize the system to break the lock. For example, when using a socket I would have kill call <em>shutdown(2)</em> or <em>close(2)</em> on it which would cause the network stack to terminate it cleanly.</p>\n\n<p>Linux' socket implementation is thread safe.</p>\n" }, { "answer_id": 203975, "author": "shodanex", "author_id": 11589, "author_profile": "https://Stackoverflow.com/users/11589", "pm_score": 0, "selected": false, "text": "<p>Signals and thread is a subtle problem on Linux according to the different man pages.\nDo you use LinuxThreads, or NPTL (if you are on Linux) ?</p>\n\n<p>I am not sure of this, but I think the signal handler affects the whole process, so either you terminate your whole process or everything continue.</p>\n\n<p>You should use timed select or poll, and set a global flag to terminate your thread.</p>\n" }, { "answer_id": 204027, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 4, "selected": false, "text": "<p>I too would recommend using a select or some other non-signal-based means of terminating your thread. One of the reasons we have threads is to try and get away from signal madness. That said...</p>\n\n<p>Generally one uses pthread_kill() with SIGUSR1 or SIGUSR2 to send a signal to the thread. The other suggested signals--SIGTERM, SIGINT, SIGKILL--have process-wide semantics that you may not be interested in.</p>\n\n<p>As for the behavior when you sent the signal, my guess is that it has to do with how you handled the signal. If you have no handler installed, the default action of that signal are applied, but in the context of the thread that received the signal. So SIGALRM, for instance, would be \"handled\" by your thread, but the handling would consist of terminating the process--probably not the desired behavior.</p>\n\n<p>Receipt of a signal by the thread will generally break it out of a read with EINTR, unless it is truly in that uninterruptible state as mentioned in an earlier answer. But I think it's not, or your experiments with SIGALRM and SIGIO would not have terminated the process.</p>\n\n<p>Is your read perhaps in some sort of a loop? If the read terminates with -1 return, then break out of that loop and exit the thread.</p>\n\n<p>You can play with this very sloppy code I put together to test out my assumptions--I am a couple of timezones away from my POSIX books at the moment...</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;pthread.h&gt;\n#include &lt;signal.h&gt;\n\nint global_gotsig = 0;\n\nvoid *gotsig(int sig, siginfo_t *info, void *ucontext) \n{\n global_gotsig++;\n return NULL;\n}\n\nvoid *reader(void *arg)\n{\n char buf[32];\n int i;\n int hdlsig = (int)arg;\n\n struct sigaction sa;\n sa.sa_handler = NULL;\n sa.sa_sigaction = gotsig;\n sa.sa_flags = SA_SIGINFO;\n sigemptyset(&amp;sa.sa_mask);\n\n if (sigaction(hdlsig, &amp;sa, NULL) &lt; 0) {\n perror(\"sigaction\");\n return (void *)-1;\n }\n i = read(fileno(stdin), buf, 32);\n if (i &lt; 0) {\n perror(\"read\");\n } else {\n printf(\"Read %d bytes\\n\", i);\n }\n return (void *)i;\n}\n\nmain(int argc, char **argv)\n{\n pthread_t tid1;\n void *ret;\n int i;\n int sig = SIGUSR1;\n\n if (argc == 2) sig = atoi(argv[1]);\n printf(\"Using sig %d\\n\", sig);\n\n if (pthread_create(&amp;tid1, NULL, reader, (void *)sig)) {\n perror(\"pthread_create\");\n exit(1);\n }\n sleep(5);\n printf(\"killing thread\\n\");\n pthread_kill(tid1, sig);\n i = pthread_join(tid1, &amp;ret);\n if (i &lt; 0)\n perror(\"pthread_join\");\n else\n printf(\"thread returned %ld\\n\", (long)ret);\n printf(\"Got sig? %d\\n\", global_gotsig);\n\n}\n</code></pre>\n" }, { "answer_id": 204804, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 0, "selected": false, "text": "<p>I think the cleanest approach would have the thread using conditional variables in a loop for continuing.</p>\n\n<p>When an i/o event is fired, the conditional should be signaled.</p>\n\n<p>The main thread could just signal the condition while chaning the loop predicate to false.</p>\n\n<p>something like:</p>\n\n<pre><code>while (!_finished)\n{\n pthread_cond_wait(&amp;cond);\n handleio();\n}\ncleanup();\n</code></pre>\n\n<p>Remember with conditional variables to properly handle signals. They can have things such as 'spurious wakeups'. So i would wrap your own function around the cond_wait function.</p>\n" }, { "answer_id": 205325, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 0, "selected": false, "text": "<pre><code>struct pollfd pfd;\npfd.fd = socket;\npfd.events = POLLIN | POLLHUP | POLLERR;\npthread_lock(&amp;lock);\nwhile(thread_alive)\n{\n int ret = poll(&amp;pfd, 1, 100);\n if(ret == 1)\n {\n //handle IO\n }\n else\n {\n pthread_cond_timedwait(&amp;lock, &amp;cond, 100);\n }\n}\npthread_unlock(&amp;lock);\n</code></pre>\n\n<p>thread_alive is a thread specific variable that can be used in combination with the signal to kill the thread.</p>\n\n<p>as for the handle IO section you need to make sure that you used open with the O_NOBLOCK option, or if its a socket there is a similar flag you can set MSG_NOWAIT??. for other fds im not sure</p>\n" }, { "answer_id": 237192, "author": "HUAGHAGUAH", "author_id": 27233, "author_profile": "https://Stackoverflow.com/users/27233", "pm_score": 1, "selected": false, "text": "<p>I'm surprised that nobody has suggested pthread_cancel. I recently wrote a multi-threaded I/O program and calling cancel() and the join() afterwards worked just great.</p>\n\n<p>I had originally tried the pthread_kill() but ended up just terminating the entire program with the signals I tested with.</p>\n" }, { "answer_id": 1003785, "author": "bdonlan", "author_id": 36723, "author_profile": "https://Stackoverflow.com/users/36723", "pm_score": 1, "selected": false, "text": "<p>If you're blocking in a third-party library that loops on EINTR, you might want to consider a combination of using pthread_kill with a signal (USR1 etc) calling an empty function (not SIG_IGN) with actually closing/replacing the file descriptor in question. By using dup2 to replace the fd with /dev/null or similar, you'll cause the third-party library to get an end-of-file result when it retries the read.</p>\n\n<p>Note that by dup()ing the original socket first, you can avoid needing to actually close the socket.</p>\n" }, { "answer_id": 3800023, "author": "qqq", "author_id": 458979, "author_profile": "https://Stackoverflow.com/users/458979", "pm_score": 4, "selected": false, "text": "<p>The canonical way to do this is with <code>pthread_cancel</code>, where the thread has done <code>pthread_cleanup_push</code>/<code>pop</code> to provide cleanup for any resources it is using.</p>\n\n<p>Unfortunately this can NOT be used in C++ code, ever. Any C++ std lib code, or ANY <code>try {} catch()</code> on the calling stack at the time of <code>pthread_cancel</code> will potentially segvi killing your whole process.</p>\n\n<p>The only workaround is to handle <code>SIGUSR1</code>, setting a stop flag, <code>pthread_kill(SIGUSR1)</code>, then anywhere the thread is blocked on I/O, if you get <code>EINTR</code> check the stop flag before retrying the I/O. In practice, this does not always succeed on Linux, don't know why.</p>\n\n<p>But in any case it's useless to talk about if you have to call any 3rd party lib, because they will most likely have a tight loop that simply restarts I/O on <code>EINTR</code>. Reverse engineering their file descriptor to close it won't cut it either—they could be waiting on a semaphore or other resource. In this case, it is simply impossible to write working code, period. Yes, this is utterly brain-damaged. Talk to the guys who designed C++ exceptions and <code>pthread_cancel</code>. Supposedly this may be fixed in some future version of C++. Good luck with that.</p>\n" }, { "answer_id": 36854661, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 4, "selected": true, "text": "<p>Old question which could very well get a new answer as things have evolved and a new technology is now available to <em>better</em> handle signals in threads.</p>\n\n<p>Since Linux kernel 2.6.22, the system offers a new function called <code>signalfd()</code> which can be used to open a file descriptor for a given set of Unix signals (outside of those that outright kill a process.)</p>\n\n<pre><code>// defined a set of signals\nsigset_t set;\nsigemptyset(&amp;set);\nsigaddset(&amp;set, SIGUSR1);\n// ... you can add more than one ...\n\n// prevent the default signal behavior (very important)\nsigprocmask(SIG_BLOCK, &amp;set, nullptr);\n\n// open a file descriptor using that set of Unix signals\nf_socket = signalfd(-1, &amp;set, SFD_NONBLOCK | SFD_CLOEXEC);\n</code></pre>\n\n<p>Now you can use the <code>poll()</code> or <code>select()</code> functions to listen to the signal along the more usual file descriptor (socket, file on disk, etc.) you were listening on.</p>\n\n<p>The NONBLOCK is important if you want a loop that can check signals and other file descriptors over and over again (i.e. it is also important on your other file descriptor).</p>\n\n<p>I have such an implementation that works with (1) timers, (2) sockets, (3) pipes, (4) Unix signals, (5) regular files. Actually, really any file descriptor plus timers.</p>\n\n<p><a href=\"https://github.com/m2osw/snapcpp/blob/master/snapwebsites/libsnapwebsites/src/snapwebsites/snap_communicator.cpp\" rel=\"nofollow noreferrer\">https://github.com/m2osw/snapcpp/blob/master/snapwebsites/libsnapwebsites/src/snapwebsites/snap_communicator.cpp</a><br>\n<a href=\"https://github.com/m2osw/snapcpp/blob/master/snapwebsites/libsnapwebsites/src/snapwebsites/snap_communicator.h\" rel=\"nofollow noreferrer\">https://github.com/m2osw/snapcpp/blob/master/snapwebsites/libsnapwebsites/src/snapwebsites/snap_communicator.h</a></p>\n\n<p>You may also be interested by libraries such as <a href=\"http://libevent.org/\" rel=\"nofollow noreferrer\">libevent</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28113/" ]
I have a thread running in the background that is reading events from an input device in a blocking fashion, now when I exit the application I want to clean up the thread properly, but I can't just run a pthread\_join() because the thread would never exit due to the blocking IO. How do I properly solve that situation? Should I send a pthread\_kill(theard, SIGIO) or a pthread\_kill(theard, SIGALRM) to break the block? Is either of that even the right signal? Or is there another way to solve this situation and let that child thread exit the blocking read? Currently a bit puzzled since none of my googling turned up a solution. This is on Linux and using pthreads. Edit: I played around a bit with SIGIO and SIGALRM, when I don't install a signal handler they break the blocking IO up, but give a message on the console ("I/O possible") but when I install a signal handler, to avoid that message, they no longer break the blocking IO, so the thread doesn't terminate. So I am kind of back to step one.
Old question which could very well get a new answer as things have evolved and a new technology is now available to *better* handle signals in threads. Since Linux kernel 2.6.22, the system offers a new function called `signalfd()` which can be used to open a file descriptor for a given set of Unix signals (outside of those that outright kill a process.) ``` // defined a set of signals sigset_t set; sigemptyset(&set); sigaddset(&set, SIGUSR1); // ... you can add more than one ... // prevent the default signal behavior (very important) sigprocmask(SIG_BLOCK, &set, nullptr); // open a file descriptor using that set of Unix signals f_socket = signalfd(-1, &set, SFD_NONBLOCK | SFD_CLOEXEC); ``` Now you can use the `poll()` or `select()` functions to listen to the signal along the more usual file descriptor (socket, file on disk, etc.) you were listening on. The NONBLOCK is important if you want a loop that can check signals and other file descriptors over and over again (i.e. it is also important on your other file descriptor). I have such an implementation that works with (1) timers, (2) sockets, (3) pipes, (4) Unix signals, (5) regular files. Actually, really any file descriptor plus timers. <https://github.com/m2osw/snapcpp/blob/master/snapwebsites/libsnapwebsites/src/snapwebsites/snap_communicator.cpp> <https://github.com/m2osw/snapcpp/blob/master/snapwebsites/libsnapwebsites/src/snapwebsites/snap_communicator.h> You may also be interested by libraries such as [libevent](http://libevent.org/)
203,771
<p>I have been using CPPUnit as a unit testing framework and am now trying to use it in an automated build and package system. However a problem holding me back is that if a crash occurs during the running of the unit tests, e.g. a null pointer dereferencing, it halts the remainder of the automation.</p> <p>Is there any way for CPPUnit to recover from the exception, record the test failure and then exist gracefully rather than terminating the unit test process? Even an approach specific to null pointer dereferencing would be useful as that makes up about 90% of the issues I have had.</p> <p>To be technology-specific, I am using makefiles on a Windows system.</p>
[ { "answer_id": 203774, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<p>In C/C++, the best way to recover from errors like that is to run each test in a separate process and then monitor them from a parent process. This is very easy in UNIX -- just fork() before the test begins. <a href=\"http://check.sourceforge.net/\" rel=\"nofollow noreferrer\">check</a> supports this, and you could likely patch CPPUnit to have this behavior without much fuss.</p>\n" }, { "answer_id": 203889, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 3, "selected": true, "text": "<p>You're automating the execution of your cppunit-based unit-tests during your build process, right ? </p>\n\n<p>If you were trying to use CppUnit to execute the build process, I would be tempted to say don't do that !</p>\n\n<p>Could you tell us what is stopping the build process when the unit tests crash ? And what are your unit tests started by, a Makefile, a script of your own, or a <a href=\"http://en.wikipedia.org/wiki/Continuous_Integration#Software\" rel=\"nofollow noreferrer\">continuous integration framework</a> ? </p>\n\n<hr>\n\n<p>To try to answer your question, CppUnit cannot recover from violation or segmentation errors. On Unix-like systems you should be able to catch the SIGSEGV and to continue, <strong>but</strong> <strong>in which state</strong> ? </p>\n\n<p>If your crashes occur in your unit test and not in your product, then I'd recommend you to rely on <a href=\"http://xunitpatterns.com/Guard%20Assertion.html\" rel=\"nofollow noreferrer\">assertion guards</a> to prevent dereferencing NULL pointers:</p>\n\n<pre><code>class TestObject : public CPPUNIT_NS::TestCase\n{\n CPPUNIT_TEST_SUITE(Test);\n CPPUNIT_TEST(testObjectIsReady);\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n void setUp(void) {}\n void tearDown(void) {} \n\nprotected:\n void testObjectIsReady(void)\n { \n Object *theObject = GetObject();\n\n CPPUNIT_ASSERT_MESSAGE(\"check pointer is not null\", theObject != NULL);\n\n //--- now you can play with your object without dereferencing a NULL pointer\n CPPUNIT_ASSERT_MESSAGE(\"check objet is ready\", theObject-&gt;isReady());\n }\n};\n</code></pre>\n" }, { "answer_id": 480666, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Sorry to say this but the previous answers you received on this are ridiculous.\ncppunit really lacks in this regard. cppunit should implement an EXIT_ON_FAIL macro which allows you to trap the access violation in windows (using SetUnhandledExceptionFilter), then you can do any clean-up and allow cpp-unit to report the failure via EXIT_ON_FAIL. Then after reporting, exit the application. </p>\n" }, { "answer_id": 540094, "author": "dlanod", "author_id": 10247, "author_profile": "https://Stackoverflow.com/users/10247", "pm_score": 1, "selected": false, "text": "<p>As an additional note to anyone perusing this question later, I've found <a href=\"http://unittest-cpp.sourceforge.net/UnitTest++.html\" rel=\"nofollow noreferrer\">UnitTest++</a> can catch exceptions in tests and just fail the test with appropriate information rather than resulting in a process exit.</p>\n" }, { "answer_id": 1886433, "author": "Baiyan Huang", "author_id": 70198, "author_profile": "https://Stackoverflow.com/users/70198", "pm_score": 0, "selected": false, "text": "<p>I didn't try it, but if in Windows, I guess use SEH would help:</p>\n\n<pre><code>__try\n{\n// running your case\n}\n\n__except\n{\n}\n</code></pre>\n\n<p>Integrate it into the CppUnit framework, and everytime receive an unknown exception, mark the case as fail.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10247/" ]
I have been using CPPUnit as a unit testing framework and am now trying to use it in an automated build and package system. However a problem holding me back is that if a crash occurs during the running of the unit tests, e.g. a null pointer dereferencing, it halts the remainder of the automation. Is there any way for CPPUnit to recover from the exception, record the test failure and then exist gracefully rather than terminating the unit test process? Even an approach specific to null pointer dereferencing would be useful as that makes up about 90% of the issues I have had. To be technology-specific, I am using makefiles on a Windows system.
You're automating the execution of your cppunit-based unit-tests during your build process, right ? If you were trying to use CppUnit to execute the build process, I would be tempted to say don't do that ! Could you tell us what is stopping the build process when the unit tests crash ? And what are your unit tests started by, a Makefile, a script of your own, or a [continuous integration framework](http://en.wikipedia.org/wiki/Continuous_Integration#Software) ? --- To try to answer your question, CppUnit cannot recover from violation or segmentation errors. On Unix-like systems you should be able to catch the SIGSEGV and to continue, **but** **in which state** ? If your crashes occur in your unit test and not in your product, then I'd recommend you to rely on [assertion guards](http://xunitpatterns.com/Guard%20Assertion.html) to prevent dereferencing NULL pointers: ``` class TestObject : public CPPUNIT_NS::TestCase { CPPUNIT_TEST_SUITE(Test); CPPUNIT_TEST(testObjectIsReady); CPPUNIT_TEST_SUITE_END(); public: void setUp(void) {} void tearDown(void) {} protected: void testObjectIsReady(void) { Object *theObject = GetObject(); CPPUNIT_ASSERT_MESSAGE("check pointer is not null", theObject != NULL); //--- now you can play with your object without dereferencing a NULL pointer CPPUNIT_ASSERT_MESSAGE("check objet is ready", theObject->isReady()); } }; ```
203,787
<p>I have an object, that is facing a particular direction with (for instance) a 45 degree field of view, and a limit view range. I have done all the initial checks (Quadtree node, and distance), but now I need to check if a particular object is within that view cone, (In this case to decide only to follow that object if we can see it). </p> <p>Apart from casting a ray for each degree from <code>Direction - (FieldOfView / 2)</code> to <code>Direction + (FieldOfView / 2)</code> (I am doing that at the moment and it is horrible), what is the best way to do this visibility check?</p>
[ { "answer_id": 203802, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 4, "selected": true, "text": "<p>Compute the angle between your view direction (understood as a vector) and the vector that starts at you and ends at the object. If it falls under FieldOfView/2, you can view the object.</p>\n\n<p>That angle is: </p>\n\n<pre><code>arccos(scalarProduct(viewDirection, (object - you)) / (norm(viewDirection)*norm(object - you))).\n</code></pre>\n" }, { "answer_id": 203805, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 2, "selected": false, "text": "<p>If you're doing 3D and can define the viewing range as a frustrum, then you can use something similar to this <a href=\"http://www.flipcode.com/archives/Frustum_Culling.shtml\" rel=\"nofollow noreferrer\">Frustrum Culling</a> technique.</p>\n" }, { "answer_id": 203806, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 2, "selected": false, "text": "<p>Get the angle between the viewer's heading vector and the vector from viewer to target. If that angle is less than (FieldOfView/2), then the target is in the viewer's field of view.</p>\n\n<p>If your vectors are 2d or 3d this will work the same way. (In 3D, if you have a view frustum instead of cone, then you'll need to separate the angles into two components.) You just need to find the angle between the two vectors.</p>\n\n<p>If you want to test targets which are larger than a single point, you'll need multiple points for each target, such as the corners of a bounding box. If the vector from viewer to any of these points gives an angle inside the field of view, then that corner of the box is visible.</p>\n" }, { "answer_id": 254086, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 4, "selected": false, "text": "<p>I've worked in the video game industry, and I can say that doing trig functions like arccos every frame is less than ideal. Instead, you precompute the cosine of the angle for the cone:</p>\n\n<pre><code>float cos_angle = cos(PI/4); // 45 degrees, for example\n</code></pre>\n\n<p>Then, each frame you can quickly check if a point falls inside that cone by comparing that with the dot product of the cone and the .</p>\n\n<pre><code>vector test_point_vector = normalize(test_point_loc - cone_origin);\nfloat dot_product = dot(normalized_cone_vector, text_point_vector);\nbool inside_code = dot_product &gt; cos_angle;\n</code></pre>\n\n<p>There are no trig functions, just some multiplication, division, and addition. Most game engines have an optimized normalize() function for vectors.</p>\n\n<p>This works because of this equation:</p>\n\n<pre><code>A · B = |A| * |B| * cos(Θ)\n</code></pre>\n\n<p>If you normalize the vectors (A -> An), the equation is simplified:</p>\n\n<pre><code>An · Bn = cos(Θ)\n</code></pre>\n" }, { "answer_id": 1082114, "author": "Mizipzor", "author_id": 56763, "author_profile": "https://Stackoverflow.com/users/56763", "pm_score": 2, "selected": false, "text": "<p>Good answers already but I just wanted to give you a link to the Wolfire blog, they recently started a algebra series that take the \"field of view\" equation as one example. <a href=\"http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-2/\" rel=\"nofollow noreferrer\">Go read it</a>, its well written and easy. </p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24793/" ]
I have an object, that is facing a particular direction with (for instance) a 45 degree field of view, and a limit view range. I have done all the initial checks (Quadtree node, and distance), but now I need to check if a particular object is within that view cone, (In this case to decide only to follow that object if we can see it). Apart from casting a ray for each degree from `Direction - (FieldOfView / 2)` to `Direction + (FieldOfView / 2)` (I am doing that at the moment and it is horrible), what is the best way to do this visibility check?
Compute the angle between your view direction (understood as a vector) and the vector that starts at you and ends at the object. If it falls under FieldOfView/2, you can view the object. That angle is: ``` arccos(scalarProduct(viewDirection, (object - you)) / (norm(viewDirection)*norm(object - you))). ```
203,807
<p>I have a VB application which extracts data and creates 3 CSV files (a.csv, b.csv, c.csv). Then I use another Excel spreadsheet (import.xls) to import all the data from the above CSV files into this sheet.</p> <p>import.xls file has a macro which opens the CSV files one by one and copies the data. The problem I am facing is the dates in the CSV files are stored as mm/dd/yyyy and this is copied as is to the Excel sheet. But I want the date in dd/mm/yyy format.</p> <p>When I open any of the CSV files manually the dates are displayed in the correct format (mm/dd/yyyy). Any idea how I can solve this issue?</p>
[ { "answer_id": 203812, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>When I run into this problem I usually write out the dates as yyyy-mm-dd which Excel will interpret unambiguously.</p>\n" }, { "answer_id": 203814, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 4, "selected": true, "text": "<p>You can use the <strong>Format</strong> VBA function:</p>\n\n<pre><code>Format(DateText, \"dd/mm/yyyy\")\n</code></pre>\n\n<p>That will format it how ever you like.</p>\n\n<p>For a more permanant solution, try changing your regional settings in windows itself, Excel uses this for its date formatting.</p>\n\n<p>Start -> Settings -> Control Panel -> Regional Options. </p>\n\n<p>Make sure that the language is set to whatever is appropriate and that the date settings are as you want them to be</p>\n" }, { "answer_id": 203893, "author": "SpyJournal", "author_id": 10326, "author_profile": "https://Stackoverflow.com/users/10326", "pm_score": 1, "selected": false, "text": "<p>First of all the other answers are all good but theres some more information you might find helpful</p>\n\n<p>A CSV file only contains text. That is the data is not in date format but in a text format. So when you open a CSV file in Excel, Excel by default interprets that data for you. It doesn't have to. You could force it to leave it as text, Or as mentioned by Mark you can add code into your import macro that alters it for you.\nIf you want an automated process then this is the best solution. Simply add the code in VBA to the macro that applies the required date format to the column with the date data.\nAlternatively you could do this manually after the file is open and the data has been pasted by selecting the column yourself and chancing the format. You can customise number formats (choose custom) and then write it up yourself. Eg dd/mm/yyyy.</p>\n" }, { "answer_id": 264992, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem and solved it like this, essentially it is the 'all of the above' option</p>\n\n<ol>\n<li>With <code>format(date,'dd-mmm-yyyy')</code>\nconvert the date to the 2-3-4 format\ne.g.01-aug-2008, no way a computer\nmistakes 01-aug for 08-jan :-)</li>\n<li>Since copying this in excel\nautomatically reverts it back to the\ndate/time format, convert the result\nto a string by using <code>cstr</code> on the\nfunction in 1</li>\n<li>Format the cells in which the date\nis copied as text (if you don't,\nthickheaded as excel is, it will\nconvert it back to date / time again</li>\n<li>Save the sheet as a csv file and\nopen in notepad to confirm it has\nworked</li>\n</ol>\n\n<p>Some people may say it's overkill, but better be on the safe side, than having a user call me a year from now and telling me it's doing something strange with the date's</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12178/" ]
I have a VB application which extracts data and creates 3 CSV files (a.csv, b.csv, c.csv). Then I use another Excel spreadsheet (import.xls) to import all the data from the above CSV files into this sheet. import.xls file has a macro which opens the CSV files one by one and copies the data. The problem I am facing is the dates in the CSV files are stored as mm/dd/yyyy and this is copied as is to the Excel sheet. But I want the date in dd/mm/yyy format. When I open any of the CSV files manually the dates are displayed in the correct format (mm/dd/yyyy). Any idea how I can solve this issue?
You can use the **Format** VBA function: ``` Format(DateText, "dd/mm/yyyy") ``` That will format it how ever you like. For a more permanant solution, try changing your regional settings in windows itself, Excel uses this for its date formatting. Start -> Settings -> Control Panel -> Regional Options. Make sure that the language is set to whatever is appropriate and that the date settings are as you want them to be
203,809
<p>This might be a little hard to explain, but I will try.</p> <p>I want to display a list of categories (stored in 1 table), and number of domains associated with each category (stored in another table). </p> <p>The monkey wrench in this case is that each domain has a set of records associated with it (which are stored in a 3rd table). I only want to show the categories that have domains associated with them, and the count of domains should reflect only the domains that have records associated with them (from the 3rd table).</p> <p>My current query</p> <pre><code>SELECT r.rev_id, c.cat_id, c.cat_name, count(d.dom_id) As rev_id_count FROM reviews r INNER JOIN domains d ON r.rev_domain_from=d.dom_id INNER JOIN categories c ON d.dom_catid=c.cat_id WHERE rev_status = 1 GROUP BY cat_name ORDER BY cat_name </code></pre> <p>This selects the correct category names, but shows a false count (rev_id_count). If the category has 2 domains in it, and each domain has 2 records, it will show count of 4, when it should be 2.</p>
[ { "answer_id": 203815, "author": "AquilaX", "author_id": 17734, "author_profile": "https://Stackoverflow.com/users/17734", "pm_score": 0, "selected": false, "text": "<p>Something like this?</p>\n\n<pre><code>SELECT c.name, count(d.id)\nFROM categories c\nJOIN domains d ON c.id = d.cid\nJOIN records r ON r.did = d.id\nGROUP BY c.name;\n</code></pre>\n" }, { "answer_id": 203851, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 0, "selected": false, "text": "<p>Start off by selecting the domain that has records - and then pull in the categories that match the domain.</p>\n\n<p>so something like</p>\n\n<pre><code> SELECT * FROM records \n INNER JOIN domains on &lt;clause&gt; \n INNER JOIN categories on &lt;clause&gt;\n WHERE &lt;something&gt;\n</code></pre>\n\n<p>I can't explain this too well, but all too often when writing SQL it is easy to look at things from the list of fields we want in the select and tend to use that to dictate the way we use the tables to build the data. In fact we should look more at how the data is related to the query we're building (which often seems back to front).</p>\n" }, { "answer_id": 203869, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 0, "selected": false, "text": "<p>Extending on AquilaX's solution, you just need to select the name of the domain:</p>\n\n<pre><code>SELECT c.name, d.name, count(d.id)\n FROM categories c\n JOIN domains d ON c.id = d.cid\n JOIN records r ON r.did = d.id\nGROUP BY c.name, d.name;\n</code></pre>\n\n<p>Which should show:</p>\n\n<pre><code>Cat 1, Domain 1, 2\nCat 1, Domain 2, 1\nCat 2, Domain 3, 5\n</code></pre>\n\n<p>etc...</p>\n\n<p><em>(not tested though)</em></p>\n" }, { "answer_id": 203887, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<pre><code>select c.name, count(distinct d.did) from domains d\n left join categories c on c.cid = d.cid\n left join records r on r.did = d.did\n group by c.name\n</code></pre>\n\n<p>tested with 2 categories, 2 domains per categories, random number of records per domain. result set:</p>\n\n<pre><code>name count\n---- ----- \ntest 2\ntest2 2\n</code></pre>\n" }, { "answer_id": 203892, "author": "Mathias", "author_id": 7241, "author_profile": "https://Stackoverflow.com/users/7241", "pm_score": 3, "selected": true, "text": "<pre><code>SELECT Categories.Name,count(DISTINCT categories.name) FROM Categories\nJOIN Domains ON Categories.ID=Domains.CID\nJOIN Records ON Records.DID=Domains.ID\nGROUP BY Categories.Name</code></pre>\n\n<p>Tested with following setup:</p>\n\n<pre><code>\nCREATE TABLE Categories (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1))\nCREATE TABLE Domains (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1), CID int)\nCREATE TABLE Records (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1), DID int)\n\nINSERT INTO Records (DID) VALUES (1)\nINSERT INTO Records (DID) VALUES (1)\nINSERT INTO Records (DID) VALUES (2)\nINSERT INTO Records (DID) VALUES (2)\nINSERT INTO Records (DID) VALUES (3)\nINSERT INTO Records (DID) VALUES (3)\n\nINSERT INTO Domains (Name,CID) VALUES ('D1',1)\nINSERT INTO Domains (Name,CID) VALUES ('D2',1)\nINSERT INTO Domains (Name,CID) VALUES ('D5',1)\nINSERT INTO Domains (Name,CID) VALUES ('D3',2)\nINSERT INTO Domains (Name,CID) VALUES ('D4',2)\n\nINSERT INTO Categories (Name) VALUES ('1')\nINSERT INTO Categories (Name) VALUES ('2')\nINSERT INTO Categories (Name) VALUES ('3')\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This might be a little hard to explain, but I will try. I want to display a list of categories (stored in 1 table), and number of domains associated with each category (stored in another table). The monkey wrench in this case is that each domain has a set of records associated with it (which are stored in a 3rd table). I only want to show the categories that have domains associated with them, and the count of domains should reflect only the domains that have records associated with them (from the 3rd table). My current query ``` SELECT r.rev_id, c.cat_id, c.cat_name, count(d.dom_id) As rev_id_count FROM reviews r INNER JOIN domains d ON r.rev_domain_from=d.dom_id INNER JOIN categories c ON d.dom_catid=c.cat_id WHERE rev_status = 1 GROUP BY cat_name ORDER BY cat_name ``` This selects the correct category names, but shows a false count (rev\_id\_count). If the category has 2 domains in it, and each domain has 2 records, it will show count of 4, when it should be 2.
``` SELECT Categories.Name,count(DISTINCT categories.name) FROM Categories JOIN Domains ON Categories.ID=Domains.CID JOIN Records ON Records.DID=Domains.ID GROUP BY Categories.Name ``` Tested with following setup: ``` CREATE TABLE Categories (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1)) CREATE TABLE Domains (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1), CID int) CREATE TABLE Records (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1), DID int) INSERT INTO Records (DID) VALUES (1) INSERT INTO Records (DID) VALUES (1) INSERT INTO Records (DID) VALUES (2) INSERT INTO Records (DID) VALUES (2) INSERT INTO Records (DID) VALUES (3) INSERT INTO Records (DID) VALUES (3) INSERT INTO Domains (Name,CID) VALUES ('D1',1) INSERT INTO Domains (Name,CID) VALUES ('D2',1) INSERT INTO Domains (Name,CID) VALUES ('D5',1) INSERT INTO Domains (Name,CID) VALUES ('D3',2) INSERT INTO Domains (Name,CID) VALUES ('D4',2) INSERT INTO Categories (Name) VALUES ('1') INSERT INTO Categories (Name) VALUES ('2') INSERT INTO Categories (Name) VALUES ('3') ```
203,823
<p>One of classes in my program uses some third-party library. Library object is a private member of my class:</p> <pre><code>// My.h #include &lt;3pheader.h&gt; class My { ... private: 3pObject m_object; } </code></pre> <p>The problem with this - any other unit in my program that uses My class should be configured to include 3p headers. Moving to another kind of 3p will jeopardize the whole build... I see two ways to fix this - one is to is to make 3pObject extern and turn m_Object into a pointer, being initialized in constructor; second is to create an "interface" and "factory" classes and export them...</p> <p>Could you suggest another ways to solve that ?</p>
[ { "answer_id": 203828, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>The Private Implementation (PIMPL) pattern:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/tips/PIMPL.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/tips/PIMPL.aspx</a></p>\n\n<p>Basically, you define that your class holds a pointer to a struct that you forward declare. Then you define the struct inside the cpp file and use the constructor and destructor in your class to create/delete the PIMPL.</p>\n\n<p>:)</p>\n" }, { "answer_id": 203830, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": true, "text": "<p>Use the \"pimpl\" idiom:</p>\n\n<pre><code>// header\nclass My\n{\n class impl;\n std::auto_ptr&lt;impl&gt; _impl;\n};\n\n// cpp\n#include &lt;3pheader.h&gt;\nclass My::impl\n{\n 3pObject _object;\n};\n</code></pre>\n" }, { "answer_id": 203856, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 0, "selected": false, "text": "<p>All of the internal structure of <a href=\"http://trolltech.com/products\" rel=\"nofollow noreferrer\">QT</a> is done using private implementation classes.<br>\nYou can look it up for a good reference on how it is done correctly.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18174/" ]
One of classes in my program uses some third-party library. Library object is a private member of my class: ``` // My.h #include <3pheader.h> class My { ... private: 3pObject m_object; } ``` The problem with this - any other unit in my program that uses My class should be configured to include 3p headers. Moving to another kind of 3p will jeopardize the whole build... I see two ways to fix this - one is to is to make 3pObject extern and turn m\_Object into a pointer, being initialized in constructor; second is to create an "interface" and "factory" classes and export them... Could you suggest another ways to solve that ?
Use the "pimpl" idiom: ``` // header class My { class impl; std::auto_ptr<impl> _impl; }; // cpp #include <3pheader.h> class My::impl { 3pObject _object; }; ```
203,844
<p>I have a form with multiple fields that I'm validating (some with methods added for custom validation) with Jörn Zaeffere's excellent jQuery Validation plugin. How do you circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls.</p> <p>My situation:</p> <p>It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted, validation fires but instead of a "required" message displaying, a "recommendation" shows that says something along the line of "you missed the following fields.... do you wish to proceed anyways?" At that point in the error container there's another submit button now visible that can be pressed which would ignore the validation and submit anyways. How to circumvent the forms .validate() for this button control and still post?</p> <p>The Buy and Sell a House sample at <a href="http://jquery.bassistance.de/validate/demo/multipart/" rel="noreferrer">http://jquery.bassistance.de/validate/demo/multipart/</a> allows for this in order to hit the previous links, but it does so through creating custom methods and adding it to the validator. I would prefer to not have to create custom methods duplicating functionality already in the validation plugin.</p> <p>The following is a shortened version of the immediately applicable script that I've got right now:</p> <pre><code>var container = $("#&lt;%= Form.ClientID %&gt; div.validationSuggestion"); $('#&lt;%= Form.ClientID %&gt;').validate({ errorContainer: container, errorLabelContainer: $("ul",container), rules: { &lt;%= YesNo.UniqueID %&gt;: { required: true }, &lt;%= ShortText.UniqueID %&gt;: { required: true } // etc. }, messages: { &lt;%= YesNo.UniqueID %&gt;: 'A message.', &lt;%= ShortText.UniqueID %&gt;: 'Another message.' // etc. }, highlight: function(element, errorClass) { $(element).addClass(errorClass); $(element.form).find("label[for=" + element.id + "]").addClass(errorClass); $(element.form).find("label[for=" + element.id + "]").removeClass("valid"); }, unhighlight: function(element, errorClass) { $(element).removeClass(errorClass); $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass); $(element.form).find("label[for=" + element.id + "]").addClass("valid"); }, wrapper: 'li' }); </code></pre>
[ { "answer_id": 203989, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 9, "selected": true, "text": "<p>You can add a CSS class of <code>cancel</code> to a submit button to suppress the validation</p>\n\n<p>e.g</p>\n\n<pre><code>&lt;input class=\"cancel\" type=\"submit\" value=\"Save\" /&gt;\n</code></pre>\n\n<p>See the jQuery Validator documentation of this feature here: <a href=\"https://jqueryvalidation.org/reference#link-skipping-validation-on-submit\" rel=\"noreferrer\">Skipping validation on submit</a></p>\n\n<hr>\n\n<p><strong>EDIT</strong>:</p>\n\n<p>The above technique has been deprecated and replaced with the <code>formnovalidate</code> attribute.</p>\n\n<pre><code>&lt;input formnovalidate=\"formnovalidate\" type=\"submit\" value=\"Save\" /&gt;\n</code></pre>\n" }, { "answer_id": 1196645, "author": "BrokeMyLegBiking", "author_id": 97686, "author_profile": "https://Stackoverflow.com/users/97686", "pm_score": 3, "selected": false, "text": "<p>You can use the <strong>onsubmit:false</strong> option (see <a href=\"http://docs.jquery.com/Plugins/Validation/validate#toptions\" rel=\"noreferrer\">documentation</a>) when wiring up validation which will not validate on submission of the form. And then in your asp:button add an OnClientClick= $('#aspnetForm').valid(); to explicitly check if form is valid.</p>\n\n<p>You could call this the opt-in model, instead of the opt-out described above.</p>\n\n<p>Note, I am also using jquery validation with ASP.NET WebForms. There are some issues to navigate but once you get through them, the user experience is very good.</p>\n" }, { "answer_id": 2879499, "author": "lepe", "author_id": 196507, "author_profile": "https://Stackoverflow.com/users/196507", "pm_score": 7, "selected": false, "text": "<p>Other (undocumented) way to do it, is to call:</p>\n\n<pre><code>$(\"form\").validate().cancelSubmit = true;\n</code></pre>\n\n<p>on the click event of the button (for example).</p>\n" }, { "answer_id": 17401929, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 2, "selected": false, "text": "<p>(Extension of <code>@lepe</code>'s and <code>@redsquare</code> answer for <code>ASP.NET MVC</code> + <code>jquery.validate.unobtrusive.js</code>)</p>\n\n<hr>\n\n<p>The <a href=\"http://jqueryvalidation.org/reference/\" rel=\"nofollow\">jquery validation plugin</a> (not the Microsoft unobtrusive one) allows you to put a <code>.cancel</code> class on your submit button to bypass validation completely (as shown in accepted answer).</p>\n\n<pre><code> To skip validation while still using a submit-button, add a class=\"cancel\" to that input.\n\n &lt;input type=\"submit\" name=\"submit\" value=\"Submit\"/&gt;\n &lt;input type=\"submit\" class=\"cancel\" name=\"cancel\" value=\"Cancel\"/&gt;\n</code></pre>\n\n<p>(don't confuse this with <a href=\"http://www.electrictoolbox.com/html-form-reset-input/\" rel=\"nofollow\"><code>type='reset'</code></a> which is something completely different)</p>\n\n<p>Unfortunately the <code>jquery.validation.unobtrusive.js</code> validation handling (ASP.NET MVC) code kinda screws up the <a href=\"http://jqueryvalidation.org/reference/\" rel=\"nofollow\">jquery.validate plugin's default behavior</a>.</p>\n\n<p>This is what I came up with to allow you to put <code>.cancel</code> on the submit button as shown above. If Microsoft ever 'fixes' this then you can just remvoe this code.</p>\n\n<pre><code> // restore behavior of .cancel from jquery validate to allow submit button \n // to automatically bypass all jquery validation\n $(document).on('click', 'input[type=image].cancel,input[type=submit].cancel', function (evt)\n {\n // find parent form, cancel validation and submit it\n // cancelSubmit just prevents jQuery validation from kicking in\n $(this).closest('form').data(\"validator\").cancelSubmit = true;\n $(this).closest('form').submit();\n return false;\n });\n</code></pre>\n\n<p>Note: If at first try it appears that this isn't working - make sure you're not roundtripping to the server and seeing a server generated page with errors. You'll need to bypass validation on the server side by some other means - this just allows the form to be submitted client side without errors (the alternative would be adding <code>.ignore</code> attributes to everything in your form).</p>\n\n<p>(Note: you may need to add <code>button</code> to the selector if you're using buttons to submit)</p>\n" }, { "answer_id": 27642144, "author": "bradlis7", "author_id": 179311, "author_profile": "https://Stackoverflow.com/users/179311", "pm_score": 1, "selected": false, "text": "<p>This question is old, but I found another way around it is to use <code>$('#formId')[0].submit()</code>, which gets the dom element instead of the jQuery object, thus bypassing any validation hooks. This button submits the parent form that contains the input.</p>\n\n<pre><code>&lt;input type='button' value='SubmitWithoutValidation' onclick='$(this).closest('form')[0].submit()'/&gt;\n</code></pre>\n\n<p>Also, make sure you don't have any <code>input</code>'s named \"submit\", or it overrides the function named <code>submit</code>.</p>\n" }, { "answer_id": 29615155, "author": "TastyCode", "author_id": 949827, "author_profile": "https://Stackoverflow.com/users/949827", "pm_score": 4, "selected": false, "text": "<p>Add formnovalidate attribute to input</p>\n\n<pre><code> &lt;input type=\"submit\" name=\"go\" value=\"Submit\"&gt; \n &lt;input type=\"submit\" formnovalidate name=\"cancel\" value=\"Cancel\"&gt; \n</code></pre>\n\n<p>Adding class=\"cancel\" is now deprecated</p>\n\n<p>See docs for Skipping validation on submit on this <a href=\"http://jqueryvalidation.org/reference#skipping-validation-on-submit\">link</a></p>\n" }, { "answer_id": 31665025, "author": "Daniel Garcia", "author_id": 259824, "author_profile": "https://Stackoverflow.com/users/259824", "pm_score": 5, "selected": false, "text": "<p>Yet another (dynamic) way:</p>\n\n<pre><code>$(\"form\").validate().settings.ignore = \"*\";\n</code></pre>\n\n<p>And to re-enable it, we just set back the default value:</p>\n\n<pre><code>$(\"form\").validate().settings.ignore = \":hidden\";\n</code></pre>\n\n<p>Source: <a href=\"https://github.com/jzaefferer/jquery-validation/issues/725#issuecomment-17601443\" rel=\"noreferrer\">https://github.com/jzaefferer/jquery-validation/issues/725#issuecomment-17601443</a></p>\n" }, { "answer_id": 39412871, "author": "Scott Mayers", "author_id": 4670975, "author_profile": "https://Stackoverflow.com/users/4670975", "pm_score": 1, "selected": false, "text": "<p>I found that the most flexible way is to do use JQuery's:</p>\n\n<pre><code>event.preventDefault():\n</code></pre>\n\n<p>E.g. if instead of submitting I want to redirect, I can do:</p>\n\n<pre><code>$(\"#redirectButton\").click(function( event ) {\n event.preventDefault();\n window.location.href='http://www.skip-submit.com';\n});\n</code></pre>\n\n<p>or I can send the data to a different endpoint (e.g. if I want to change the action):</p>\n\n<pre><code>$(\"#saveButton\").click(function( event ) {\n event.preventDefault();\n var postData = $('#myForm').serialize();\n var jqxhr = $.post('http://www.another-end-point.com', postData ,function() {\n }).done(function() {\n alert(\"Data sent!\");\n }).fail(function(jqXHR, textStatus, errorThrown) {\n alert(\"Ooops, we have an error\");\n })\n</code></pre>\n\n<p>Once you do 'event.preventDefault();' you bypass validation.</p>\n" }, { "answer_id": 41952058, "author": "Bugfixer", "author_id": 2050394, "author_profile": "https://Stackoverflow.com/users/2050394", "pm_score": 1, "selected": false, "text": "<p>I have two button for form submission, button named save and exit bypasses the validation :</p>\n\n<pre><code>$('.save_exist').on('click', function (event) {\n $('#MyformID').removeData('validator');\n $('.form-control').removeClass('error');\n $('.form-control').removeClass('required'); \n $(\"#loanApplication\").validate().cancelSubmit = true;\n $('#loanApplication').submit();\n event.preventDefault();\n});\n</code></pre>\n" }, { "answer_id": 48323384, "author": "Davide Ciarmiello", "author_id": 7752815, "author_profile": "https://Stackoverflow.com/users/7752815", "pm_score": 2, "selected": false, "text": "<pre><code>$(\"form\").validate().settings.ignore = \"*\";\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>$(\"form\").validate().cancelSubmit = true;\n</code></pre>\n\n<p>But without success in a custom required validator. For call a submit dynamically, i have created a fake hidden submit button with this code:</p>\n\n<pre><code>var btn = form.children('input.cancel.fakeSubmitFormButton');\nif (btn.length === 0) {\n btn = $('&lt;input name=\"FakeCancelSubmitButton\" class=\"cancel fakeSubmitFormButton hide\" type=\"submit\" formnovalidate value=\"FakeCancelSubmitButton\" /&gt;');\n form.append(btn);\n}\nbtn.click();\n</code></pre>\n\n<p>Now skip the validation correctly :)</p>\n" }, { "answer_id": 53108235, "author": "Lucy", "author_id": 8808260, "author_profile": "https://Stackoverflow.com/users/8808260", "pm_score": 0, "selected": false, "text": "<p>Here is the simplest version, hope it helps someone,</p>\n\n<pre><code>$('#cancel-button').click(function() {\n var $form = $(this).closest('form');\n $form.find('*[data-validation]').attr('data-validation', null);\n $form.get(0).submit();\n});\n</code></pre>\n" }, { "answer_id": 63010987, "author": "user3024034", "author_id": 3024034, "author_profile": "https://Stackoverflow.com/users/3024034", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;button type=&quot;submit&quot; formnovalidate=&quot;formnovalidate&quot;&gt;submit&lt;/button&gt;\n</code></pre>\n<p>also working</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9344/" ]
I have a form with multiple fields that I'm validating (some with methods added for custom validation) with Jörn Zaeffere's excellent jQuery Validation plugin. How do you circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls. My situation: It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted, validation fires but instead of a "required" message displaying, a "recommendation" shows that says something along the line of "you missed the following fields.... do you wish to proceed anyways?" At that point in the error container there's another submit button now visible that can be pressed which would ignore the validation and submit anyways. How to circumvent the forms .validate() for this button control and still post? The Buy and Sell a House sample at <http://jquery.bassistance.de/validate/demo/multipart/> allows for this in order to hit the previous links, but it does so through creating custom methods and adding it to the validator. I would prefer to not have to create custom methods duplicating functionality already in the validation plugin. The following is a shortened version of the immediately applicable script that I've got right now: ``` var container = $("#<%= Form.ClientID %> div.validationSuggestion"); $('#<%= Form.ClientID %>').validate({ errorContainer: container, errorLabelContainer: $("ul",container), rules: { <%= YesNo.UniqueID %>: { required: true }, <%= ShortText.UniqueID %>: { required: true } // etc. }, messages: { <%= YesNo.UniqueID %>: 'A message.', <%= ShortText.UniqueID %>: 'Another message.' // etc. }, highlight: function(element, errorClass) { $(element).addClass(errorClass); $(element.form).find("label[for=" + element.id + "]").addClass(errorClass); $(element.form).find("label[for=" + element.id + "]").removeClass("valid"); }, unhighlight: function(element, errorClass) { $(element).removeClass(errorClass); $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass); $(element.form).find("label[for=" + element.id + "]").addClass("valid"); }, wrapper: 'li' }); ```
You can add a CSS class of `cancel` to a submit button to suppress the validation e.g ``` <input class="cancel" type="submit" value="Save" /> ``` See the jQuery Validator documentation of this feature here: [Skipping validation on submit](https://jqueryvalidation.org/reference#link-skipping-validation-on-submit) --- **EDIT**: The above technique has been deprecated and replaced with the `formnovalidate` attribute. ``` <input formnovalidate="formnovalidate" type="submit" value="Save" /> ```
203,854
<p>Example. 123456, and we want the third from the right ('4') out.</p> <p>The idea in practise is to access each digit seperately (ie. 6 5 4 3 2 1).</p> <p>C/C++/C# preferred.</p>
[ { "answer_id": 203864, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": -1, "selected": false, "text": "<p>In C you could do something like the following, where n=0 would indicate the rightmost digit</p>\n\n<pre><code>char nthDigitFromRight(int x,int n)\n{\n char str[20];\n sprintf(str,\"%020d\",x);\n return(str[19 - x]);\n}\n</code></pre>\n\n<p>Change [19-x] to [20-x] if you want n=1 for rightmost digit.</p>\n" }, { "answer_id": 203874, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 2, "selected": false, "text": "<p>The reason that it won't work (easily) with bit-wise operations is that the base of the decimal system (10) is not a power of the base of the binary system (2).</p>\n\n<p>If you were coding in base 8, you'd have <code>pow(2, 3) == 8</code>, and could extract each octal digit as a block of three bits.</p>\n\n<p>So you really have to convert to base 10, which is usually done by converting to a string (with toString (Java) or sprintf (C), as the others have shown in their replies).</p>\n" }, { "answer_id": 203877, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "<p>A more efficient implementation might be something like this:</p>\n\n<pre><code>char nthdigit(int x, int n)\n{\n while (n--) {\n x /= 10;\n }\n return (x % 10) + '0';\n}\n</code></pre>\n\n<p>This saves the effort of converting all digits to string format if you only want one of them. And, you don't have to allocate space for the converted string.</p>\n\n<p>If speed is a concern, you could precalculate an array of powers of 10 and use n to index into this array:</p>\n\n<pre><code>char nthdigit(int x, int n)\n{\n static int powersof10[] = {1, 10, 100, 1000, ...};\n return ((x / powersof10[n]) % 10) + '0';\n}\n</code></pre>\n\n<p>As mentioned by others, this is as close as you are going to get to bitwise operations for base 10.</p>\n" }, { "answer_id": 203881, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": false, "text": "<p>Use base-10 math:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n int x = 123456;\n\n for (int i = 1; i &lt;= 6; i++)\n {\n Console.WriteLine(GetDigit(x, i));\n }\n }\n\n static int GetDigit(int number, int digit)\n {\n return (number / (int)Math.Pow(10, digit - 1)) % 10;\n }\n}\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>6\n5\n4\n3\n2\n1\n</code></pre>\n" }, { "answer_id": 203979, "author": "Karsten", "author_id": 28144, "author_profile": "https://Stackoverflow.com/users/28144", "pm_score": 0, "selected": false, "text": "<p>You could try a bitwise shift-left (for N-1) and then read the digit at [0], as this could be an assembler approach.</p>\n\n<p>123456 -> 456 -> read first digit</p>\n" }, { "answer_id": 204011, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 2, "selected": false, "text": "<p>This works for unsigned ints up to 451069, as explained <a href=\"http://www.cs.uiowa.edu/~jones/bcd/divide.html\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>def hundreds_digit(u): return mod10(div100(u))\n\ndef div100(u): return div10(div10(u))\ndef mod10(u): return u - mul10(div10(u))\ndef mul10(u): return ((u &lt;&lt; 2) + u) &lt;&lt; 1\n\ndef div10(u):\n Q = ((u &gt;&gt; 1) + u) &gt;&gt; 1 # Q = u*0.11\n Q = ((Q &gt;&gt; 4) + Q) # Q = u*0.110011\n Q = ((Q &gt;&gt; 8) + Q) &gt;&gt; 3 # Q = u*0.00011001100110011\n return Q\n\n# Alternatively:\n# def div100(u): return (u * 0xa3d7) &gt;&gt; 22\n# though that'd only work for 16-bit u values.\n# Or you could construct shifts and adds along the lines of div10(),\n# but I didn't go to the trouble.\n</code></pre>\n\n<p>Testing it out:</p>\n\n<pre><code>&gt;&gt;&gt; hundreds_digit(123456)\n4\n&gt;&gt;&gt; hundreds_digit(123956)\n9\n</code></pre>\n\n<p>I'd be surprised if it's faster, though. Maybe you should reconsider your problem.</p>\n" }, { "answer_id": 16094891, "author": "eselk", "author_id": 1042232, "author_profile": "https://Stackoverflow.com/users/1042232", "pm_score": 3, "selected": false, "text": "<p>Just spent time writing this based on answers here, so thought I would share.</p>\n\n<p>This is based on Brannon's answer, but lets you get more than one digit at a time. In my case I use it to extract parts from a date and time saved in an int where the digits are in yyyymmddhhnnssm_s format.</p>\n\n<pre><code>public static int GetDigits(this int number, int highestDigit, int numDigits)\n{\n return (number / (int)Math.Pow(10, highestDigit - numDigits)) % (int)Math.Pow(10, numDigits);\n}\n</code></pre>\n\n<p>I made it an extension, you might not want to, but here is sample usage:</p>\n\n<pre><code>int i = 20010607;\nstring year = i.GetDigits(8,4).ToString();\nstring month = i.GetDigits(4,2).ToString();\nstring day = i.GetDigits(2,2).ToString();\n</code></pre>\n\n<p>results:</p>\n\n<p>year = 2001</p>\n\n<p>month = 6</p>\n\n<p>day = 7</p>\n" }, { "answer_id": 26696263, "author": "Michael Peterson", "author_id": 211614, "author_profile": "https://Stackoverflow.com/users/211614", "pm_score": 1, "selected": false, "text": "<p><strong>value = (number % (10^position)) / 10^(position - 1)</strong></p>\n\n<p>Example:</p>\n\n<p>number = 23846</p>\n\n<p>position = 1 -> value = 6</p>\n\n<p>position = 2 -> value = 4</p>\n\n<p>position = 3 -> value = 8</p>\n\n<p><strong>Here is a simple Objective-C utility method to do this:</strong></p>\n\n<pre><code>+ (int)digitAtPosition:(int)pos of:(int)number {\n\n return (number % ((int)pow(10, pos))) / (int)pow(10, pos - 1);\n}\n</code></pre>\n" }, { "answer_id": 31288251, "author": "Sonal S.", "author_id": 1736902, "author_profile": "https://Stackoverflow.com/users/1736902", "pm_score": 0, "selected": false, "text": "<p>Following code will give nth digit from right in a number:</p>\n\n<pre><code>public void getDigit(long n,int k){\n int i=0;\n long r =0;\n while(i&lt;n){\n r=n%10;\n n=n/10;\n i++;\n }\n System.out.println( k + \"th digit from right \" + r);\n }\n</code></pre>\n" }, { "answer_id": 34098361, "author": "Evorlor", "author_id": 1889720, "author_profile": "https://Stackoverflow.com/users/1889720", "pm_score": 0, "selected": false, "text": "<p>Just for fun, here is the C# extension class for it:</p>\n\n<pre><code>public static class IntExtensions\n{\n /// &lt;summary&gt;\n /// Returns the nth digit from an int, \n /// where 0 is the least significant digit \n /// and n is the most significant digit.\n /// &lt;/summary&gt;\n public static int GetDigit(this int number, int digit)\n {\n for (int i = 0; i &lt; digit; i++)\n {\n number /= 10;\n }\n return number % 10;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>int myNumber = 12345;\nint five = myNumber.GetDigit(0);\nint four = myNumber.GetDigit(1);\nint three = myNumber.GetDigit(2);\nint two = myNumber.GetDigit(3);\nint one = myNumber.GetDigit(4);\nint zero = myNumber.GetDigit(5);\n</code></pre>\n" }, { "answer_id": 37766556, "author": "KLeviss XHyra", "author_id": 6454151, "author_profile": "https://Stackoverflow.com/users/6454151", "pm_score": -1, "selected": false, "text": "<pre><code>int returndigit(int n,int d)\n{\n d=d-1;\n while(d--)\n {\n n/=10;\n }\n return (n%10);\n}\n</code></pre>\n" }, { "answer_id": 49096726, "author": "Anandha Varman", "author_id": 9441949, "author_profile": "https://Stackoverflow.com/users/9441949", "pm_score": -1, "selected": false, "text": "<p>two digit d1 and d2 will be passed .the program must print the nth Number is the number system that consist only digit with d1 and d2\ninput format\nfirst line contain d1\nsecond line contain d2\nthird kine contain n\nd1 is not equal to d2</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24661/" ]
Example. 123456, and we want the third from the right ('4') out. The idea in practise is to access each digit seperately (ie. 6 5 4 3 2 1). C/C++/C# preferred.
A more efficient implementation might be something like this: ``` char nthdigit(int x, int n) { while (n--) { x /= 10; } return (x % 10) + '0'; } ``` This saves the effort of converting all digits to string format if you only want one of them. And, you don't have to allocate space for the converted string. If speed is a concern, you could precalculate an array of powers of 10 and use n to index into this array: ``` char nthdigit(int x, int n) { static int powersof10[] = {1, 10, 100, 1000, ...}; return ((x / powersof10[n]) % 10) + '0'; } ``` As mentioned by others, this is as close as you are going to get to bitwise operations for base 10.
203,859
<p>Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:</p> <p><a href="http://www.google.com/" rel="noreferrer">http://www.google.com/</a></p> <p>How do I get markdown to add tags to URLs when I format a block of text?</p>
[ { "answer_id": 203870, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>This isn't a feature of Markdown -- what you should do is run a post-processor against the text looking for a URL-like pattern. There's a good example in the <a href=\"http://google-app-engine-samples.googlecode.com/svn/trunk/cccwiki/wiki.py\" rel=\"nofollow noreferrer\">Google app engine example code</a> -- see the <code>AutoLink</code> transform.</p>\n" }, { "answer_id": 203973, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "<p>There's an extra for this in python-markdown2:</p>\n\n<p><a href=\"http://code.google.com/p/python-markdown2/wiki/LinkPatterns\" rel=\"nofollow noreferrer\">http://code.google.com/p/python-markdown2/wiki/LinkPatterns</a></p>\n" }, { "answer_id": 206486, "author": "andrewrk", "author_id": 432, "author_profile": "https://Stackoverflow.com/users/432", "pm_score": 2, "selected": false, "text": "<p>I was using the <a href=\"http://www.djangoproject.com/\" rel=\"nofollow noreferrer\">Django framework</a>, which has a filter called urlize, which does exactly what I wanted. However, it only works on plain text, so I couldn't pass is through the output of markdown. I followed <a href=\"https://docs.djangoproject.com/en/dev/howto/custom-template-tags/\" rel=\"nofollow noreferrer\">this guide</a> to create a custom filter called urlify2 which works on html, and passed the text through this filter:</p>\n\n<pre><code>&lt;div class=\"news_post\"&gt;\n {% autoescape off %}\n {{ post.content|markdown|urlify2}}\n {% endautoescape %}\n&lt;/div&gt;\n</code></pre>\n\n<p>The urlify2.py filter:</p>\n\n<pre><code>from django import template\nimport re\n\nregister = template.Library()\n\nurlfinder = re.compile(\"([0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9]{1,3}|((news|telnet|nttp|file|http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\\\.)[-A-Za-z0-9\\\\.]+):[0-9]*)?/[-A-Za-z0-9_\\\\$\\\\.\\\\+\\\\!\\\\*\\\\(\\\\),;:@&amp;=\\\\?/~\\\\#\\\\%]*[^]'\\\\.}&gt;\\\\),\\\\\\\"]\")\n\[email protected](\"urlify2\")\ndef urlify2(value):\n return urlfinder.sub(r'&lt;a href=\"\\1\"&gt;\\1&lt;/a&gt;', value)\n</code></pre>\n" }, { "answer_id": 215721, "author": "andrewrk", "author_id": 432, "author_profile": "https://Stackoverflow.com/users/432", "pm_score": 2, "selected": false, "text": "<p>Best case scenario, edit the markdown and just put &lt; > around the URLs. This will make the link clickable. Only problem is it requires educating your users, or whoever writes the markdown.</p>\n" }, { "answer_id": 828458, "author": "csytan", "author_id": 86568, "author_profile": "https://Stackoverflow.com/users/86568", "pm_score": 3, "selected": true, "text": "<p>I couldn't get superjoe30's regular expression to compile, so I adapted his solution to convert plain URLs (within Markdown text) to be Markdown compatible.</p>\n\n<p>The modified filter:</p>\n\n<pre><code>urlfinder = re.compile('^(http:\\/\\/\\S+)')\nurlfinder2 = re.compile('\\s(http:\\/\\/\\S+)')\[email protected]('urlify_markdown')\ndef urlify_markdown(value):\n value = urlfinder.sub(r'&lt;\\1&gt;', value)\n return urlfinder2.sub(r' &lt;\\1&gt;', value)\n</code></pre>\n\n<p>Within the template:</p>\n\n<pre><code>&lt;div&gt;\n {{ content|urlify_markdown|markdown}}\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 1665440, "author": "SamBarnes", "author_id": 168632, "author_profile": "https://Stackoverflow.com/users/168632", "pm_score": 3, "selected": false, "text": "<p>You could write an extension to markdown. Save this code as mdx_autolink.py</p>\n\n<pre><code>import markdown\nfrom markdown.inlinepatterns import Pattern\n\nEXTRA_AUTOLINK_RE = r'(?&lt;!\"|&gt;)((https?://|www)[-\\w./#?%=&amp;]+)'\n\nclass AutoLinkPattern(Pattern):\n\n def handleMatch(self, m):\n el = markdown.etree.Element('a')\n if m.group(2).startswith('http'):\n href = m.group(2)\n else:\n href = 'http://%s' % m.group(2)\n el.set('href', href)\n el.text = m.group(2)\n return el\n\nclass AutoLinkExtension(markdown.Extension):\n \"\"\"\n There's already an inline pattern called autolink which handles \n &lt;http://www.google.com&gt; type links. So lets call this extra_autolink \n \"\"\"\n\n def extendMarkdown(self, md, md_globals):\n md.inlinePatterns.add('extra_autolink', \n AutoLinkPattern(EXTRA_AUTOLINK_RE, self), '&lt;automail')\n\ndef makeExtension(configs=[]):\n return AutoLinkExtension(configs=configs)\n</code></pre>\n\n<p>Then use it in your template like this:</p>\n\n<pre><code>{% load markdown %}\n\n(( content|markdown:'autolink'))\n</code></pre>\n\n<p>Update:</p>\n\n<p>I've found an issue with this solution: When markdown's standard link syntax is used and the displayed portion matches the regular expression, eg:</p>\n\n<pre><code>[www.google.com](http://www.yahoo.co.uk)\n</code></pre>\n\n<p>strangely becomes:\n <a href=\"http://www.google.com\" rel=\"noreferrer\">www.google.com</a></p>\n\n<p>But who'd want to do that anyway?!</p>\n" }, { "answer_id": 42060153, "author": "chriscauley", "author_id": 266564, "author_profile": "https://Stackoverflow.com/users/266564", "pm_score": 1, "selected": false, "text": "<p>I know this question is almost a decade old, but markdown-urlize covers every possible use case I could think of including not requiring http(s):// before a url, leaving the parenthesis in <code>(google.com)</code>, removing the angle brackets from <code>&lt;google.com&gt;</code>, ignoring urls in code blocks, and more I hadn't thought of:</p>\n\n<p><a href=\"https://github.com/r0wb0t/markdown-urlize\" rel=\"nofollow noreferrer\">https://github.com/r0wb0t/markdown-urlize</a></p>\n\n<p>There's no pip install, but you can wget this:</p>\n\n<p><a href=\"https://raw.githubusercontent.com/r0wb0t/markdown-urlize/master/mdx_urlize.py\" rel=\"nofollow noreferrer\">https://raw.githubusercontent.com/r0wb0t/markdown-urlize/master/mdx_urlize.py</a></p>\n\n<p>and then either put the above file on the python path (first option) or not (second option) and then use one of the following:</p>\n\n<pre><code>markdown.markdown(text, extensions=['urlize'], safe_mode=True)\nmarkdown.markdown(text, extensions=['path.to.mdx_urlize'], safe_mode=True)\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one: <http://www.google.com/> How do I get markdown to add tags to URLs when I format a block of text?
I couldn't get superjoe30's regular expression to compile, so I adapted his solution to convert plain URLs (within Markdown text) to be Markdown compatible. The modified filter: ``` urlfinder = re.compile('^(http:\/\/\S+)') urlfinder2 = re.compile('\s(http:\/\/\S+)') @register.filter('urlify_markdown') def urlify_markdown(value): value = urlfinder.sub(r'<\1>', value) return urlfinder2.sub(r' <\1>', value) ``` Within the template: ``` <div> {{ content|urlify_markdown|markdown}} </div> ```
203,890
<p>How do I generate an audio sine or square wave of a given frequency?</p> <p>I am hoping to do this to calibrate equipment, so how precise would these waves be?</p>
[ { "answer_id": 203917, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 6, "selected": true, "text": "<p>You can use <a href=\"http://codeplex.com/naudio\" rel=\"noreferrer\">NAudio</a> and create a derived WaveStream that outputs sine or square waves which you could output to the soundcard or write to a <a href=\"http://en.wikipedia.org/wiki/WAV\" rel=\"noreferrer\">WAV</a> file. If you used 32-bit floating point samples you could write the values directly out of the sin function without having to scale as it already goes between -1 and 1.</p>\n\n<p>As for accuracy, do you mean exactly the right frequency, or exactly the right wave shape? There is no such thing as a true square wave, and even the sine wave will likely have a few very quiet artifacts at other frequencies. If it's accuracy of frequency that matters, you are reliant on the stability and accuracy of the clock in your sound card. Having said that, I would imagine that the accuracy would be good enough for most uses. </p>\n\n<p>Here's some example code that makes a 1&nbsp;kHz sample at a 8&nbsp;kHz sample rate and with 16 bit samples (that is, not floating point):</p>\n\n<pre><code>int sampleRate = 8000;\nshort[] buffer = new short[8000];\ndouble amplitude = 0.25 * short.MaxValue;\ndouble frequency = 1000;\nfor (int n = 0; n &lt; buffer.Length; n++)\n{\n buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate));\n}\n</code></pre>\n" }, { "answer_id": 19772815, "author": "Edward", "author_id": 2953342, "author_profile": "https://Stackoverflow.com/users/2953342", "pm_score": 5, "selected": false, "text": "<p>This lets you give frequency, duration, and amplitude, and it is 100% .NET CLR code. No external DLL's. It works by creating a WAV-formatted <code>MemoryStream</code> which is like creating a file in memory only, without storing it to disk. Then it plays that <code>MemoryStream</code> with <code>System.Media.SoundPlayer</code>.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Windows.Forms;\n\npublic static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)\n{\n var mStrm = new MemoryStream();\n BinaryWriter writer = new BinaryWriter(mStrm);\n\n const double TAU = 2 * Math.PI;\n int formatChunkSize = 16;\n int headerSize = 8;\n short formatType = 1;\n short tracks = 1;\n int samplesPerSecond = 44100;\n short bitsPerSample = 16;\n short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));\n int bytesPerSecond = samplesPerSecond * frameSize;\n int waveSize = 4;\n int samples = (int)((decimal)samplesPerSecond * msDuration / 1000);\n int dataChunkSize = samples * frameSize;\n int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;\n // var encoding = new System.Text.UTF8Encoding();\n writer.Write(0x46464952); // = encoding.GetBytes(\"RIFF\")\n writer.Write(fileSize);\n writer.Write(0x45564157); // = encoding.GetBytes(\"WAVE\")\n writer.Write(0x20746D66); // = encoding.GetBytes(\"fmt \")\n writer.Write(formatChunkSize);\n writer.Write(formatType);\n writer.Write(tracks);\n writer.Write(samplesPerSecond);\n writer.Write(bytesPerSecond);\n writer.Write(frameSize);\n writer.Write(bitsPerSample);\n writer.Write(0x61746164); // = encoding.GetBytes(\"data\")\n writer.Write(dataChunkSize);\n {\n double theta = frequency * TAU / (double)samplesPerSecond;\n // 'volume' is UInt16 with range 0 thru Uint16.MaxValue ( = 65 535)\n // we need 'amp' to have the range of 0 thru Int16.MaxValue ( = 32 767)\n double amp = volume &gt;&gt; 2; // so we simply set amp = volume / 2\n for (int step = 0; step &lt; samples; step++)\n {\n short s = (short)(amp * Math.Sin(theta * (double)step));\n writer.Write(s);\n }\n }\n\n mStrm.Seek(0, SeekOrigin.Begin);\n new System.Media.SoundPlayer(mStrm).Play();\n writer.Close();\n mStrm.Close();\n} // public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)\n</code></pre>\n" }, { "answer_id": 21500396, "author": "Aleks", "author_id": 3258422, "author_profile": "https://Stackoverflow.com/users/3258422", "pm_score": 3, "selected": false, "text": "<p>Try from <a href=\"http://alvas.net/alvas.audio,tips.aspx#tip86\" rel=\"noreferrer\">Creating sine and save to wave file in C#</a> </p>\n\n<pre><code>private void TestSine()\n{\n IntPtr format;\n byte[] data;\n GetSineWave(1000, 100, 44100, -1, out format, out data);\n WaveWriter ww = new WaveWriter(File.Create(@\"d:\\work\\sine.wav\"),\n AudioCompressionManager.FormatBytes(format));\n ww.WriteData(data);\n ww.Close();\n}\n\nprivate void GetSineWave(double freq, int durationMs, int sampleRate, short decibel, out IntPtr format, out byte[] data)\n{\n short max = dB2Short(decibel);//short.MaxValue\n double fs = sampleRate; // sample freq\n int len = sampleRate * durationMs / 1000;\n short[] data16Bit = new short[len];\n for (int i = 0; i &lt; len; i++)\n {\n double t = (double)i / fs; // current time\n data16Bit[i] = (short)(Math.Sin(2 * Math.PI * t * freq) * max);\n }\n IntPtr format1 = AudioCompressionManager.GetPcmFormat(1, 16, (int)fs);\n byte[] data1 = new byte[data16Bit.Length * 2];\n Buffer.BlockCopy(data16Bit, 0, data1, 0, data1.Length);\n format = format1;\n data = data1;\n}\n\nprivate static short dB2Short(double dB)\n{\n double times = Math.Pow(10, dB / 10);\n return (short)(short.MaxValue * times);\n}\n</code></pre>\n" }, { "answer_id": 50389401, "author": "Declan Taylor", "author_id": 8201378, "author_profile": "https://Stackoverflow.com/users/8201378", "pm_score": 1, "selected": false, "text": "<p>Using <em>Math.NET Numerics</em> </p>\n\n<p><a href=\"https://numerics.mathdotnet.com/Generate.html\" rel=\"nofollow noreferrer\">https://numerics.mathdotnet.com/Generate.html</a></p>\n\n<blockquote>\n <p><strong>Sinusoidal</strong></p>\n \n <p>Generates a Sine wave array of the given length. This is equivalent to\n applying a scaled trigonometric Sine function to a periodic sawtooth\n of amplitude 2π.</p>\n \n <p>s(x)=A⋅sin(2πνx+θ)</p>\n \n <p>Generate.Sinusoidal(length,samplingRate,frequency,amplitude,mean,phase,delay)</p>\n</blockquote>\n\n<p>e.g</p>\n\n<pre><code> Generate.Sinusoidal(15, 1000.0, 100.0, 10.0);\n</code></pre>\n\n<p>returns array { 0, 5.9, 9.5, 9.5, 5.9, 0, -5.9, ... }</p>\n\n<p>and there's also </p>\n\n<pre><code>Generate.Square(...\n</code></pre>\n\n<p>which will </p>\n\n<blockquote>\n <p>create a periodic square wave...</p>\n</blockquote>\n\n<p>can't speak about precision.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
How do I generate an audio sine or square wave of a given frequency? I am hoping to do this to calibrate equipment, so how precise would these waves be?
You can use [NAudio](http://codeplex.com/naudio) and create a derived WaveStream that outputs sine or square waves which you could output to the soundcard or write to a [WAV](http://en.wikipedia.org/wiki/WAV) file. If you used 32-bit floating point samples you could write the values directly out of the sin function without having to scale as it already goes between -1 and 1. As for accuracy, do you mean exactly the right frequency, or exactly the right wave shape? There is no such thing as a true square wave, and even the sine wave will likely have a few very quiet artifacts at other frequencies. If it's accuracy of frequency that matters, you are reliant on the stability and accuracy of the clock in your sound card. Having said that, I would imagine that the accuracy would be good enough for most uses. Here's some example code that makes a 1 kHz sample at a 8 kHz sample rate and with 16 bit samples (that is, not floating point): ``` int sampleRate = 8000; short[] buffer = new short[8000]; double amplitude = 0.25 * short.MaxValue; double frequency = 1000; for (int n = 0; n < buffer.Length; n++) { buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate)); } ```
203,911
<p>I am using Java API and XPath to parse my XML. I have XML like this:</p> <pre><code>&lt;animals&gt; &lt;dog&gt; &lt;looks&gt;dangerous &lt;/looks&gt; &lt;bites&gt; hard &lt;/bites&gt; &lt;growls&gt; yes &lt;/growls&gt; &lt;/dog&gt; &lt;cat&gt;nothing special&lt;/cat&gt; &lt;/animals&gt; </code></pre> <p>I would like an XPath condition to print </p> <pre><code>&lt;dog&gt; &lt;looks&gt;dangerous &lt;/looks&gt; &lt;bites&gt; hard &lt;/bites&gt; &lt;growls&gt; yes &lt;/growls&gt; &lt;/dog&gt; </code></pre> <p>But I am not able to now. If I use <code>/animal/dog/text()</code> it gives <code>dangerous</code>. But I guess it is used print text alone. Is there a way using XPath condition to fetch a block of XML?</p> <p><strong>EDIT</strong>:</p> <p>Thanks a lot for your responses. Appreciate your time spent on this. Is there way to do it in Java without printing the inner text? </p> <p>Here is where my XPath condition goes:</p> <pre><code>public static final String XPATH_INPUT_DATA="//text()"; </code></pre>
[ { "answer_id": 203938, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 2, "selected": false, "text": "<p>If you use /animals/dog you will get back the 'dog' node with all the child nodes. Printing the inner xml of that node should give you what you need.</p>\n" }, { "answer_id": 204526, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 1, "selected": false, "text": "<p>Demonstration of rslite's method, with the command-line tool <a href=\"http://www.xml.com/pub/a/2002/04/17/perl-xml.html\" rel=\"nofollow noreferrer\">xpath</a> (written in Perl but it is standard Xpath, it should work everywhere):</p>\n\n<pre><code>% xpath -e /animals/dog animals.xml \nFound 1 nodes in animals.xml:\n-- NODE --\n&lt;dog&gt;\n &lt;looks&gt;dangerous &lt;/looks&gt; \n &lt;bites&gt; hard &lt;/bites&gt;\n &lt;growls&gt; yes &lt;/growls&gt;\n&lt;/dog&gt;\n</code></pre>\n" }, { "answer_id": 221823, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 1, "selected": false, "text": "<p>All XPath does is selects a node. The //text() test just selects all text nodes from within the document. The elements exist in the document only as element nodes, and not as blocks of text as you seem to be implying. If you want to convert these elements to text then you need to make this conversion at the Java level (by printing the inner text).</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25458/" ]
I am using Java API and XPath to parse my XML. I have XML like this: ``` <animals> <dog> <looks>dangerous </looks> <bites> hard </bites> <growls> yes </growls> </dog> <cat>nothing special</cat> </animals> ``` I would like an XPath condition to print ``` <dog> <looks>dangerous </looks> <bites> hard </bites> <growls> yes </growls> </dog> ``` But I am not able to now. If I use `/animal/dog/text()` it gives `dangerous`. But I guess it is used print text alone. Is there a way using XPath condition to fetch a block of XML? **EDIT**: Thanks a lot for your responses. Appreciate your time spent on this. Is there way to do it in Java without printing the inner text? Here is where my XPath condition goes: ``` public static final String XPATH_INPUT_DATA="//text()"; ```
If you use /animals/dog you will get back the 'dog' node with all the child nodes. Printing the inner xml of that node should give you what you need.
203,918
<p>Been creating a simple program using VBA that I can use to review vocabulary in Chinese.</p> <p>I've gotten a fair bit working so far, but have run into a huge problem with inputting a macron-character such as "ā" (unicode 257). The specific application I am working on right now involves changing the contents of the text-box form so that an "a" can automatically be replaced as I type into the text box. Such a procedure itself is easy--I can get it to work with the pinyin characters "á" and "à".</p> <pre><code>Select Case testchar Case "a" Mid(strclip, markloc, 1) = "ā" End Select </code></pre> <p>The previous is an attempt at using the Mid function to replace one character in the textbox string with a pinyin character at the appropriate cue from the user.</p> <p>The hangup is I can't enter the "ā" into VBA! I've been looking around the internet but this doesn't seem like a problem to anyone else. When I am in the VBA editor and I type alt + 0257, nothing happens. I can't copy-paste from notepad either.. I'm about ready to scrap VBA and redo this application in some other language..</p> <p>Cheers</p>
[ { "answer_id": 203942, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 0, "selected": false, "text": "<p>I don't have ms-office installed on my machine to try it.<br>\nHowever, you can use StrConv function with parameter for Unicode (alongwith LCID) to put the unicode content into the textbox.</p>\n\n<p>Note that VB6 style controls dont accept unicode values. <br>\nIf you are creating forms inside VBA editor, it should work (because it uses Forms 2.0 Library).</p>\n" }, { "answer_id": 203946, "author": "Ozgur Ozcitak", "author_id": 976, "author_profile": "https://Stackoverflow.com/users/976", "pm_score": 2, "selected": false, "text": "<p>You can use ChrW to generate Unicode characters:</p>\n\n<pre><code>Mid(strclip, markloc, 1) = ChrW(257)\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Been creating a simple program using VBA that I can use to review vocabulary in Chinese. I've gotten a fair bit working so far, but have run into a huge problem with inputting a macron-character such as "ā" (unicode 257). The specific application I am working on right now involves changing the contents of the text-box form so that an "a" can automatically be replaced as I type into the text box. Such a procedure itself is easy--I can get it to work with the pinyin characters "á" and "à". ``` Select Case testchar Case "a" Mid(strclip, markloc, 1) = "ā" End Select ``` The previous is an attempt at using the Mid function to replace one character in the textbox string with a pinyin character at the appropriate cue from the user. The hangup is I can't enter the "ā" into VBA! I've been looking around the internet but this doesn't seem like a problem to anyone else. When I am in the VBA editor and I type alt + 0257, nothing happens. I can't copy-paste from notepad either.. I'm about ready to scrap VBA and redo this application in some other language.. Cheers
You can use ChrW to generate Unicode characters: ``` Mid(strclip, markloc, 1) = ChrW(257) ```
203,930
<p>Kinda long title, but anyways...</p> <p>I've been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams<br> <a href="http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html</a><br> <a href="http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html</a></p> <p>But I can't seem to figure it out in C#.</p> <pre><code>StreamWriter writer = new StreamWriter(tcpClient.GetStream()); writer.Write(data.Length + data); </code></pre> <p>This doesn't work very well at all. Could someone give me a nudge in the right direction?</p>
[ { "answer_id": 203934, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>Instead of <code>data.Length</code>, try:</p>\n\n<pre><code>writer.Write(chr(data.Length) + data);\n</code></pre>\n\n<p>This will prefix every data block with one byte indicating its length (up to 255 bytes long). As you requested, this is only a nudge. :)</p>\n\n<p>Update: I just remembered that C# is all Unicode and stuff, so chr() probably gives you more than one byte. Adjust to fit.</p>\n" }, { "answer_id": 203955, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 1, "selected": false, "text": "<p>I guess this should do that: \n(I assume your data is a string)</p>\n\n<pre>\nStream stream = tcpClient.GetStream();\nEncoding encoding = Encoding.GetEncoding(\"encoding name\");\n\nbyte[] bytes = encoding.getBytes(data);\n\nstream.Write(BitConverter.GetBytes((short)bytes.Length),0,2); // hope data isn't longer that 64k\nstream.Write(bytes,0,bytes.Length);\n</pre>\n" }, { "answer_id": 203962, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>Generally you would send the length first. Both ends should agree on what a length looks like - for example, you might be happy to use fixed 4-byte length prefix as binary:</p>\n\n<pre><code> byte[] data = ...\n int len = data.Length;\n byte[] prefix = Bitconverter.GetBytes(len);\n stream.Write(prefix, 0, prefix.Length); // fixed 4 bytes\n stream.Write(data, 0, data.Length);\n</code></pre>\n\n<p>Obviously the caller needs to do the same - i.e. read the first 4 bytes to get the length. For reading, the receiver should take care not to read too much data. One way is with a limiting stream - for example, <a href=\"http://code.google.com/p/protobuf-net/source/browse/trunk/protobuf-net/SubStream.cs\" rel=\"nofollow noreferrer\">this class</a> can be used to get a Stream that won't read too much.</p>\n\n<p>If you don't want the overhead of always sending 4 bytes, then some more interesting encodings are possible - for example, using the msb as a continuation block.</p>\n\n<p>For info, <a href=\"http://code.google.com/p/protobuf-net/\" rel=\"nofollow noreferrer\">protobuf-net</a> is a binary serializer designed around Google's \"protocol buffers\" message-based format. It handles a lot of the details for you, and might be of interest if you don't want to spend lots of time writing serialization code. There are examples for sockets in the QuickStart project, <a href=\"http://code.google.com/p/protobuf-net/source/browse/trunk/QuickStart/3%20Sockets.cs\" rel=\"nofollow noreferrer\">for example here</a></p>\n" }, { "answer_id": 204020, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 0, "selected": false, "text": "<p>When you say, \"This doesn't work very well at all\", I'd be curious about specifically what doesn't work. Are they .NET applications on both ends of the socket? If so, ignore this answer. If not, then could the problem be the byte ordering of the integer? A little endian vs big endian issue? This thread here discusses it:</p>\n\n<p><a href=\"http://bytes.com/forum/thread225649.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread225649.html</a></p>\n\n<p><a href=\"http://books.google.com/books?id=2zT5b2BS1OUC&amp;pg=PA64&amp;lpg=PA64&amp;dq=c%23+sockets+integers+byte+ordering&amp;source=web&amp;ots=_ISzZZ6HHT&amp;sig=tUHdNT0NGv0uxusmHG9YjFw6j9k&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=2&amp;ct=result\" rel=\"nofollow noreferrer\">http://books.google.com/books?id=2zT5b2BS1OUC&amp;pg=PA64&amp;lpg=PA64&amp;dq=c%23+sockets+integers+byte+ordering&amp;source=web&amp;ots=_ISzZZ6HHT&amp;sig=tUHdNT0NGv0uxusmHG9YjFw6j9k&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=2&amp;ct=result</a></p>\n\n<p>Another problem if both ends aren't .NET could be that the other end expects ANSI strings whereas you are sending Unicode.</p>\n" }, { "answer_id": 204096, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 0, "selected": false, "text": "<p>You could also, if you wanted to preserve the plaintextness of it, specify a specific maximum size and pad the number via string.Format. (Say for instance only allowing 4 characters in the length) This avoids the problems of numbers in the useful datastream, and simplifies decoding as well.</p>\n\n<p>A final plaintext solution is to put a specific character between length and data, such as -, then grab single characters at a time till you hit a minus, decode the retrieved string (Ignoring the minus of course) and then use that to determine the length of the remaining string, and your output code which simply need to be changed to add that character in between.</p>\n" }, { "answer_id": 604455, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use WriteLine instead of Write, ReadLine instead of Read...</p>\n\n<p>If you are talking sending pure textual messages, append the Newline character at the end of your messages. Then, read bytes till you encounter this Newline character and convert the bytes into a string.\nFor your convenience, any System.IO.StreamReader and System.IO.StreamReader implement this behavior in a single method (WriterLine or ReadLine)\n writer.WriteLine(\"Line to send\");\n string lineSent = reader.ReadLine();</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15067/" ]
Kinda long title, but anyways... I've been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams <http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html> <http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html> But I can't seem to figure it out in C#. ``` StreamWriter writer = new StreamWriter(tcpClient.GetStream()); writer.Write(data.Length + data); ``` This doesn't work very well at all. Could someone give me a nudge in the right direction?
Generally you would send the length first. Both ends should agree on what a length looks like - for example, you might be happy to use fixed 4-byte length prefix as binary: ``` byte[] data = ... int len = data.Length; byte[] prefix = Bitconverter.GetBytes(len); stream.Write(prefix, 0, prefix.Length); // fixed 4 bytes stream.Write(data, 0, data.Length); ``` Obviously the caller needs to do the same - i.e. read the first 4 bytes to get the length. For reading, the receiver should take care not to read too much data. One way is with a limiting stream - for example, [this class](http://code.google.com/p/protobuf-net/source/browse/trunk/protobuf-net/SubStream.cs) can be used to get a Stream that won't read too much. If you don't want the overhead of always sending 4 bytes, then some more interesting encodings are possible - for example, using the msb as a continuation block. For info, [protobuf-net](http://code.google.com/p/protobuf-net/) is a binary serializer designed around Google's "protocol buffers" message-based format. It handles a lot of the details for you, and might be of interest if you don't want to spend lots of time writing serialization code. There are examples for sockets in the QuickStart project, [for example here](http://code.google.com/p/protobuf-net/source/browse/trunk/QuickStart/3%20Sockets.cs)
203,969
<p>How do you get an instance of the actionscript class <code>Class</code> from an instance of that class?</p> <p>In Python, this would be <code>x.__class__</code>; in Java, <code>x.getClass();</code>.</p> <p>I'm aware that <a href="http://actionscript.org/forums/showthread.php3?t=120135#td_post_545693" rel="noreferrer">certain terrible hacks</a> exist to do this, but I'm looking for a built-in language facility, or at least a library routine built on something reliable.</p>
[ { "answer_id": 204003, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 4, "selected": false, "text": "<p>Any reason you couldn't do this?</p>\n\n<pre><code>var s:Sprite = new flash.display.Sprite();\n\nvar className:String = flash.utils.getQualifiedClassName( s );\nvar myClass:Class = flash.utils.getDefinitionByName( className ) as Class;\n\ntrace(className ); // flash.display::Sprite\ntrace(myClass); // [class Sprite]\n\nvar s2 = new myClass();\ntrace(s2); // [object Sprite]\n</code></pre>\n\n<p>I don't know a way to avoid round-tripping through a String, but it should work well enough.</p>\n" }, { "answer_id": 204006, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 7, "selected": true, "text": "<p>You can get it through the 'constructor' property of the base Object class. i.e.:</p>\n\n<pre><code>var myClass:Class = Object(myObj).constructor;\n</code></pre>\n" }, { "answer_id": 9152781, "author": "iND", "author_id": 516537, "author_profile": "https://Stackoverflow.com/users/516537", "pm_score": 4, "selected": false, "text": "<p>The accepted (and currently most popular answer) has some flaws. The answer serves for this specific use case, but the comments have expanded the answer to a seeming general solution. </p>\n\n<p>But it is not a type-safe solution in certain cases, and it doesn't address all possible objects. The idea that XML is not supported has been addressed well enough here and elsewhere, but the type-safe idea has not.</p>\n\n<p>The assumption made is that it is an class object created by the programmer. Here are some tests that I set up (this is in strict mode, but a local test). Note the <code>int</code> test results:</p>\n\n<pre><code>var sprite:Sprite = new Sprite();\nvar xml:XML = new XML();\nvar testInt:int = 2;\nvar testClass:TestClass = new TestClass();\nvar testAnon:Object = {};\n\ntrace(\"classname 1 = \" + getQualifiedClassName(sprite));\ntrace(\"myclass 1 = \" + getDefinitionByName(getQualifiedClassName(sprite)));\ntrace(\"constructor a 1 = \" + Object(sprite).constructor);\ntrace(\"constructor a 1 = \" + (Object(sprite).constructor as Class));\ntrace(\"constructor b 1 = \" + sprite[\"constructor\"]);\ntrace(\"constructor b 1 = \" + (sprite[\"constructor\"] as Class));\ntrace(\"...\");\ntrace(\"classname 2 = \" + getQualifiedClassName(xml));\ntrace(\"myclass 2 = \" + getDefinitionByName(getQualifiedClassName(xml)));\ntrace(\"constructor a 2 = \" + Object(xml).constructor);\ntrace(\"constructor a 2 = \" + (Object(xml).constructor as Class));\ntrace(\"constructor b 2 = \" + xml[\"constructor\"]);\ntrace(\"constructor b 2 = \" + (xml[\"constructor\"] as Class));\ntrace(\"...\");\ntrace(\"classname 3 = \" + getQualifiedClassName(testInt));\ntrace(\"myclass 3 = \" + getDefinitionByName(getQualifiedClassName(testInt)));\ntrace(\"constructor a 3 = \" + Object(testInt).constructor);\ntrace(\"constructor a 3 = \" + (Object(testInt).constructor as Class));\ntrace(\"constructor b 3 = \" + testInt[\"constructor\"]);\ntrace(\"constructor b 3 = \" + (testInt[\"constructor\"] as Class));\ntrace(\"...\");\ntrace(\"classname 4 = \" + getQualifiedClassName(testClass));\ntrace(\"myclass 4 = \" + getDefinitionByName(getQualifiedClassName(testClass)));\ntrace(\"constructor a 4 = \" + Object(testClass).constructor);\ntrace(\"constructor a 4 = \" + (Object(testClass).constructor as Class));\ntrace(\"constructor b 4 = \" + testClass[\"constructor\"]);\ntrace(\"constructor b 4 = \" + (testClass[\"constructor\"] as Class));\ntrace(\"...\");\ntrace(\"classname 5 = \" + getQualifiedClassName(testAnon));\ntrace(\"myclass 5 = \" + getDefinitionByName(getQualifiedClassName(testAnon)));\ntrace(\"constructor a 5 = \" + Object(testAnon).constructor);\ntrace(\"constructor a 5 = \" + (Object(testAnon).constructor as Class));\ntrace(\"constructor b 5 = \" + testAnon[\"constructor\"]);\ntrace(\"constructor b 5 = \" + (testAnon[\"constructor\"] as Class));\ntrace(\"...\");\n</code></pre>\n\n<p>With <code>TestClass</code> defined as:</p>\n\n<pre><code>package\n{\n public class TestClass\n {\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>classname 1 = flash.display::Sprite\nmyclass 1 = [class Sprite]\nconstructor a 1 = [class Sprite]\nconstructor a 1 = [class Sprite]\nconstructor b 1 = [class Sprite]\nconstructor b 1 = [class Sprite]\n...\nclassname 2 = XML\nmyclass 2 = [class XML]\nconstructor a 2 = \nconstructor a 2 = null\nconstructor b 2 = \nconstructor b 2 = null\n...\nclassname 3 = int\nmyclass 3 = [class int]\nconstructor a 3 = [class Number]\nconstructor a 3 = [class Number]\nconstructor b 3 = [class Number]\nconstructor b 3 = [class Number]\n...\nclassname 4 = src::TestClass\nmyclass 4 = [class TestClass]\nconstructor a 4 = [class TestClass]\nconstructor a 4 = [class TestClass]\nconstructor b 4 = [class TestClass]\nconstructor b 4 = [class TestClass]\n...\nclassname 5 = Object\nmyclass 5 = [class Object]\nconstructor a 5 = [class Object]\nconstructor a 5 = [class Object]\nconstructor b 5 = [class Object]\nconstructor b 5 = [class Object]\n...\n</code></pre>\n\n<p>Beyond any current testing, there is fairly good reason to use <code>getDefinitionByName</code> over the <code>constructor</code> methods. The <code>getDefinitionByName</code> method allows :</p>\n\n<ul>\n<li>Adobe to develop internal solutions for the (current and future) problematic areas</li>\n<li>you would not have to change your code for future Adobe developments</li>\n<li>you do not have to develop two (or more) separate methods of dynamic instantiation.</li>\n</ul>\n\n<p>It may be slower now, but in the future there may be improvements from Adobe's side that would address the speed issue.</p>\n\n<p>(For example, it used to be that <code>uint</code> was far slower in for-loops than <code>int</code>, so a lot of conversion code was set up to use the faster <code>int</code>. It was a fairly simple issue to solve, so Adobe fixed it, and now there is a lot of code that jumps through some unnecessary hoops to achieve an outdated goal.)</p>\n\n<p>Since the <code>getDefinitionByName</code> method works correctly in all cases, code should be developed using that method, and then work to get Adobe to fix the speed issue. </p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13564/" ]
How do you get an instance of the actionscript class `Class` from an instance of that class? In Python, this would be `x.__class__`; in Java, `x.getClass();`. I'm aware that [certain terrible hacks](http://actionscript.org/forums/showthread.php3?t=120135#td_post_545693) exist to do this, but I'm looking for a built-in language facility, or at least a library routine built on something reliable.
You can get it through the 'constructor' property of the base Object class. i.e.: ``` var myClass:Class = Object(myObj).constructor; ```
203,984
<p>I have an <code>ArrayList&lt;String&gt;</code>, and I want to remove repeated strings from it. How can I do this?</p>
[ { "answer_id": 203992, "author": "jonathan-stafford", "author_id": 27587, "author_profile": "https://Stackoverflow.com/users/27587", "pm_score": 11, "selected": true, "text": "<p>If you don't want duplicates in a <code>Collection</code>, you should consider why you're using a <code>Collection</code> that allows duplicates. The easiest way to remove repeated elements is to add the contents to a <code>Set</code> (which will not allow duplicates) and then add the <code>Set</code> back to the <code>ArrayList</code>:</p>\n\n<pre><code>Set&lt;String&gt; set = new HashSet&lt;&gt;(yourList);\nyourList.clear();\nyourList.addAll(set);\n</code></pre>\n\n<p>Of course, this destroys the ordering of the elements in the <code>ArrayList</code>.</p>\n" }, { "answer_id": 203997, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 6, "selected": false, "text": "<p>If you don't want duplicates, use a <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Set.html\" rel=\"noreferrer\">Set</a> instead of a <code>List</code>. To convert a <code>List</code> to a <code>Set</code> you can use the following code:</p>\n\n<pre><code>// list is some List of Strings\nSet&lt;String&gt; s = new HashSet&lt;String&gt;(list);\n</code></pre>\n\n<p>If really necessary you can use the same construction to convert a <code>Set</code> back into a <code>List</code>.</p>\n" }, { "answer_id": 204004, "author": "abahgat", "author_id": 27565, "author_profile": "https://Stackoverflow.com/users/27565", "pm_score": 8, "selected": false, "text": "<p>Although converting the <code>ArrayList</code> to a <code>HashSet</code> effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you to use this variant</p>\n\n<pre><code>// list is some List of Strings\nSet&lt;String&gt; s = new LinkedHashSet&lt;&gt;(list);\n</code></pre>\n\n<p>Then, if you need to get back a <code>List</code> reference, you can use again the conversion constructor.</p>\n" }, { "answer_id": 204766, "author": "Vinze", "author_id": 26859, "author_profile": "https://Stackoverflow.com/users/26859", "pm_score": 1, "selected": false, "text": "<p>As said before, you should use a class implementing the Set interface instead of List to be sure of the unicity of elements. If you have to keep the order of elements, the SortedSet interface can then be used; the TreeSet class implements that interface.</p>\n" }, { "answer_id": 215212, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 4, "selected": false, "text": "<p>Probably a bit overkill, but I enjoy this kind of isolated problem. :)</p>\n\n<p>This code uses a temporary Set (for the uniqueness check) but removes elements directly inside the original list. Since element removal inside an ArrayList can induce a huge amount of array copying, the remove(int)-method is avoided.</p>\n\n<pre><code>public static &lt;T&gt; void removeDuplicates(ArrayList&lt;T&gt; list) {\n int size = list.size();\n int out = 0;\n {\n final Set&lt;T&gt; encountered = new HashSet&lt;T&gt;();\n for (int in = 0; in &lt; size; in++) {\n final T t = list.get(in);\n final boolean first = encountered.add(t);\n if (first) {\n list.set(out++, t);\n }\n }\n }\n while (out &lt; size) {\n list.remove(--size);\n }\n}\n</code></pre>\n\n<p>While we're at it, here's a version for LinkedList (a lot nicer!):</p>\n\n<pre><code>public static &lt;T&gt; void removeDuplicates(LinkedList&lt;T&gt; list) {\n final Set&lt;T&gt; encountered = new HashSet&lt;T&gt;();\n for (Iterator&lt;T&gt; iter = list.iterator(); iter.hasNext(); ) {\n final T t = iter.next();\n final boolean first = encountered.add(t);\n if (!first) {\n iter.remove();\n }\n }\n}\n</code></pre>\n\n<p>Use the marker interface to present a unified solution for List:</p>\n\n<pre><code>public static &lt;T&gt; void removeDuplicates(List&lt;T&gt; list) {\n if (list instanceof RandomAccess) {\n // use first version here\n } else {\n // use other version here\n }\n}\n</code></pre>\n\n<p>EDIT: I guess the generics-stuff doesn't really add any value here.. Oh well. :)</p>\n" }, { "answer_id": 4547382, "author": "stbn", "author_id": 554467, "author_profile": "https://Stackoverflow.com/users/554467", "pm_score": 5, "selected": false, "text": "<p>Here's a way that doesn't affect your list ordering:</p>\n\n<pre><code>ArrayList l1 = new ArrayList();\nArrayList l2 = new ArrayList();\n\nIterator iterator = l1.iterator();\n\nwhile (iterator.hasNext()) {\n YourClass o = (YourClass) iterator.next();\n if(!l2.contains(o)) l2.add(o);\n}\n</code></pre>\n\n<p>l1 is the original list, and l2 is the list without repeated items\n(Make sure YourClass has the equals method according to what you want to stand for equality)</p>\n" }, { "answer_id": 5618571, "author": "HarpyWar", "author_id": 701779, "author_profile": "https://Stackoverflow.com/users/701779", "pm_score": 2, "selected": false, "text": "<p>When you are filling the ArrayList, use a condition for each element. For example:</p>\n\n<pre><code> ArrayList&lt; Integer &gt; al = new ArrayList&lt; Integer &gt;(); \n\n // fill 1 \n for ( int i = 0; i &lt;= 5; i++ ) \n if ( !al.contains( i ) ) \n al.add( i ); \n\n // fill 2 \n for (int i = 0; i &lt;= 10; i++ ) \n if ( !al.contains( i ) ) \n al.add( i ); \n\n for( Integer i: al )\n {\n System.out.print( i + \" \"); \n }\n</code></pre>\n\n<p>We will get an array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}</p>\n" }, { "answer_id": 8452741, "author": "Timofey Gorshkov", "author_id": 274205, "author_profile": "https://Stackoverflow.com/users/274205", "pm_score": 4, "selected": false, "text": "<p>There is also <a href=\"https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/ImmutableSet.html\" rel=\"noreferrer\"><code>ImmutableSet</code></a> from <a href=\"https://github.com/google/guava\" rel=\"noreferrer\">Guava</a> as an option (<a href=\"https://github.com/google/guava/wiki/ImmutableCollectionsExplained\" rel=\"noreferrer\">here</a> is the documentation):</p>\n\n<pre><code>ImmutableSet.copyOf(list);\n</code></pre>\n" }, { "answer_id": 8962127, "author": "Ghyour", "author_id": 1163576, "author_profile": "https://Stackoverflow.com/users/1163576", "pm_score": 2, "selected": false, "text": "<pre><code>for(int a=0;a&lt;myArray.size();a++){\n for(int b=a+1;b&lt;myArray.size();b++){\n if(myArray.get(a).equalsIgnoreCase(myArray.get(b))){\n myArray.remove(b); \n dups++;\n b--;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 12665409, "author": "reddy", "author_id": 1710433, "author_profile": "https://Stackoverflow.com/users/1710433", "pm_score": 0, "selected": false, "text": "<pre><code>import java.util.*;\nclass RemoveDupFrmString\n{\n public static void main(String[] args)\n {\n\n String s=\"appsc\";\n\n Set&lt;Character&gt; unique = new LinkedHashSet&lt;Character&gt; ();\n\n for(char c : s.toCharArray()) {\n\n System.out.println(unique.add(c));\n }\n for(char dis:unique){\n System.out.println(dis);\n }\n\n\n }\n}\n</code></pre>\n" }, { "answer_id": 14126093, "author": "user1912383", "author_id": 1912383, "author_profile": "https://Stackoverflow.com/users/1912383", "pm_score": 1, "selected": false, "text": "<p>LinkedHashSet will do the trick.</p>\n\n<pre><code>String[] arr2 = {\"5\",\"1\",\"2\",\"3\",\"3\",\"4\",\"1\",\"2\"};\nSet&lt;String&gt; set = new LinkedHashSet&lt;String&gt;(Arrays.asList(arr2));\nfor(String s1 : set)\n System.out.println(s1);\n\nSystem.out.println( \"------------------------\" );\nString[] arr3 = set.toArray(new String[0]);\nfor(int i = 0; i &lt; arr3.length; i++)\n System.out.println(arr3[i].toString());\n</code></pre>\n\n<p>//output: 5,1,2,3,4</p>\n" }, { "answer_id": 18504616, "author": "Harsha", "author_id": 2706817, "author_profile": "https://Stackoverflow.com/users/2706817", "pm_score": 0, "selected": false, "text": "<pre><code>public Set&lt;Object&gt; findDuplicates(List&lt;Object&gt; list) {\n Set&lt;Object&gt; items = new HashSet&lt;Object&gt;();\n Set&lt;Object&gt; duplicates = new HashSet&lt;Object&gt;();\n for (Object item : list) {\n if (items.contains(item)) {\n duplicates.add(item);\n } else { \n items.add(item);\n } \n } \n return duplicates;\n }\n</code></pre>\n" }, { "answer_id": 19305534, "author": "user2868724", "author_id": 2868724, "author_profile": "https://Stackoverflow.com/users/2868724", "pm_score": 5, "selected": false, "text": "<p>this can solve the problem:</p>\n\n<pre><code>private List&lt;SomeClass&gt; clearListFromDuplicateFirstName(List&lt;SomeClass&gt; list1) {\n\n Map&lt;String, SomeClass&gt; cleanMap = new LinkedHashMap&lt;String, SomeClass&gt;();\n for (int i = 0; i &lt; list1.size(); i++) {\n cleanMap.put(list1.get(i).getFirstName(), list1.get(i));\n }\n List&lt;SomeClass&gt; list = new ArrayList&lt;SomeClass&gt;(cleanMap.values());\n return list;\n}\n</code></pre>\n" }, { "answer_id": 19334383, "author": "ram", "author_id": 2071911, "author_profile": "https://Stackoverflow.com/users/2071911", "pm_score": 2, "selected": false, "text": "<p>If you want to preserve your Order then it is best to use <strong>LinkedHashSet</strong>.\nBecause if you want to pass this List to an Insert Query by Iterating it, the order would be preserved.</p>\n\n<p>Try this</p>\n\n<pre><code>LinkedHashSet link=new LinkedHashSet();\nList listOfValues=new ArrayList();\nlistOfValues.add(link);\n</code></pre>\n\n<p>This conversion will be very helpful when you want to return a List but not a Set.</p>\n" }, { "answer_id": 19434592, "author": "CarlJohn", "author_id": 369035, "author_profile": "https://Stackoverflow.com/users/369035", "pm_score": 4, "selected": false, "text": "<p>It is possible to remove duplicates from arraylist without using <strong>HashSet</strong> or <strong>one more arraylist</strong>. </p>\n\n<p>Try this code..</p>\n\n<pre><code> ArrayList&lt;String&gt; lst = new ArrayList&lt;String&gt;();\n lst.add(\"ABC\");\n lst.add(\"ABC\");\n lst.add(\"ABCD\");\n lst.add(\"ABCD\");\n lst.add(\"ABCE\");\n\n System.out.println(\"Duplicates List \"+lst);\n\n Object[] st = lst.toArray();\n for (Object s : st) {\n if (lst.indexOf(s) != lst.lastIndexOf(s)) {\n lst.remove(lst.lastIndexOf(s));\n }\n }\n\n System.out.println(\"Distinct List \"+lst);\n</code></pre>\n\n<p>Output is</p>\n\n<pre><code>Duplicates List [ABC, ABC, ABCD, ABCD, ABCE]\nDistinct List [ABC, ABCD, ABCE]\n</code></pre>\n" }, { "answer_id": 23177411, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 7, "selected": false, "text": "<p>In Java 8:</p>\n\n<pre><code>List&lt;String&gt; deduped = list.stream().distinct().collect(Collectors.toList());\n</code></pre>\n\n<p>Please note that the <a href=\"https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java\">hashCode-equals</a> contract for list members should be respected for the filtering to work properly.</p>\n" }, { "answer_id": 24205781, "author": "SparkOn", "author_id": 3282808, "author_profile": "https://Stackoverflow.com/users/3282808", "pm_score": 0, "selected": false, "text": "<pre><code> ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();\n HashSet&lt;String&gt; unique = new LinkedHashSet&lt;String&gt;();\n HashSet&lt;String&gt; dup = new LinkedHashSet&lt;String&gt;();\n boolean b = false;\n list.add(\"Hello\");\n list.add(\"Hello\");\n list.add(\"how\");\n list.add(\"are\");\n list.add(\"u\");\n list.add(\"u\");\n\n for(Iterator iterator= list.iterator();iterator.hasNext();)\n {\n String value = (String)iterator.next();\n System.out.println(value);\n\n if(b==unique.add(value))\n dup.add(value);\n else\n unique.add(value);\n\n\n }\n System.out.println(unique);\n System.out.println(dup);\n</code></pre>\n" }, { "answer_id": 25780946, "author": "Thananjayan N", "author_id": 4029759, "author_profile": "https://Stackoverflow.com/users/4029759", "pm_score": 0, "selected": false, "text": "<p>If you want to remove duplicates from ArrayList means find the below logic,</p>\n\n<pre><code>public static Object[] removeDuplicate(Object[] inputArray)\n{\n long startTime = System.nanoTime();\n int totalSize = inputArray.length;\n Object[] resultArray = new Object[totalSize];\n int newSize = 0;\n for(int i=0; i&lt;totalSize; i++)\n {\n Object value = inputArray[i];\n if(value == null)\n {\n continue;\n }\n\n for(int j=i+1; j&lt;totalSize; j++)\n {\n if(value.equals(inputArray[j]))\n {\n inputArray[j] = null;\n }\n }\n resultArray[newSize++] = value;\n }\n\n long endTime = System.nanoTime()-startTime;\n System.out.println(\"Total Time-B:\"+endTime);\n return resultArray;\n}\n</code></pre>\n" }, { "answer_id": 27356461, "author": "M Kaweepatt Churcharoen", "author_id": 1516571, "author_profile": "https://Stackoverflow.com/users/1516571", "pm_score": 2, "selected": false, "text": "<p>This three lines of code can remove the duplicated element from ArrayList or any collection.</p>\n\n<pre><code>List&lt;Entity&gt; entities = repository.findByUserId(userId);\n\nSet&lt;Entity&gt; s = new LinkedHashSet&lt;Entity&gt;(entities);\nentities.clear();\nentities.addAll(s);\n</code></pre>\n" }, { "answer_id": 28987005, "author": "sambhu", "author_id": 4435902, "author_profile": "https://Stackoverflow.com/users/4435902", "pm_score": 2, "selected": false, "text": "<p><strong>Code:</strong></p>\n\n<pre><code>List&lt;String&gt; duplicatList = new ArrayList&lt;String&gt;();\nduplicatList = Arrays.asList(\"AA\",\"BB\",\"CC\",\"DD\",\"DD\",\"EE\",\"AA\",\"FF\");\n//above AA and DD are duplicate\nSet&lt;String&gt; uniqueList = new HashSet&lt;String&gt;(duplicatList);\nduplicatList = new ArrayList&lt;String&gt;(uniqueList); //let GC will doing free memory\nSystem.out.println(\"Removed Duplicate : \"+duplicatList);\n</code></pre>\n\n<p><strong>Note:</strong> Definitely, there will be memory overhead.</p>\n" }, { "answer_id": 31160570, "author": "sharkbait", "author_id": 1353274, "author_profile": "https://Stackoverflow.com/users/1353274", "pm_score": 0, "selected": false, "text": "<p>The @jonathan-stafford solution is OK. But this don't preserve the list order.</p>\n\n<p>If you want preserve the list order you have to use this:</p>\n\n<pre><code>public static &lt;T&gt; void removeDuplicate(List &lt;T&gt; list) {\nSet &lt;T&gt; set = new HashSet &lt;T&gt;();\nList &lt;T&gt; newList = new ArrayList &lt;T&gt;();\nfor (Iterator &lt;T&gt;iter = list.iterator(); iter.hasNext(); ) {\n Object element = iter.next();\n if (set.add((T) element))\n newList.add((T) element);\n }\n list.clear();\n list.addAll(newList);\n}\n</code></pre>\n\n<p>It's only to complete the answer. Very good!</p>\n" }, { "answer_id": 31770675, "author": "siva", "author_id": 5182491, "author_profile": "https://Stackoverflow.com/users/5182491", "pm_score": 1, "selected": false, "text": "<pre><code> List&lt;String&gt; result = new ArrayList&lt;String&gt;();\n Set&lt;String&gt; set = new LinkedHashSet&lt;String&gt;();\n String s = \"ravi is a good!boy. But ravi is very nasty fellow.\";\n StringTokenizer st = new StringTokenizer(s, \" ,. ,!\");\n while (st.hasMoreTokens()) {\n result.add(st.nextToken());\n }\n System.out.println(result);\n set.addAll(result);\n result.clear();\n result.addAll(set);\n System.out.println(result);\n\noutput:\n[ravi, is, a, good, boy, But, ravi, is, very, nasty, fellow]\n[ravi, is, a, good, boy, But, very, nasty, fellow]\n</code></pre>\n" }, { "answer_id": 31971798, "author": "infoj", "author_id": 4851359, "author_profile": "https://Stackoverflow.com/users/4851359", "pm_score": 5, "selected": false, "text": "<p>Java 8 streams provide a very simple way to remove duplicate elements from a list. Using the distinct method.\nIf we have a list of cities and we want to remove duplicates from that list it can be done in a single line - </p>\n\n<pre><code> List&lt;String&gt; cityList = new ArrayList&lt;&gt;();\n cityList.add(\"Delhi\");\n cityList.add(\"Mumbai\");\n cityList.add(\"Bangalore\");\n cityList.add(\"Chennai\");\n cityList.add(\"Kolkata\");\n cityList.add(\"Mumbai\");\n\n cityList = cityList.stream().distinct().collect(Collectors.toList());\n</code></pre>\n\n<p><a href=\"http://netjs.blogspot.com/2015/08/how-to-remove-duplicate-elements-from-arraylist-java.html\" rel=\"noreferrer\">How to remove duplicate elements from an arraylist</a></p>\n" }, { "answer_id": 32680600, "author": "Manash Ranjan Dakua", "author_id": 4879651, "author_profile": "https://Stackoverflow.com/users/4879651", "pm_score": 4, "selected": false, "text": "<pre><code>public static void main(String[] args){\n ArrayList&lt;Object&gt; al = new ArrayList&lt;Object&gt;();\n al.add(\"abc\");\n al.add('a');\n al.add('b');\n al.add('a');\n al.add(\"abc\");\n al.add(10.3);\n al.add('c');\n al.add(10);\n al.add(\"abc\");\n al.add(10);\n System.out.println(\"Before Duplicate Remove:\"+al);\n for(int i=0;i&lt;al.size();i++){\n for(int j=i+1;j&lt;al.size();j++){\n if(al.get(i).equals(al.get(j))){\n al.remove(j);\n j--;\n }\n }\n }\n System.out.println(\"After Removing duplicate:\"+al);\n}\n</code></pre>\n" }, { "answer_id": 32735976, "author": "neo7", "author_id": 1982580, "author_profile": "https://Stackoverflow.com/users/1982580", "pm_score": 0, "selected": false, "text": "<p>Here is my answer without using any other data structure like set or hashmap etc.</p>\n\n<pre><code>public static &lt;T&gt; ArrayList&lt;T&gt; uniquefy(ArrayList&lt;T&gt; myList) {\n\n ArrayList &lt;T&gt; uniqueArrayList = new ArrayList&lt;T&gt;();\n for (int i = 0; i &lt; myList.size(); i++){\n if (!uniqueArrayList.contains(myList.get(i))){\n uniqueArrayList.add(myList.get(i));\n }\n }\n\n return uniqueArrayList;\n}\n</code></pre>\n" }, { "answer_id": 33751322, "author": "satish", "author_id": 5281441, "author_profile": "https://Stackoverflow.com/users/5281441", "pm_score": -1, "selected": false, "text": "<p>In Java, List permits ordered access of their elements. They can have duplicates because their lookup key is the position not some hash code, every element can be modified while they remain in the list where as Set represents a collection of unique elements and while elements are in set, they must not be modified.While there is no restriction preventing you from modifying elements in a set, if an element is modified, then it could become forever lost in the set.</p>\n<pre><code>public static void main(String[] args) {\n List&lt;String&gt; l = new ArrayList&lt;String&gt;();\n l.add(&quot;A&quot;);\n l.add(&quot;B&quot;);\n l.add(&quot;C&quot;);\n l.add(&quot;A&quot;);\n System.out.println(&quot;Before removing duplicates: &quot;);\n for (String s : l) {\n System.out.println(s);\n }\n Set&lt;String&gt; set = new HashSet&lt;String&gt;(l);\n List&lt;String&gt; newlist = new ArrayList&lt;String&gt;(set);\n System.out.println(&quot;after removing duplicates: &quot;);\n for (String s : newlist) {\n System.out.println(s);\n }\n }\n</code></pre>\n<p>for reference, refer this link <a href=\"http://techno-terminal.blogspot.in/2015/11/how-to-remove-duplicates-from-arraylist.html\" rel=\"nofollow noreferrer\">How to remove duplicates from ArrayList</a></p>\n" }, { "answer_id": 34033817, "author": "Ravi Vital", "author_id": 5628310, "author_profile": "https://Stackoverflow.com/users/5628310", "pm_score": 0, "selected": false, "text": "<p>Would something like this work better ?</p>\n<pre><code>public static void removeDuplicates(ArrayList&lt;String&gt; list) {\n Arraylist&lt;Object&gt; ar = new Arraylist&lt;Object&gt;();\n Arraylist&lt;Object&gt; tempAR = new Arraylist&lt;Object&gt;();\n while (list.size()&gt;0){\n ar.add(list(0));\n list.removeall(Collections.singleton(list(0)));\n }\n list.addAll(ar);\n}\n</code></pre>\n<p>That should maintain the order and also not be quadratic in run time.</p>\n" }, { "answer_id": 34204842, "author": "Craig P. Motlin", "author_id": 23572, "author_profile": "https://Stackoverflow.com/users/23572", "pm_score": 3, "selected": false, "text": "<p>If you're willing to use a third-party library, you can use the method <code>distinct()</code> in <a href=\"http://www.eclipse.org/collections/\" rel=\"nofollow\">Eclipse Collections</a> (formerly GS Collections).</p>\n\n<pre><code>ListIterable&lt;Integer&gt; integers = FastList.newListWith(1, 3, 1, 2, 2, 1);\nAssert.assertEquals(\n FastList.newListWith(1, 3, 2),\n integers.distinct());\n</code></pre>\n\n<p>The advantage of using <code>distinct()</code> instead of converting to a Set and then back to a List is that <code>distinct()</code> preserves the order of the original List, retaining the first occurrence of each element. It's implemented by using both a Set and a List.</p>\n\n<pre><code>MutableSet&lt;T&gt; seenSoFar = UnifiedSet.newSet();\nint size = list.size();\nfor (int i = 0; i &lt; size; i++)\n{\n T item = list.get(i);\n if (seenSoFar.add(item))\n {\n targetCollection.add(item);\n }\n}\nreturn targetCollection;\n</code></pre>\n\n<p>If you cannot convert your original List into an Eclipse Collections type, you can use ListAdapter to get the same API.</p>\n\n<pre><code>MutableList&lt;Integer&gt; distinct = ListAdapter.adapt(integers).distinct();\n</code></pre>\n\n<p><strong>Note:</strong> I am a committer for Eclipse Collections.</p>\n" }, { "answer_id": 36234085, "author": "Hardip", "author_id": 5018911, "author_profile": "https://Stackoverflow.com/users/5018911", "pm_score": 2, "selected": false, "text": "<pre><code>ArrayList&lt;String&gt; city=new ArrayList&lt;String&gt;();\ncity.add(\"rajkot\");\ncity.add(\"gondal\");\ncity.add(\"rajkot\");\ncity.add(\"gova\");\ncity.add(\"baroda\");\ncity.add(\"morbi\");\ncity.add(\"gova\");\n\nHashSet&lt;String&gt; hashSet = new HashSet&lt;String&gt;();\nhashSet.addAll(city);\ncity.clear();\ncity.addAll(hashSet);\nToast.makeText(getActivity(),\"\" + city.toString(),Toast.LENGTH_SHORT).show();\n</code></pre>\n" }, { "answer_id": 37405769, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 6, "selected": false, "text": "<p>Suppose we have a list of <code>String</code> like:</p>\n\n<pre><code>List&lt;String&gt; strList = new ArrayList&lt;&gt;(5);\n// insert up to five items to list. \n</code></pre>\n\n<p>Then we can remove duplicate elements in multiple ways.</p>\n\n<h2>Prior to Java 8</h2>\n\n<pre><code>List&lt;String&gt; deDupStringList = new ArrayList&lt;&gt;(new HashSet&lt;&gt;(strList));\n</code></pre>\n\n<p><strong>Note:</strong> If we want to maintain the insertion order then we need to use <code>LinkedHashSet</code> in place of <code>HashSet</code></p>\n\n<h2>Using Guava</h2>\n\n<pre><code>List&lt;String&gt; deDupStringList2 = Lists.newArrayList(Sets.newHashSet(strList));\n</code></pre>\n\n<h2>Using Java 8</h2>\n\n<pre><code>List&lt;String&gt; deDupStringList3 = strList.stream().distinct().collect(Collectors.toList());\n</code></pre>\n\n<p><strong>Note:</strong> In case we want to collect the result in a <strong>specific list implementation</strong> e.g. <code>LinkedList</code> then we can modify the above example as:</p>\n\n<pre><code>List&lt;String&gt; deDupStringList3 = strList.stream().distinct()\n .collect(Collectors.toCollection(LinkedList::new));\n</code></pre>\n\n<p>We can use <code>parallelStream</code> also in the above code but it may not give expected performace benefits. Check this <a href=\"https://stackoverflow.com/questions/53645037/will-parallel-stream-work-fine-with-distinct-operation\">question</a> for more.</p>\n" }, { "answer_id": 40419515, "author": "Nenad Bulatović", "author_id": 1159404, "author_profile": "https://Stackoverflow.com/users/1159404", "pm_score": 5, "selected": false, "text": "<p>You can also do it this way, and preserve order:</p>\n\n<pre><code>// delete duplicates (if any) from 'myArrayList'\nmyArrayList = new ArrayList&lt;String&gt;(new LinkedHashSet&lt;String&gt;(myArrayList));\n</code></pre>\n" }, { "answer_id": 43025730, "author": "Gujjula Ramesh Reddy", "author_id": 6128908, "author_profile": "https://Stackoverflow.com/users/6128908", "pm_score": 1, "selected": false, "text": "<p>This is used for your Custom Objects list </p>\n\n<pre><code> public List&lt;Contact&gt; removeDuplicates(List&lt;Contact&gt; list) {\n // Set set1 = new LinkedHashSet(list);\n Set set = new TreeSet(new Comparator() {\n\n @Override\n public int compare(Object o1, Object o2) {\n if (((Contact) o1).getId().equalsIgnoreCase(((Contact) o2).getId()) /*&amp;&amp;\n ((Contact)o1).getName().equalsIgnoreCase(((Contact)o2).getName())*/) {\n return 0;\n }\n return 1;\n }\n });\n set.addAll(list);\n\n final List newList = new ArrayList(set);\n return newList;\n}\n</code></pre>\n" }, { "answer_id": 47580485, "author": "HamidReza", "author_id": 767555, "author_profile": "https://Stackoverflow.com/users/767555", "pm_score": 2, "selected": false, "text": "<p>you can use nested loop in follow :</p>\n\n<pre><code>ArrayList&lt;Class1&gt; l1 = new ArrayList&lt;Class1&gt;();\nArrayList&lt;Class1&gt; l2 = new ArrayList&lt;Class1&gt;();\n\n Iterator iterator1 = l1.iterator();\n boolean repeated = false;\n\n while (iterator1.hasNext())\n {\n Class1 c1 = (Class1) iterator1.next();\n for (Class1 _c: l2) {\n if(_c.getId() == c1.getId())\n repeated = true;\n }\n if(!repeated)\n l2.add(c1);\n }\n</code></pre>\n" }, { "answer_id": 50253949, "author": "Saurabh Gaddelpalliwar", "author_id": 4019233, "author_profile": "https://Stackoverflow.com/users/4019233", "pm_score": 3, "selected": false, "text": "<h2>If you are using model type List&lt; T>/ArrayList&lt; T> . Hope,it's help you.</h2>\n\n<p><strong>Here is my code without using any other data structure like set or hashmap</strong></p>\n\n<pre><code>for (int i = 0; i &lt; Models.size(); i++){\nfor (int j = i + 1; j &lt; Models.size(); j++) { \n if (Models.get(i).getName().equals(Models.get(j).getName())) { \n Models.remove(j);\n j--;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 50382676, "author": "Sameer Shrestha", "author_id": 7044810, "author_profile": "https://Stackoverflow.com/users/7044810", "pm_score": 0, "selected": false, "text": "<p>Time Complexity : O(n) : Without Set</p>\n\n<pre><code>private static void removeDup(ArrayList&lt;String&gt; listWithDuplicateElements) {\n System.out.println(\" Original Duplicate List :\" + listWithDuplicateElements);\n List&lt;String&gt; listWithoutDuplicateElements = new ArrayList&lt;&gt;(listWithDuplicateElements.size());\n\n listWithDuplicateElements.stream().forEach(str -&gt; {\n if (listWithoutDuplicateElements.indexOf(str) == -1) {\n listWithoutDuplicateElements.add(str);\n }\n }); \n\n System.out.println(\" Without Duplicate List :\" + listWithoutDuplicateElements);\n}\n</code></pre>\n" }, { "answer_id": 51181971, "author": "seekingStillness", "author_id": 6592058, "author_profile": "https://Stackoverflow.com/users/6592058", "pm_score": 0, "selected": false, "text": "<p>This is the right one (if you are concerned about the overhead of HashSet.</p>\n\n<pre><code> public static ArrayList&lt;String&gt; removeDuplicates (ArrayList&lt;String&gt; arrayList){\n if (arrayList.isEmpty()) return null; //return what makes sense for your app\n Collections.sort(arrayList, String.CASE_INSENSITIVE_ORDER);\n //remove duplicates\n ArrayList &lt;String&gt; arrayList_mod = new ArrayList&lt;&gt;();\n arrayList_mod.add(arrayList.get(0));\n for (int i=1; i&lt;arrayList.size(); i++){\n if (!arrayList.get(i).equals(arrayList.get(i-1))) arrayList_mod.add(arrayList.get(i));\n }\n return arrayList_mod;\n}\n</code></pre>\n" }, { "answer_id": 54595465, "author": "saif", "author_id": 7208392, "author_profile": "https://Stackoverflow.com/users/7208392", "pm_score": 0, "selected": false, "text": "<pre><code>Set&lt;String&gt; strSet = strList.stream().collect(Collectors.toSet());\n</code></pre>\n\n<p>Is the easiest way to remove your duplicates.</p>\n" }, { "answer_id": 55073204, "author": "LiNKeR", "author_id": 10138416, "author_profile": "https://Stackoverflow.com/users/10138416", "pm_score": 0, "selected": false, "text": "<p>If you want your list to automatically ignore duplicates and preserve its order, you could create a <strong>HashList</strong>(a HashMap embedded List).</p>\n\n<pre><code>public static class HashList&lt;T&gt; extends ArrayList&lt;T&gt;{\n private HashMap &lt;T,T&gt; hashMap;\n public HashList(){\n hashMap=new HashMap&lt;&gt;();\n }\n\n @Override\n public boolean add(T t){\n if(hashMap.get(t)==null){\n hashMap.put(t,t);\n return super.add(t);\n }else return false;\n }\n\n @Override\n public boolean addAll(Collection&lt;? extends T&gt; c){\n HashList&lt;T&gt; addup=(HashList&lt;T&gt;)c;\n for(int i=0;i&lt;addup.size();i++){\n add(addup.get(i));\n }return true;\n }\n\n }\n</code></pre>\n\n<p><strong><code>Usage Example:</code></strong></p>\n\n<pre><code>HashList&lt;String&gt; hashlist=new HashList&lt;&gt;();\nhashList.add(\"hello\");\nhashList.add(\"hello\");\nSystem.out.println(\" HashList: \"+hashlist);\n</code></pre>\n" }, { "answer_id": 69499989, "author": "Gil SH", "author_id": 880223, "author_profile": "https://Stackoverflow.com/users/880223", "pm_score": 0, "selected": false, "text": "<p>Here is a solution that works with any object:</p>\n<pre><code>public static &lt;T&gt; List&lt;T&gt; clearDuplicates(List&lt;T&gt; messages,Comparator&lt;T&gt; comparator) {\n List&lt;T&gt; results = new ArrayList&lt;T&gt;();\n for (T m1 : messages) {\n boolean found = false;\n for (T m2 : results) {\n if (comparator.compare(m1,m2)==0) {\n found=true;\n break;\n }\n }\n if (!found) {\n results.add(m1);\n }\n }\n return results;\n}\n</code></pre>\n" }, { "answer_id": 71637149, "author": "Kirguduck", "author_id": 8619606, "author_profile": "https://Stackoverflow.com/users/8619606", "pm_score": 0, "selected": false, "text": "<p>Kotlin</p>\n<pre><code>val list = listOf('a', 'A', 'b', 'B', 'A', 'a')\nprintln(list.distinct()) // [a, A, b, B]\nprintln(list.distinctBy { it.uppercaseChar() }) // [a, b]\n</code></pre>\n<p>from here <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/distinct-by.html\" rel=\"nofollow noreferrer\">kotlinlang</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25778/" ]
I have an `ArrayList<String>`, and I want to remove repeated strings from it. How can I do this?
If you don't want duplicates in a `Collection`, you should consider why you're using a `Collection` that allows duplicates. The easiest way to remove repeated elements is to add the contents to a `Set` (which will not allow duplicates) and then add the `Set` back to the `ArrayList`: ``` Set<String> set = new HashSet<>(yourList); yourList.clear(); yourList.addAll(set); ``` Of course, this destroys the ordering of the elements in the `ArrayList`.
203,990
<p>I'm writing a C++ client which is using libcurl for communicating with a PHP script.</p> <p>The communication should be session based, and thus the first task is to login and make the PHP script set up a session.</p> <p>I'm not used to working with sessions either from C++ or PHP. I basically know that it has to do with cookies and communicating session id.</p> <p>I can't find any example on the curl homepage which demonstrates a simple session management use case.</p> <p>I'm assuming it has something to do with one or many of the following options in curl:</p> <pre><code>CURLOPT_COOKIE CURLOPT_COOKIEFILE CURLOPT_COOKIEJAR CURLOPT_COOKIESESSION CURLOPT_COOKIELIST </code></pre> <p>But I can't really see the big picture just from the documentation of CURLOPT_COOKIESESSION for instance.</p> <p>Anybody who has done this, please share a simple piece of code which shows the concept.</p> <p>Regards</p> <p>Robert</p>
[ { "answer_id": 204023, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": -1, "selected": false, "text": "<p>A session in PHP has the purpose of preserving some state over several requests, since HTTP in itself is stateless. To get a session from PHP, simply request a php page that starts a session, and keep the cookie you get back for subsequent requests.</p>\n\n<p>Starting a session in php is simple - call the session_start() function. That function will resume an existsing session if the cookie exists in the request. When the session is started, persistent variables can be set using the superglobal array $_SESSION. It's a good idea to store a 'is logged in'-token there =) To end the PHP session, set $_SESSION to array(), so that the token is destroyed.</p>\n" }, { "answer_id": 204357, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": 1, "selected": false, "text": "<p>I have an example for command line curl in bash - logging in to PHPMyAdmin and then using its export function. Maybe it will help you:</p>\n\n<pre><code>#!/bin/bash\n\nPHPMYADMINURL=\"http://www.example.com/phpmyadmin/\"\n\n# Username and password, has to be URL-encoded\nMYUSERNAME=\"username\"\nMYPASSWORD=\"password\"\n\nTMPCOOKIES=\"$(mktemp)\" || exit 1\n\nTOKEN=$(\n curl \\\n --silent \\\n --show-error \\\n --data @- \\\n --data \"lang=en-utf-8\" \\\n --cookie-jar \"$TMPCOOKIES\" \\\n --dump-header - \\\n --url \"$PHPMYADMINURL\" \\\n &lt;&lt;&lt; \"pma_username=$MYUSERNAME&amp;pma_password=$MYPASSWORD\" \\\n | egrep 'token=[0-9a-h]+' \\\n | head -1 \\\n | sed -r 's/^(.*token=)([0-9a-h]+)(.*)/\\2/' \\\n ) || exit 1\n\ncurl \\\n --cookie \"$TMPCOOKIES\" \\\n --data \"token=$TOKEN\" \\\n --data \"export_type=server\" \\\n --data \"what=sql\" \\\n --data \"asfile=sendit\" \\\n --data \"sql_data=something\" \\\n --data \"sql_columns=something\" \\\n --data \"sql_hex_for_blob=something\" \\\n --data \"compression=gzip\" \\\n --url \"$PHPMYADMINURL\"export.php 1&gt;&amp;2 || exit 1\n\nrm -f \"$TMPCOOKIES\" || exit 1\n</code></pre>\n\n<p>PHPMyAdmin uses tokens besides cookies so the code is a little more complicated than normally needed.</p>\n" }, { "answer_id": 205417, "author": "pk.", "author_id": 10615, "author_profile": "https://Stackoverflow.com/users/10615", "pm_score": 3, "selected": true, "text": "<p>As far as I understand it, CURL will handle session cookies automatically for you if you enable cookies, as long as you reuse your CURL handle for each request in the session:</p>\n\n<pre><code>CURL *Handle = curl_easy_init();\n\n// Read cookies from a previous session, as stored in MyCookieFileName.\ncurl_easy_setopt( Handle, CURLOPT_COOKIEFILE, MyCookieFileName );\n// Save cookies from *this* session in MyCookieFileName\ncurl_easy_setopt( Handle, CURLOPT_COOKIEJAR, MyCookieFileName );\n\ncurl_easy_setopt( Handle, CURLOPT_URL, MyLoginPageUrl );\nassert( curl_easy_perform( Handle ) == CURLE_OK );\n\ncurl_easy_setopt( Handle, CURLOPT_URL, MyActionPageUrl );\nassert( curl_easy_perform( Handle ) == CURLE_OK );\n\n// The cookies are actually saved here.\ncurl_easy_cleanup( Handle );\n</code></pre>\n\n<p>I'm not positive that you need to set both COOKIEFILE and COOKIEJAR, but the documentation makes it seem that way. In any case, you have to set one of the two in order to enable cookies at all in CURL. You can do something as simple as:</p>\n\n<pre><code>curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, \"\" );\n</code></pre>\n\n<p>That won't read any cookies from disk, but it will enable session cookies for the duration of the curl handle.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/203990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
I'm writing a C++ client which is using libcurl for communicating with a PHP script. The communication should be session based, and thus the first task is to login and make the PHP script set up a session. I'm not used to working with sessions either from C++ or PHP. I basically know that it has to do with cookies and communicating session id. I can't find any example on the curl homepage which demonstrates a simple session management use case. I'm assuming it has something to do with one or many of the following options in curl: ``` CURLOPT_COOKIE CURLOPT_COOKIEFILE CURLOPT_COOKIEJAR CURLOPT_COOKIESESSION CURLOPT_COOKIELIST ``` But I can't really see the big picture just from the documentation of CURLOPT\_COOKIESESSION for instance. Anybody who has done this, please share a simple piece of code which shows the concept. Regards Robert
As far as I understand it, CURL will handle session cookies automatically for you if you enable cookies, as long as you reuse your CURL handle for each request in the session: ``` CURL *Handle = curl_easy_init(); // Read cookies from a previous session, as stored in MyCookieFileName. curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, MyCookieFileName ); // Save cookies from *this* session in MyCookieFileName curl_easy_setopt( Handle, CURLOPT_COOKIEJAR, MyCookieFileName ); curl_easy_setopt( Handle, CURLOPT_URL, MyLoginPageUrl ); assert( curl_easy_perform( Handle ) == CURLE_OK ); curl_easy_setopt( Handle, CURLOPT_URL, MyActionPageUrl ); assert( curl_easy_perform( Handle ) == CURLE_OK ); // The cookies are actually saved here. curl_easy_cleanup( Handle ); ``` I'm not positive that you need to set both COOKIEFILE and COOKIEJAR, but the documentation makes it seem that way. In any case, you have to set one of the two in order to enable cookies at all in CURL. You can do something as simple as: ``` curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, "" ); ``` That won't read any cookies from disk, but it will enable session cookies for the duration of the curl handle.
204,007
<p>I get this error:-</p> <p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' at line 1</p> <p>whenever I tried something like this:-</p> <pre><code>mysql&gt; source /home/user1/sql/ddl.sql mysql&gt; source /home/user1/sql/insert.sql mysql&gt; source /home/user1/sql/cleanup.sql </code></pre> <p>The intresting thing is, this happen to each and every one of the sql scripts but only the first statement is corrupted. The rest of the statements in the script will run fine. I have worked around this by putting a dummy statement in every script.</p> <p>Anyone had this problem before? I am completely stumped and checking Google hadn't helped yet. Thanks in advance.</p>
[ { "answer_id": 204016, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>Your input files may contain a <a href=\"http://en.wikipedia.org/wiki/Byte_Order_Mark\" rel=\"nofollow noreferrer\">Unicode BOM</a>, which is a bit of cruft that some programs such as Notepad place at the start of the file to indicate the file format.</p>\n" }, { "answer_id": 204022, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "<p>A possibility is that the SQL files were written in Unicode with a <a href=\"https://en.wikipedia.org/wiki/Byte_Order_Mark\" rel=\"nofollow noreferrer\">BOM</a>, which MySQL cannot interpret. </p>\n\n<p>That would explain the symptoms.</p>\n\n<p>A solution is to open them in a decent editor and save them back without it.</p>\n\n<p>Example in VIM:</p>\n\n<p>Force BOM removal</p>\n\n<pre><code>:set nobomb\n</code></pre>\n\n<p>Save and quit</p>\n\n<pre><code>:x!\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18500/" ]
I get this error:- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' at line 1 whenever I tried something like this:- ``` mysql> source /home/user1/sql/ddl.sql mysql> source /home/user1/sql/insert.sql mysql> source /home/user1/sql/cleanup.sql ``` The intresting thing is, this happen to each and every one of the sql scripts but only the first statement is corrupted. The rest of the statements in the script will run fine. I have worked around this by putting a dummy statement in every script. Anyone had this problem before? I am completely stumped and checking Google hadn't helped yet. Thanks in advance.
A possibility is that the SQL files were written in Unicode with a [BOM](https://en.wikipedia.org/wiki/Byte_Order_Mark), which MySQL cannot interpret. That would explain the symptoms. A solution is to open them in a decent editor and save them back without it. Example in VIM: Force BOM removal ``` :set nobomb ``` Save and quit ``` :x! ```
204,017
<p>I have a Python script that needs to execute an external program, but for some reason fails.</p> <p>If I have the following script:</p> <pre><code>import os; os.system("C:\\Temp\\a b c\\Notepad.exe"); raw_input(); </code></pre> <p>Then it fails with the following error:</p> <blockquote> <p>'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.</p> </blockquote> <p>If I escape the program with quotes:</p> <pre><code>import os; os.system('"C:\\Temp\\a b c\\Notepad.exe"'); raw_input(); </code></pre> <p>Then it works. However, if I add a parameter, it stops working again:</p> <pre><code>import os; os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"'); raw_input(); </code></pre> <p>What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.</p> <p>Also note, moving the program to a non-spaced path is not an option either.</p> <hr> <p>This does not work either:</p> <pre><code>import os; os.system("'C:\\Temp\\a b c\\Notepad.exe'"); raw_input(); </code></pre> <p>Note the swapped single/double quotes.</p> <p>With or without a parameter to Notepad here, it fails with the error message</p> <blockquote> <p>The filename, directory name, or volume label syntax is incorrect.</p> </blockquote>
[ { "answer_id": 204024, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "<p>I suspect it's the same problem as when you use shortcuts in Windows... Try this:</p>\n\n<pre><code>import os;\nos.system(\"\\\"C:\\\\Temp\\\\a b c\\\\Notepad.exe\\\" C:\\\\test.txt\");\n</code></pre>\n" }, { "answer_id": 204049, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 9, "selected": true, "text": "<p><a href=\"http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module\" rel=\"noreferrer\"><code>subprocess.call</code></a> will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.</p>\n\n<pre><code>import subprocess\nsubprocess.call(['C:\\\\Temp\\\\a b c\\\\Notepad.exe', 'C:\\\\test.txt'])\n</code></pre>\n" }, { "answer_id": 206215, "author": "user16738", "author_id": 16738, "author_profile": "https://Stackoverflow.com/users/16738", "pm_score": 6, "selected": false, "text": "<p>Here's a different way of doing it.</p>\n\n<p>If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS \"start\" command: the file is opened with whatever application (if any) its extension is associated with.</p>\n\n<pre><code>filepath = 'textfile.txt'\nimport os\nos.startfile(filepath)\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>import os\nos.startfile('textfile.txt')\n</code></pre>\n\n<p>This will open textfile.txt with Notepad if Notepad is associated with .txt files.</p>\n" }, { "answer_id": 911976, "author": "Daniel Serodio", "author_id": 112254, "author_profile": "https://Stackoverflow.com/users/112254", "pm_score": 5, "selected": false, "text": "<p>The outermost quotes are consumed by Python itself, and the Windows shell doesn't see it. As mentioned above, Windows only understands double-quotes. \nPython will convert forward-slashed to backslashes on Windows, so you can use</p>\n\n<pre><code>os.system('\"C://Temp/a b c/Notepad.exe\"')\n</code></pre>\n\n<p>The ' is consumed by Python, which then passes \"C://Temp/a b c/Notepad.exe\" (as a Windows path, no double-backslashes needed) to CMD.EXE</p>\n" }, { "answer_id": 1622730, "author": "Paul Hoffman", "author_id": 196379, "author_profile": "https://Stackoverflow.com/users/196379", "pm_score": 4, "selected": false, "text": "<p>At least in Windows 7 and Python 3.1, <code>os.system</code> in Windows wants the command line <em>double-quoted</em> if there are spaces in path to the command. For example:</p>\n\n<pre><code> TheCommand = '\\\"\\\"C:\\\\Temp\\\\a b c\\\\Notepad.exe\\\"\\\"'\n os.system(TheCommand)\n</code></pre>\n\n<p>A real-world example that was stumping me was cloning a drive in VirtualBox. The <code>subprocess.call</code> solution above didn't work because of some access rights issue, but when I double-quoted the command, <code>os.system</code> became happy:</p>\n\n<pre><code> TheCommand = '\\\"\\\"C:\\\\Program Files\\\\Sun\\\\VirtualBox\\\\VBoxManage.exe\\\" ' \\\n + ' clonehd \\\"' + OrigFile + '\\\" \\\"' + NewFile + '\\\"\\\"'\n os.system(TheCommand)\n</code></pre>\n" }, { "answer_id": 2742855, "author": "rahul", "author_id": 329544, "author_profile": "https://Stackoverflow.com/users/329544", "pm_score": 4, "selected": false, "text": "<pre><code>import win32api # if active state python is installed or install pywin32 package seperately\n\ntry: win32api.WinExec('NOTEPAD.exe') # Works seamlessly\nexcept: pass\n</code></pre>\n" }, { "answer_id": 48382479, "author": "gbonetti", "author_id": 1534775, "author_profile": "https://Stackoverflow.com/users/1534775", "pm_score": 4, "selected": false, "text": "<p>For python >= 3.5 <code>subprocess.run</code> should be used in place of <code>subprocess.call</code></p>\n\n<p><a href=\"https://docs.python.org/3/library/subprocess.html#older-high-level-api\" rel=\"noreferrer\">https://docs.python.org/3/library/subprocess.html#older-high-level-api</a></p>\n\n<pre><code>import subprocess\nsubprocess.run(['notepad.exe', 'test.txt'])\n</code></pre>\n" }, { "answer_id": 48382727, "author": "Benyamin Jafari - aGn", "author_id": 3702377, "author_profile": "https://Stackoverflow.com/users/3702377", "pm_score": 0, "selected": false, "text": "<p>Suppose we want to run your Django web server (in Linux) that there is space between your path (path=<code>'/home/&lt;you&gt;/&lt;first-path-section&gt; &lt;second-path-section&gt;'</code>), so do the following:</p>\n\n<pre><code>import subprocess\n\nargs = ['{}/manage.py'.format('/home/&lt;you&gt;/&lt;first-path-section&gt; &lt;second-path-section&gt;'), 'runserver']\nres = subprocess.Popen(args, stdout=subprocess.PIPE)\noutput, error_ = res.communicate()\n\nif not error_:\n print(output)\nelse:\n print(error_)\n</code></pre>\n\n<hr>\n\n<p>[<strong>Note</strong>]: </p>\n\n<ul>\n<li>Do not forget accessing permission: <code>chmod 755 -R &lt;'yor path'&gt;</code></li>\n<li><code>manage.py</code> is exceutable: <code>chmod +x manage.py</code></li>\n</ul>\n" }, { "answer_id": 57399125, "author": "WestAce", "author_id": 3781163, "author_profile": "https://Stackoverflow.com/users/3781163", "pm_score": 1, "selected": false, "text": "<p>For Python 3.7, use <a href=\"https://docs.python.org/3.7/library/subprocess.html#using-the-subprocess-module\" rel=\"nofollow noreferrer\">subprocess.call</a>. Use raw string to simplify the Windows paths:</p>\n\n<pre><code>import subprocess\nsubprocess.call([r'C:\\Temp\\Example\\Notepad.exe', 'C:\\test.txt'])\n</code></pre>\n" }, { "answer_id": 61435838, "author": "rajat prakash", "author_id": 6593856, "author_profile": "https://Stackoverflow.com/users/6593856", "pm_score": 0, "selected": false, "text": "<p>No need for sub-process, It can be simply achieved by</p>\n<pre><code>GitPath=&quot;C:\\\\Program Files\\\\Git\\\\git-bash.exe&quot;# Application File Path in mycase its GITBASH\nos.startfile(GitPath)\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
I have a Python script that needs to execute an external program, but for some reason fails. If I have the following script: ``` import os; os.system("C:\\Temp\\a b c\\Notepad.exe"); raw_input(); ``` Then it fails with the following error: > > 'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file. > > > If I escape the program with quotes: ``` import os; os.system('"C:\\Temp\\a b c\\Notepad.exe"'); raw_input(); ``` Then it works. However, if I add a parameter, it stops working again: ``` import os; os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"'); raw_input(); ``` What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete. Also note, moving the program to a non-spaced path is not an option either. --- This does not work either: ``` import os; os.system("'C:\\Temp\\a b c\\Notepad.exe'"); raw_input(); ``` Note the swapped single/double quotes. With or without a parameter to Notepad here, it fails with the error message > > The filename, directory name, or volume label syntax is incorrect. > > >
[`subprocess.call`](http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module) will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e. ``` import subprocess subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt']) ```
204,032
<p>I've run into a problem trying to return an object that holds a collection of childobjects that again can hold a collection of grandchild objects. I get an error, 'connection forcibly closed by host'.</p> <p>Is there any way to make this work? I currently have a structure resembling this:</p> <p>pseudo code:</p> <pre><code>Person: IEnumerable&lt;Order&gt; Order: IEnumerable&lt;OrderLine&gt; </code></pre> <p>All three objects have the DataContract attribute and all public properties i want exposed (including the IEnumerable's) have the DataMember attribute.</p> <p>I have multiple OperationContract's on my service and all the methods returning a single object OR an IEnumerable of an object works perfectly. It's only when i try to nest IEnumerable that it turns bad. Also in my client service reference i picked the generic list as my collection type. I just want to emphasize, <strong>only one of my operations/methods fail with this error - the rest of them work perfectly</strong>.</p> <p>EDIT (more detailed error description):</p> <pre><code>[SocketException (0x2746): An existing connection was forcibly closed by the remote host] [IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.] [WebException: The underlying connection was closed: An unexpected error occurred on a receive.] [CommunicationException: An error occurred while receiving the HTTP response to http://myservice.mydomain.dk/MyService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.] </code></pre> <p>I tried looking for logs but i can't find any... also i'm using a WSHttpBinding and an http endpoint.</p>
[ { "answer_id": 204114, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "<p>did you specify in your service behavior config? it seems like some information is missing in this stacktrace. </p>\n\n<p>can you grab the exception at server side (e.g. in visual studio debug mode or with a logging library like log4net). </p>\n\n<p>have you tried calling some other methods (simple helloworld() e.g.) on the same service to be sure that the service configuration itself works?\nthis kind of exceptino could also indicate some serialization problems. what types do you want to send over the wire? do you use KnownType's somewhere?</p>\n" }, { "answer_id": 204126, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<pre><code>Server Error in '/' Application.\n--------------------------------------------------------------------------------\n\nAn existing connection was forcibly closed by the remote host \nDescription: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. \n\nException Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host\n\nSource Error: \n\nAn unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. \n\nStack Trace: \n\n\n[SocketException (0x2746): An existing connection was forcibly closed by the remote host]\n System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +93\n System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +119\n\n[IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.]\n System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +267\n System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) +25\n System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) +306\n\n[WebException: The underlying connection was closed: An unexpected error occurred on a receive.]\n System.Net.HttpWebRequest.GetResponse() +1532114\n System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +40\n\n[CommunicationException: An error occurred while receiving the HTTP response to http://Zzzstrukturservice.xxx.dk/ZzzstrukturService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.]\n System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +2668969\n System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type) +717\n xxx.Services.ZzzstrukturServiceClient.ZzzstrukturServiceProxy.IZzzstrukturService.GetMatrixSet(Int32 matrixSetId) +0\n xxx.Services.ZzzstrukturServiceClient.ZzzstrukturRepository.GetMatrixSetById(Int32 matrixSetId) in f:\\ccnet\\work\\xxx.Zzzstruktur\\1. Presentation Layer\\ZzzstrukturServiceClient\\ZzzstrukturRepository.cs:90\n xxx.yyy.yyyWeb.AnnoncePage.OnLoad(EventArgs e) in f:\\ccnet\\work\\yyyV2\\1. Presentation Layer\\yyyWeb\\Annonce.aspx.cs:40\n System.Web.UI.Control.LoadRecursive() +47\n System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436\n\n\n\n\n--------------------------------------------------------------------------------\nVersion Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433 \n</code></pre>\n" }, { "answer_id": 204138, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 1, "selected": false, "text": "<p>this is actually the same information as your first exception description. it would be interesing what the original cause for the socketexception was. it has to be some type of error in the service itself. can you locate where exactly whar exception happens? </p>\n\n<p>i had similar errors when trying to return normal IEnumerables that were overwritten (they were marked as virtual) by NHibernate, and substitued with GenericPersistentBag, which is not serializable.\nhave you marked your IEnumerable datamembers as virtual due to nhibernate or something similar? this could explain your error.</p>\n\n<p>btw. wcf exceptions are often quite meaningless (which can be very frustrating when tracking down a bug ;)</p>\n" }, { "answer_id": 204351, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 4, "selected": false, "text": "<p>Ok i finally found the real problem in my case. It seems exposing enums is not the greatest thing in the world. I either have to set a default value on them, or instead expose the property as an int or whatever integer-type my enum is based on.</p>\n\n<p>Thanks for helping, you had no way of knowing this - i found the enums on the 3rd level in my structure and systematicly removing datamembers one by one was the way i found out. It seems i'm not the only one who ran into this problem - this guy obviously had similar problems :)</p>\n\n<p><a href=\"http://zianet.dk/blog/2007/11/24/serializing-enums-in-wcf/\" rel=\"nofollow noreferrer\">http://zianet.dk/blog/2007/11/24/serializing-enums-in-wcf/</a></p>\n" }, { "answer_id": 217492, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 6, "selected": true, "text": "<p>As a note, you need to learn how to use the WCF logging utilities:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms730064.aspx\" rel=\"noreferrer\">Logging info.</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms732009.aspx\" rel=\"noreferrer\">Config Editor</a> (makes it a snap to setup).</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms732023.aspx\" rel=\"noreferrer\">Trace viewer.</a> Totally awesome. Allows multiple services (client and server) to trace and can join them and help you analyse all the details. Lets you get to the root of issues really fast. (Cause when there's a server WCF error, the client is unlikely to get useful data out.)</p>\n" }, { "answer_id": 324944, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I don't know why this can happen. but i also had similar problems.</p>\n\n<p>I have changed my enums.remove the indexes(e.g. ASNOrder = 1, -> ASNOrder,),and no error occoured.</p>\n" }, { "answer_id": 2114679, "author": "Kyle Lahnakoski", "author_id": 214460, "author_profile": "https://Stackoverflow.com/users/214460", "pm_score": 1, "selected": false, "text": "<p>I have had the same problem too (.Net 3.5). Turns out my base class <code>DataContract</code> was missing a known type. It's unfortunate that the WCF error was not more descriptive.</p>\n" }, { "answer_id": 2114693, "author": "Chris O", "author_id": 194709, "author_profile": "https://Stackoverflow.com/users/194709", "pm_score": 0, "selected": false, "text": "<p>Don't return the literal <code>IEnumerable</code> in a contract, there is the famous <a href=\"https://connect.microsoft.com/wcf/feedback/ViewFeedBack.aspx?FeedbackID=336696\" rel=\"nofollow noreferrer\">WCF IEnumerable bug</a></p>\n" }, { "answer_id": 2474727, "author": "Thoại Nguyễn", "author_id": 297058, "author_profile": "https://Stackoverflow.com/users/297058", "pm_score": 2, "selected": false, "text": "<p>Add this line into <code>&lt;system.web/&gt;</code>:</p>\n\n<pre><code>&lt;httpRuntime maxRequestLength=\"102400\" executionTimeout=\"3600\" /&gt;\n</code></pre>\n" }, { "answer_id": 2699473, "author": "Tiny122", "author_id": 324294, "author_profile": "https://Stackoverflow.com/users/324294", "pm_score": 0, "selected": false, "text": "<p>Yep, I had the same problem here and it was todo with returning objects that had enum values in it. Changed the <code>DataMember</code> to an int and everything statrted working. </p>\n" }, { "answer_id": 3477537, "author": "trkll", "author_id": 419623, "author_profile": "https://Stackoverflow.com/users/419623", "pm_score": 0, "selected": false, "text": "<p>Try setting <code>[OperationBehavior()]</code> above your implementation of the interface method.</p>\n" }, { "answer_id": 4016710, "author": "Rob Willis", "author_id": 333315, "author_profile": "https://Stackoverflow.com/users/333315", "pm_score": 0, "selected": false, "text": "<p>I've had this error when using 'yield return' to build up an enumeration of objects mapped to my <code>DataContract</code> type. </p>\n\n<p>Calling <code>ToList</code> / <code>ToArray</code> on the yield results fixed the issue and the service call worked correctly.</p>\n" }, { "answer_id": 4050171, "author": "indiPy", "author_id": 341950, "author_profile": "https://Stackoverflow.com/users/341950", "pm_score": 3, "selected": false, "text": "<p>If you are working with WCF+(EF+POCO) then try setting,</p>\n\n<pre><code>ObjectContext.ContextOptions.LazyLoadingEnabled = false;\nObjectContext.ContextOptions.ProxyCreationEnabled = false;\n</code></pre>\n" }, { "answer_id": 4638483, "author": "Brandon Roberson", "author_id": 568669, "author_profile": "https://Stackoverflow.com/users/568669", "pm_score": 2, "selected": false, "text": "<p>Enums get a <code>DataContract</code> attribute, like any class would, but the enum values aren't supposed to have <code>DataMember</code> attributes on them.</p>\n\n<p>Change them to <code>EnumMember</code> and you'll stop getting this inscrutable error.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
I've run into a problem trying to return an object that holds a collection of childobjects that again can hold a collection of grandchild objects. I get an error, 'connection forcibly closed by host'. Is there any way to make this work? I currently have a structure resembling this: pseudo code: ``` Person: IEnumerable<Order> Order: IEnumerable<OrderLine> ``` All three objects have the DataContract attribute and all public properties i want exposed (including the IEnumerable's) have the DataMember attribute. I have multiple OperationContract's on my service and all the methods returning a single object OR an IEnumerable of an object works perfectly. It's only when i try to nest IEnumerable that it turns bad. Also in my client service reference i picked the generic list as my collection type. I just want to emphasize, **only one of my operations/methods fail with this error - the rest of them work perfectly**. EDIT (more detailed error description): ``` [SocketException (0x2746): An existing connection was forcibly closed by the remote host] [IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.] [WebException: The underlying connection was closed: An unexpected error occurred on a receive.] [CommunicationException: An error occurred while receiving the HTTP response to http://myservice.mydomain.dk/MyService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.] ``` I tried looking for logs but i can't find any... also i'm using a WSHttpBinding and an http endpoint.
As a note, you need to learn how to use the WCF logging utilities: [Logging info.](http://msdn.microsoft.com/en-us/library/ms730064.aspx) [Config Editor](http://msdn.microsoft.com/en-us/library/ms732009.aspx) (makes it a snap to setup). [Trace viewer.](http://msdn.microsoft.com/en-us/library/ms732023.aspx) Totally awesome. Allows multiple services (client and server) to trace and can join them and help you analyse all the details. Lets you get to the root of issues really fast. (Cause when there's a server WCF error, the client is unlikely to get useful data out.)
204,040
<p>REBOL has no built-in way to perform list comprehensions. However, REBOL has a powerful facility (known as <code>parse</code>) that can be used to create domain-specific languages (DSLs). I've used <code>parse</code> to create such a mini-DSL for list comprehensions. In order to interpret the expression, the block containing the comprehension is passed to a function, which for lack of a better term I've called <code>comprehend</code>.</p> <p><strong>Example:</strong></p> <pre><code>comprehend [(a * b) for a in 1x100 for b in 4x10 where (all [odd? a odd? b])] </code></pre> <p>For some reason, <code>comprehend</code> doesn't sound right to me, but something like <code>eval</code> is too general.</p> <p>I haven't found any other language that requires a keyword or function for list comprehensions. They are pure syntactic sugar wherever they exist. Unfortunately I don't have that option. So, seeing that I must have a function, what's a good, succinct, logical name for it?</p>
[ { "answer_id": 501616, "author": "igowen", "author_id": 53924, "author_profile": "https://Stackoverflow.com/users/53924", "pm_score": 2, "selected": false, "text": "<p>Because list comprehensions can be thought of as analogous to map, you might think about calling it something like \"listmap\". Alternately, because list comprehensions are based on set-builder notation, you could call it something along the lines of \"build\" or \"buildlist\".</p>\n\n<p>(Disclaimer: I know very little about REBOL, so forgive me if these names are already taken)</p>\n" }, { "answer_id": 501642, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>How about <code>select</code>?</p>\n\n<p><code>select [(a * b) for a in 1x100 for b in 4x10 where (all [odd? a odd? b])]</code></p>\n" }, { "answer_id": 501651, "author": "Logan Capaldo", "author_id": 61289, "author_profile": "https://Stackoverflow.com/users/61289", "pm_score": 1, "selected": false, "text": "<p><code>do</code> could be appropriate, as list comprehensions are just one instance of Monad comprehensions, and <code>do</code> is the keyword used in Haskell for sugared Monadic computations but I suspect it's too vague for a user library. I called my list comprehension function <code>comp</code>, but that's just an abbreviation of what you already have. Perhaps <code>yielding</code>? E.g. <code>yielding [(a * b) for a in 1x100 for b in 4x10 where (all [odd? a odd? b])]</code>. Just sort of squint and pretend the [ ] aren't there.</p>\n" }, { "answer_id": 501979, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 2, "selected": false, "text": "<p>transmogrify</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27779/" ]
REBOL has no built-in way to perform list comprehensions. However, REBOL has a powerful facility (known as `parse`) that can be used to create domain-specific languages (DSLs). I've used `parse` to create such a mini-DSL for list comprehensions. In order to interpret the expression, the block containing the comprehension is passed to a function, which for lack of a better term I've called `comprehend`. **Example:** ``` comprehend [(a * b) for a in 1x100 for b in 4x10 where (all [odd? a odd? b])] ``` For some reason, `comprehend` doesn't sound right to me, but something like `eval` is too general. I haven't found any other language that requires a keyword or function for list comprehensions. They are pure syntactic sugar wherever they exist. Unfortunately I don't have that option. So, seeing that I must have a function, what's a good, succinct, logical name for it?
How about `select`? `select [(a * b) for a in 1x100 for b in 4x10 where (all [odd? a odd? b])]`
204,050
<p>I know a role name and want to find all users in this role. How do I acheive this in SQL Server 2000 (in the SQL script, not in Management Studio or other tool)?</p>
[ { "answer_id": 204105, "author": "Tim", "author_id": 10363, "author_profile": "https://Stackoverflow.com/users/10363", "pm_score": 3, "selected": true, "text": "<p>You can use the following stored procedures:</p>\n\n<p>For fixed server roles, the stored procedure is <a href=\"http://msdn.microsoft.com/en-us/library/ms188772.aspx\" rel=\"nofollow noreferrer\">sp_helpsrvrolemember</a>:</p>\n\n<pre><code>exec sp_helpsrvrolemember 'role'\n</code></pre>\n\n<p>For general roles, the stored procedure is <a href=\"http://msdn.microsoft.com/en-us/library/ms178021.aspx\" rel=\"nofollow noreferrer\">sp_helprolemember</a>:</p>\n\n<pre><code>exec sp_helprolemember 'role'\n</code></pre>\n" }, { "answer_id": 204106, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 0, "selected": false, "text": "<p>Just use SQL-DMO:\nReplace <em>rolename</em> with your role</p>\n\n<pre><code>exec sp_helprolemember rolename\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23714/" ]
I know a role name and want to find all users in this role. How do I acheive this in SQL Server 2000 (in the SQL script, not in Management Studio or other tool)?
You can use the following stored procedures: For fixed server roles, the stored procedure is [sp\_helpsrvrolemember](http://msdn.microsoft.com/en-us/library/ms188772.aspx): ``` exec sp_helpsrvrolemember 'role' ``` For general roles, the stored procedure is [sp\_helprolemember](http://msdn.microsoft.com/en-us/library/ms178021.aspx): ``` exec sp_helprolemember 'role' ```
204,075
<p>I know many people who use computers every day, who do not know how to select multiple items in a HTML select box/list. I don't want to use this control in my pages any more:</p> <pre><code>Please pick 3 options: &lt;select name="categories" size="10" multiple="yes"&gt; </code></pre> <p>So what user-friendly alternatives do you suggest? Perhaps have 10 tickboxes...or maybe just have each option in a coloured block which changes colour when they click to choose it? This gets messier when I consider my current list of 20 options might grow to 50 eventually.</p> <p>Whatever way I pick it's gonna be a pain to validate it (using Javascript), to make sure the person picks at least 1 item and not more than 3. It's not about detecting how many options they have picked, the problem is more about how to convey this to the user in a friendly way!</p> <p><b>Edit:</b> I suppose I could use tags, like right here on stackoverflow, but I feel these are less appropriate if the users are non-technical (and half of them will be).</p>
[ { "answer_id": 204088, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 3, "selected": true, "text": "<p>You could just use a manual list of items (Say as simple links), that have Javascript onclick behavior that deselects/selects manually. Basically by changing the css class between two values, and checking these css (Or some other attribute) during submission to determine the selections.</p>\n\n<p>This would allow the user to simply select an item by clicking, and deselect by clicking, rather than the standard Ctrl+Click requirement.</p>\n" }, { "answer_id": 204104, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 4, "selected": false, "text": "<p>Alternatives I used in past are:</p>\n\n<p>1) For small number of items use a checkbox list. \nThe checkboxes are much more intuitive and simple to use, but for large number of items it can became an issue. Still, when the number of items is growing you can add a:</p>\n\n<pre><code>&lt;div style=\"overflow: scroll\" /&gt;\n</code></pre>\n\n<p>with a fixed height.</p>\n\n<p>2) For very large number of items it becomes difficult to see what is really selected especially when there are few items actually selected. In this case two lists side by side with the possibility to move items from one to another is a much better approach.</p>\n\n<p>3) When the number of items is not very big but greater than a few, I used a dropdown with checkboxes build in-house that has the advantage of occupying only a small space. Something like <a href=\"http://code.google.com/p/dropdown-check-list/\" rel=\"nofollow noreferrer\">this</a> might be of help.</p>\n" }, { "answer_id": 204109, "author": "Vlad Gudim", "author_id": 22088, "author_profile": "https://Stackoverflow.com/users/22088", "pm_score": 1, "selected": false, "text": "<p>For unfrequent users having three drop downs might work the best>: </p>\n\n<pre><code>&lt;select&gt;&lt;option&gt;Capa Verde&lt;/option&gt;&lt;/select&gt;\n&lt;select&gt;&lt;option&gt;Holiday&lt;/option&gt;&lt;/select&gt;\n&lt;select&gt;&lt;option&gt;Competition&lt;/option&gt;&lt;/select&gt;\n</code></pre>\n\n<p>Alternatively, you might have a range of buttons that stick once clicked. However it is going to be difficult then to convey the limitation of up to three options.</p>\n\n<p>If it is needed to mark each photograph individually and there is a limited number of categories you could display a list of categories (may be in several columns) right on top of the photograph (obviously you'd need to make sure the items a readable and indicate that they afford clicking) and let users select and de-select the tags by a single click. It is not very keyboard friendly, however its mostly impossible to use web without some sort of pointing device. In this case you'd use spacial positioning to connect categories and photographs.</p>\n\n<p>There are various options with two piles (available and selected) etc. </p>\n\n<p>Can you do at least a \"hallway\" usability testing?</p>\n\n<p>What is the actual task in user terms and who are the users?</p>\n" }, { "answer_id": 204157, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "<p>I suggest using two list boxes, one with the available ones, and one with the selected ones. Clicking or double-clicking an item in one of the lists should move the item into the other list. For convenience, I'd also include two \"Move\" buttons to do the same. This approach works surprisingly well with average users, in web applications as well as desktop applications.</p>\n" }, { "answer_id": 204459, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 1, "selected": false, "text": "<p>I hate multi-select, especially when the item can later be edited (if you click without holding CTRL, you lose what you already had selected). The best two options in my experience are:</p>\n\n<ol>\n<li>Having three separate select options (if you're limiting to three). The benefit here is that you're instructions of \"select up to three\" hold very well with the user experience and with a little JavaScript you can remove the first selection from the second dropdown thus removing confusion.</li>\n<li>Using check boxes. The benefit of check boxes is that it probably matches your database better, plus the information is pretty intuitive to the user and with a bit of thought of how you present the options the user experience can be pretty solid. Ex. grouping your check boxes into areas that make sense.</li>\n</ol>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11461/" ]
I know many people who use computers every day, who do not know how to select multiple items in a HTML select box/list. I don't want to use this control in my pages any more: ``` Please pick 3 options: <select name="categories" size="10" multiple="yes"> ``` So what user-friendly alternatives do you suggest? Perhaps have 10 tickboxes...or maybe just have each option in a coloured block which changes colour when they click to choose it? This gets messier when I consider my current list of 20 options might grow to 50 eventually. Whatever way I pick it's gonna be a pain to validate it (using Javascript), to make sure the person picks at least 1 item and not more than 3. It's not about detecting how many options they have picked, the problem is more about how to convey this to the user in a friendly way! **Edit:** I suppose I could use tags, like right here on stackoverflow, but I feel these are less appropriate if the users are non-technical (and half of them will be).
You could just use a manual list of items (Say as simple links), that have Javascript onclick behavior that deselects/selects manually. Basically by changing the css class between two values, and checking these css (Or some other attribute) during submission to determine the selections. This would allow the user to simply select an item by clicking, and deselect by clicking, rather than the standard Ctrl+Click requirement.