qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
142,252
<p>This code works (C# 3)</p> <pre><code>double d; if(d == (double)(int)d) ...; </code></pre> <ol> <li>Is there a better way to do this?</li> <li>For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)</li> </ol> <p><em>Note:</em> Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.</p>
[ { "answer_id": 142262, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "if (d == (int)d) {\n //...\n}\n" }, { "answer_id": 142263, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "d == Math.Floor(d)\n" }, { "answer_id": 142272, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "double d = 4.0;\nint i = 4;\n\nbool equal = d.CompareTo(i) == 0; // true\n" }, { "answer_id": 142287, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 3, "selected": false, "text": "d == Math.Floor(d + 0.00001);\n" }, { "answer_id": 142295, "author": "VoxPelli", "author_id": 20667, "author_profile": "https://Stackoverflow.com/users/20667", "pm_score": 3, "selected": false, "text": "if (d % 1 == 0) {\n //...\n}\n" }, { "answer_id": 142302, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 3, "selected": false, "text": "1.1 + 0.6 != 1.7 1.1 + 0.6 - 1.7 == 2.2204460492503131e-16" }, { "answer_id": 142309, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "if( Math.abs(d - Math.Floor(d + 0.001)) < 0.001)\n" }, { "answer_id": 142412, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 1, "selected": false, "text": "static void Main(string[] args)\n{\n const int precision = 10000;\n\n foreach (var d in new[] { 2, 2.9, 2.001, 1.999, 1.99999999, 2.00000001 })\n {\n if ((int) (d*precision + .5)%precision == 0)\n {\n Console.WriteLine(\"{0} is an int\", d);\n }\n }\n}\n 2 is an int\n1.99999999 is an int\n2.00000001 is an int\n" }, { "answer_id": 598312, "author": "Crash893", "author_id": 72136, "author_profile": "https://Stackoverflow.com/users/72136", "pm_score": 0, "selected": false, "text": " bool IsInt(double x)\n {\n try\n {\n int y = Int16.Parse(x.ToString());\n return true;\n }\n catch \n {\n return false;\n }\n }\n" }, { "answer_id": 13444282, "author": "ccook", "author_id": 51275, "author_profile": "https://Stackoverflow.com/users/51275", "pm_score": 0, "selected": false, "text": "Math.Abs(d - Math.Floor(d)) <= double.Epsilon\n // number of possible rounds\nconst int rounds = 1;\n\n// precision causes rounding up to double.Epsilon\ndouble d = double.Epsilon*.75;\n\n// due to the rounding this comparison fails\nConsole.WriteLine(d == Math.Floor(d));\n\n// this comparison succeeds by accounting for the rounding\nConsole.WriteLine(Math.Abs(d - Math.Floor(d)) <= rounds*double.Epsilon);\n\n// The difference is double.Epsilon, 4.940656458412465E-324\nConsole.WriteLine(Math.Abs(d - Math.Floor(d)).ToString(\"E15\"));\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
142,261
<p>Is there a way to get the C/C++ preprocessor or a template or such to mangle/hash the __FILE__ and __LINE__ and perhaps some other external input like a build-number into a single short number that can be quoted in logs or error messages?</p> <p>(The intention would be to be able to reverse it (to a list of candidates if its lossy) when needed when a customer quotes it in a bug report.)</p>
[ { "answer_id": 142328, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 0, "selected": false, "text": "typedef union ErrorCode {\n struct {\n unsigned int file: 15;\n unsigned int line: 12; /* Better than 5 bits, still not great\n Thanks commenters!! */\n unsigned int build: 5;\n } bits;\n unsigned int code;\n} ErrorCode;\n\nunsigned int buildErrorCodes(const char *file, int line, int build)\n{\n ErrorCode code;\n code.bits.line=line & ((1<<12) - 1);\n code.bits.build=build & ((1<< 5) - 1);\n code.bits.file=some_hash_function(file) & ((1<<15) - 1);\n\n return code.code;\n}\n buildErrorCodes(__FILE__, __LINE__, BUILD_CODE) \n" }, { "answer_id": 142338, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 3, "selected": true, "text": "__LINE__ __FILE__" }, { "answer_id": 142344, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "((*(int*)__FILE__ && 0xFFFF0000) | version << 8 | __LINE__ )\n" }, { "answer_id": 142369, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "__LINE__ __FILE__ template Serial(char[] file, int line)\n{\n prgams(msg, \n \"template Serial(char[] file : \\\"~file~\"\\\", int line : \"~line.stringof~\")\"\n \"{const int Serial = __LINE__;\");\n const int Serial = -1;\n}\n" }, { "answer_id": 142376, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "#ifdef DEBUG\n#define trace_here(version) printf(\"[%d]%s:%d {%d}\\n\", version, __FILE__, __LINE__, errloc++);\n#else\n#define trace_here(version) printf(\"{%lu}\\n\", version<<16|errloc++);\n#endif\n" }, { "answer_id": 168900, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": 0, "selected": false, "text": "extern const char g_DebugAnchor;\n#define FILE_STR_OFFSET (__FILE__ - &g_DebugAnchor)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15721/" ]
142,273
<p>We are beginning to go down the path of mobile browser support for an enterprise e-commerce webapp (Java/Servlet based). Of course there are many decisions to be made, but it seems to me the cornerstone is to be able to reliably detect mobile browsers, and make decisions on the content to be returned accordingly. Is there a standard way to make this determination (quickly) based on the http request, and ideally glean more information about the given browser and device making the request (screen size, html capabilities, etc?).</p> <p>I would also appreciate any supplemental information that would be of use from someone who has gone down this path of taking an existing large scale enterprise webapp and architect-ing out mobile browser support from the development side.</p> <p>[edit] I certainly understand the request header and the information about a database of standard user agents is a great help. For those talking about 'other' request header properties, if you could include similar standardized name / resource of values that would be a big help.</p> <p>[edit] Several users have proposed solutions that involve a call over the wire to some web service that will do the detection. While I'm sure this works, it is not a good solution for an enterprise e-commerce site for two reasons: 1) speed. A call over the wire for every page request to a third party would have huge performance implications. 2) dependency/legal. We'd tie our website response time and key functionality to their service, which is horrible for legal and risk reasons.</p>
[ { "answer_id": 1555338, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 2, "selected": false, "text": "HTTP_X_WAP_PROFILE HTTP_ACCEPT HTTP_USER_AGENT" }, { "answer_id": 7988637, "author": "ian", "author_id": 335555, "author_profile": "https://Stackoverflow.com/users/335555", "pm_score": 2, "selected": false, "text": "<VirtualHost (your-address-binding)> \n\n (your-virtual-host-configuration) \n\n RewriteEngine On \n RewriteCond %{QUERY_STRING} !ui=pc\n RewriteCond %{HTTP_COOKIE} !ui=pc\n RewriteCond %{HTTP_USER_AGENT} \"^.*(iphone|ipod|ipad|android|symbian|nokia|blackberry| rim |opera mini|opera mobi|windows ce|windows phone|up\\.browser|netfront|palm-|palm os|pre\\/|palmsource|avantogo|webos|hiptop|iris|kddi|kindle|lg-|lge|mot-|motorola|nintendo ds|nitro|playstation portable|samsung|sanyo|sprint|sonyericsson|symbian).*$\" [NC,OR]\n\n RewriteCond %{HTTP_USER_AGENT} \"^(alcatel|audiovox|bird|coral|cricket|docomo|edl|huawei|htc|gt-|lava|lct|lg|lynx|mobile|lenovo|maui|micromax|mot|myphone|nec|nexian|nook|pantech|pg|polaris|ppc|sch|sec|spice|tianyu|ustarcom|utstarcom|videocon|vodafone|winwap|zte).*$\" [NC] \n\n RewriteRule /(.*) http://bemoko.com/$1 [L]\n\n RewriteCond %{QUERY_STRING} \"ui=pc\"\n RewriteRule ^/ - [CO=ui:pc:(your-cookie-domain):86400:/]\n RewriteCond %{QUERY_STRING} \"ui=default\"\n RewriteRule ^/ - [CO=ui:default:(your-cookie-domain):86400:/]\n</VirtualHost>\n" }, { "answer_id": 27815018, "author": "Prathamesh Rasam", "author_id": 2853681, "author_profile": "https://Stackoverflow.com/users/2853681", "pm_score": 0, "selected": false, "text": "http://wurfl.sourceforge.net/wurfl_schema.php\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17123/" ]
142,282
<p>If I have a <code>UIView</code> (or <code>UIView</code> subclass) that is visible, how can I tell if it's currently being shown on the screen (as opposed to, for example, being in a section of a scroll view that is currently off-screen)?</p> <p>To maybe give you a better idea of what I mean, <code>UITableView</code> has a couple of methods for determining the set of currently visible cells. I'm looking for some code that can make a similar determination for any given <code>UIView</code>.</p>
[ { "answer_id": 145040, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 5, "selected": true, "text": "CGRectIntersectsRect() -[UIView convertRect:to(from)View] -[UIScrollView contentOffset]" }, { "answer_id": 11855952, "author": "Steven Hepting", "author_id": 98855, "author_profile": "https://Stackoverflow.com/users/98855", "pm_score": 0, "selected": false, "text": "CGRect viewFrame = self.view.frame;\nCGRect appFrame = [[UIScreen mainScreen] applicationFrame];\n\n// We may have received messages while this tableview is offscreen\nif (CGRectIntersectsRect(viewFrame, appFrame)) {\n // Do work here\n}\n" }, { "answer_id": 14206078, "author": "ecume des jours", "author_id": 1272234, "author_profile": "https://Stackoverflow.com/users/1272234", "pm_score": 1, "selected": false, "text": "if (myView.superview){\n //do something with myView because you can assume it is on the screen\n}\nelse {\n //myView is not in the view hierarchy\n}\n" }, { "answer_id": 16756678, "author": "aoakenfo", "author_id": 1152845, "author_profile": "https://Stackoverflow.com/users/1152845", "pm_score": 2, "selected": false, "text": "for(UIView* view in scrollView.subviews) {\n if([view isKindOfClass:[SomeView class]]) {\n\n // the parent of view of scrollView (which basically matches the application frame)\n CGRect f = self.view.frame; \n // adjust our frame to match the scroll view's content offset\n f.origin.y = _scrollView.contentOffset.y;\n\n CGRect r = [self.view convertRect:view.frame toView:self.view];\n\n if(CGRectIntersectsRect(f, r)) {\n // view is visible\n }\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544/" ]
142,317
<p>I have the following code that shows either a bug or a misunderstanding on my part.</p> <p>I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.</p> <p>Is this work as it should, or should I file a bug?</p> <pre> import java.io.*; import java.net.*; import java.util.*; public class OOS { public static void main(String[] args) throws Exception { Thread t1 = new Thread(new Runnable() { public void run() { try { ServerSocket ss = new ServerSocket(12344); Socket s= ss.accept(); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); List same = new ArrayList(); same.add(0); oos.writeObject(same); same.clear(); same.add(1); oos.writeObject(same); } catch(Exception e) { e.printStackTrace(); } } }); t1.start(); Socket s = new Socket("localhost", 12344); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); // outputs [0] as expected System.out.println(ois.readObject()); // outputs [0], but expected [1] System.out.println(ois.readObject()); System.exit(0); } } </pre>
[ { "answer_id": 142704, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 3, "selected": false, "text": "public void writeUnshared(Object obj);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21838/" ]
142,319
<p>This is a new gmail labs feature that lets you specify an RSS feed to grab random quotes from to append to your email signature. I'd like to use that to generate signatures programmatically based on parameters I pass in, the current time, etc. (For example, I have a script in pine that appends the current probabilities of McCain and Obama winning, fetched from intrade's API. See below.) But it seems gmail caches the contents of the URL you specify. Any way to control that or anyone know how often gmail looks at the URL?</p> <p>ADDED: Here's the program I'm using to test this. This file lives at <a href="http://kibotzer.com/sigs.php" rel="nofollow noreferrer">http://kibotzer.com/sigs.php</a>. The no-cache header idea, taken from here -- <a href="http://mapki.com/wiki/Dynamic_XML" rel="nofollow noreferrer">http://mapki.com/wiki/Dynamic_XML</a> -- seems to not help.</p> <pre><code>&lt;?php header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // HTTP/1.1 header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); // HTTP/1.0 header("Pragma: no-cache"); //XML Header header("content-type:text/xml"); ?&gt; &lt;!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd"&gt; &lt;rss version="0.91"&gt; &lt;channel&gt; &lt;title&gt;Dynamic Signatures&lt;/title&gt; &lt;link&gt;http://kibotzer.com&lt;/link&gt; &lt;description&gt;Blah blah&lt;/description&gt; &lt;language&gt;en-us&lt;/language&gt; &lt;pubDate&gt;26 Sep 2008 02:15:01 -0000&lt;/pubDate&gt; &lt;webMaster&gt;dreeves@kibotzer.com&lt;/webMaster&gt; &lt;managingEditor&gt;dreeves@kibotzer.com (Daniel Reeves)&lt;/managingEditor&gt; &lt;lastBuildDate&gt;26 Sep 2008 02:15:01 -0000&lt;/lastBuildDate&gt; &lt;image&gt; &lt;title&gt;Kibotzer Logo&lt;/title&gt; &lt;url&gt;http://kibotzer.com/logos/kibo-logo-1.gif&lt;/url&gt; &lt;link&gt;http://kibotzer.com/&lt;/link&gt; &lt;width&gt;120&lt;/width&gt; &lt;height&gt;60&lt;/height&gt; &lt;description&gt;Kibotzer&lt;/description&gt; &lt;/image&gt; &lt;item&gt; &lt;title&gt; Dynamic Signature 1 (&lt;?php echo gmdate("H:i:s"); ?&gt;) &lt;/title&gt; &lt;link&gt;http://kibotzer.com&lt;/link&gt; &lt;description&gt;This is the description for Signature 1 (&lt;?php echo gmdate("H:i:s"); ?&gt;) &lt;/description&gt; &lt;/item&gt; &lt;item&gt; &lt;title&gt; Dynamic Signature 2 (&lt;?php echo gmdate("H:i:s"); ?&gt;) &lt;/title&gt; &lt;link&gt;http://kibotzer.com&lt;/link&gt; &lt;description&gt;This is the description for Signature 2 (&lt;?php echo gmdate("H:i:s"); ?&gt;) &lt;/description&gt; &lt;/item&gt; &lt;/channel&gt; &lt;/rss&gt; </code></pre> <pre> -- http://ai.eecs.umich.edu/people/dreeves - - search://"Daniel Reeves" Latest probabilities from intrade... 42.1% McCain becomes president (last trade 18:07 FRI) 57.0% Obama becomes president (last trade 18:34 FRI) 17.6% US recession in 2008 (last trade 16:24 FRI) 16.1% Overt air strike against Iran in '08 (last trade 17:39 FRI) </pre>
[ { "answer_id": 142704, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 3, "selected": false, "text": "public void writeUnshared(Object obj);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
142,320
<p>I'm setting up our new Dev server, what is the easiest way to assign multiple IP addresses to Windows 2008 Server Network Adapter?</p> <p>I'm setting up our development machine, running IIS 7 and want to have the range between 192.168.1.200 - .254 available when I'm setting up a new website in IIS 7.</p>
[ { "answer_id": 142411, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 2, "selected": false, "text": "> netsh interface ipv4 add address \"Local Area Connection\" 192.168.1.201 255.255.255.0\n" }, { "answer_id": 142477, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": true, "text": "FOR /L %b IN (200,1,254) DO netsh interface ip add address \"your_adapter\" 192.168.1.%b 255.255.255.0\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
142,340
<p>I understand that Microsoft uses this template when versioning their products: Major.Minor.Build.Revision. </p> <p>Major is changed when the "developers" want to show that there is a big change in the software and backward compatibility cannot be assumed. Maybe a major rewrite of the code is done. </p> <p>Minor number represents a significant enhancement with the intention of backward compatibility. </p> <p>Build number is a small change, for example a recompilation of the same source. </p> <p>Revision is used to fix a security hole and should be fully interchangeable. Both Build and Revision are optional. This information is based on <a href="http://msdn.microsoft.com/en-us/library/system.version.aspx" rel="noreferrer">MSDN Version Class</a>. </p> <p>How do you version your projects and why do you version them this way?</p>
[ { "answer_id": 142425, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 0, "selected": false, "text": "001 002b3" }, { "answer_id": 142615, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 0, "selected": false, "text": "def serial(t)\n t = Time.now.utc if not t.instance_of?(Time)\n t.strftime(\"%Y\").to_i - 2000 + t.strftime(\"0.%m%d\").to_f\nend\n\nserial(Time.now) #=> 8.0926\nserial(Time.now.utc) #=> 8.0927\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4093/" ]
142,356
<p>What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?</p> <p>I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.</p> <pre><code>Type type = typeof(FooBar) BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; type.GetConstructors(flags) .Where(constructor =&gt; constructor.GetParameters().Length == 0) .First(); </code></pre>
[ { "answer_id": 142362, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 8, "selected": true, "text": "type.GetConstructor(Type.EmptyTypes)\n" }, { "answer_id": 142442, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 5, "selected": false, "text": "System.Type System.Activator.CreateInstance ConstructorInfo.Invoke" }, { "answer_id": 16045524, "author": "Jeff B", "author_id": 945456, "author_profile": "https://Stackoverflow.com/users/945456", "pm_score": 2, "selected": false, "text": "T NewItUp<T>() where T : new()\n{\n return new T();\n}\n" }, { "answer_id": 17552973, "author": "DaFlame", "author_id": 1112470, "author_profile": "https://Stackoverflow.com/users/1112470", "pm_score": 2, "selected": false, "text": "Activator.CreateInstance(Type) using System;\nusing System.Linq.Expressions;\n\npublic static class TypeHelper\n{\n public static Func<object> CreateDefaultConstructor(Type type)\n {\n NewExpression newExp = Expression.New(type);\n\n // Create a new lambda expression with the NewExpression as the body.\n var lambda = Expression.Lambda<Func<object>>(newExp);\n\n // Compile our new lambda expression.\n return lambda.Compile();\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12784/" ]
142,357
<p>What are the best JVM settings you have found for running Eclipse?</p>
[ { "answer_id": 142596, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 4, "selected": false, "text": "Workspace name (shown in window title) -showlocation" }, { "answer_id": 144349, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": false, "text": "-showlocation\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256M\n-framework\nplugins\\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar\n-vm\njdk1.6.0_10\\jre\\bin\\client\\jvm.dll\n-vmargs\n-Dosgi.requiredJavaVersion=1.5\n-Xms128m\n-Xmx384m\n-Xss2m\n-XX:PermSize=128m\n-XX:MaxPermSize=128m\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+UseConcMarkSweepGC\n-XX:+CMSIncrementalMode\n-XX:+CMSIncrementalPacing\n-XX:CompileThreshold=5\n-Dcom.sun.management.jmxremote\n C:\\[jdk1.6.0_0x path]\\bin\\jconsole.exe\n" }, { "answer_id": 366121, "author": "Gilberto Olimpio", "author_id": 45869, "author_profile": "https://Stackoverflow.com/users/45869", "pm_score": 3, "selected": false, "text": "-vm \n[your_jdk_folder]/jre/lib/i386/client/libjvm.so\n -vm\n[your_jdk_folder]/jre/lib/amd64/server/libjvm.so\n" }, { "answer_id": 1409590, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": false, "text": "startup launcher.library -startup\nplugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar\n--launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519\n -data\n../../workspace\n-showlocation\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n384m\n-startup\nplugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar\n--launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519\n-vm\n../../../../program files/Java/jdk1.6.0_17/jre/bin/client/jvm.dll\n-vmargs\n-Dosgi.requiredJavaVersion=1.5\n-Xms128m\n-Xmx384m\n-Xss4m\n-XX:PermSize=128m\n-XX:MaxPermSize=384m\n-XX:CompileThreshold=5\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+UseConcMarkSweepGC\n-XX:+CMSIncrementalMode\n-XX:+CMSIncrementalPacing\n-Dcom.sun.management.jmxremote\n-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/jv/eclipse/mydropins\n org.eclipse.equinox.p2.reconciler.dropins.directory --launcher.XXMaxPermSize\n384m\n-vmargs\n-XX:MaxPermSize=128m\n --launcher.XXMaxPermSize -XX:MaxPermSize= -XX:MaxPermSize=256m -XX:MaxPermSize -XX eclipse.ini 384m =384m m --launcher. --launcher.library --launcher.suppressErrors -vmargs -XX:MaxPermSize=384m" }, { "answer_id": 1838017, "author": "Kire Haglin", "author_id": 2049208, "author_profile": "https://Stackoverflow.com/users/2049208", "pm_score": 3, "selected": false, "text": "-showsplash\norg.eclipse.platform\n-vm\n C:\\jrmc-3.1.2-1.6.0\\bin\\javaw.exe \n-vmargs\n-XgcPrio:deterministic\n-XpauseTarget:20\n" }, { "answer_id": 3275659, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 9, "selected": true, "text": "-XX:MaxPermSize --launcher.XXMaxPermSize -data\n../../workspace\n-showlocation\n-showsplash\norg.eclipse.platform\n--launcher.defaultAction\nopenFile\n-vm\nC:/Prog/Java/jdk1.6.0_21/jre/bin/server/jvm.dll\n-vmargs\n-Dosgi.requiredJavaVersion=1.6\n-Declipse.p2.unsignedPolicy=allow\n-Xms128m\n-Xmx384m\n-Xss4m\n-XX:PermSize=128m\n-XX:MaxPermSize=384m\n-XX:CompileThreshold=5\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+CMSIncrementalPacing\n-XX:+UnlockExperimentalVMOptions\n-XX:+UseG1GC\n-XX:+UseFastAccessorMethods\n-Dcom.sun.management.jmxremote\n-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/Prog/Java/eclipse_addons\n p2.reconciler.dropins.directory eclipse.ini -XX:MaxPermSize --launcher.XXMaxPermSize -XX:MaxPermSize --launcher.XXMaxPermSize: isSunVM --launcher.XXMaxPermSize -XX:MaxPermSize eclipse.exe Sun Microsystems -XX:MaxPermSize org.eclipse.equinox.launcher plugins org.eclipse.equinox.launcher.[platform] eclipse_* -Dosgi.requiredJavaVersion = 1.6\n -XX:+UnlockExperimentalVMOptions\n-XX:+UseG1GC\n-XX:+UseFastAccessorMethods\n UseFastAccessorMethods --launcher.defaultAction\nopenFile\n - --launcher.openFile eclipse myFile.txt\n Open With Send To eclipse.ini -Declipse.p2.unsignedPolicy=allow\n eclipse.ini user.home user.home eclipse.ini -eclipse.keyring \nC:\\eclipse\\keyring.txt\n eclipse.ini -debug\n .options org.eclipse.equinox.p2.core/debug=true\norg.eclipse.equinox.p2.core/reconciler=true\n dropins/ Unzip eclipse-SDK-3.5M5-win32.zip to ..../eclipse\nUnzip mdt-ocl-SDK-1.3.0M5.zip to ..../eclipse/dropins/mdt-ocl-SDK-1.3.0M5\n Help / About / Plugin org.eclipse.ocl.doc org.eclipse.ocl Help / About / Configuration org.eclipse.ocl Help / Installation / Information Installed Software org.eclipse.ocl -DresolveReferencedLibrariesForContainers=true\n -Djava.net.preferIPv4Stack=true\n -Xincgc \n-XX:-DontCompileHugeMethods \n-XX:MaxInlineSize=1024 \n-XX:FreqInlineSize=1024 \n" }, { "answer_id": 3276567, "author": "Chris Dennett", "author_id": 87197, "author_profile": "https://Stackoverflow.com/users/87197", "pm_score": 2, "selected": false, "text": "-vm\nC:/Program Files (x86)/Java/jdk1.7.0/bin\n-startup\nplugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar\n--launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20100628\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256m\n--launcher.defaultAction\nopenFile\n-vmargs\n-server\n-Dosgi.requiredJavaVersion=1.7\n-Xmn100m\n-Xss1m\n-XgcPrio:deterministic\n-XpauseTarget:20\n-XX:PermSize=400M\n-XX:MaxPermSize=500M\n-XX:CompileThreshold=10\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+UnlockExperimentalVMOptions\n-XX:+DoEscapeAnalysis\n-XX:+UseG1GC\n-XX:+UseFastAccessorMethods\n-XX:+AggressiveOpts\n-Xms512m\n-Xmx512m\n" }, { "answer_id": 7523852, "author": "CurlyBrackets", "author_id": 559686, "author_profile": "https://Stackoverflow.com/users/559686", "pm_score": 3, "selected": false, "text": "-startup\nplugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar\n--launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502\n-product\norg.eclipse.epp.package.jee.product\n--launcher.defaultAction\nopenFile\n--launcher.XXMaxPermSize\n256M\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256m\n--launcher.defaultAction\nopenFile\n-vmargs\n-Dosgi.requiredJavaVersion=1.5\n-Xms1024m\n-Xmx4096m \n-XX:MaxPermSize=256m\n" }, { "answer_id": 7776565, "author": "A Null Pointer", "author_id": 371396, "author_profile": "https://Stackoverflow.com/users/371396", "pm_score": 3, "selected": false, "text": "-startup\n../../../plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar\n--launcher.library\n../../../plugins/org.eclipse.equinox.launcher.cocoa.macosx_1.1.100.v20110502\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256m\n--launcher.defaultAction\nopenFile\n-vmargs\n-Xms128m\n-Xmx512m\n-XX:MaxPermSize=256m\n-Xdock:icon=../Resources/Eclipse.icns\n-XstartOnFirstThread\n-Dorg.eclipse.swt.internal.carbon.smallFonts\n-Dcom.sun.management.jmxremote\n-Declipse.p2.unsignedPolicy=allow\n" }, { "answer_id": 7822155, "author": "Mikko Rantalainen", "author_id": 334451, "author_profile": "https://Stackoverflow.com/users/334451", "pm_score": 4, "selected": false, "text": "-nosplash\n-vmargs\n-Xincgc\n-Xss500k\n-Dosgi.requiredJavaVersion=1.6\n-Xms64m\n-Xmx200m\n-XX:NewSize=8m\n-XX:PermSize=80m\n-XX:MaxPermSize=150m\n-XX:MaxPermHeapExpansion=10m\n-XX:+UseConcMarkSweepGC\n-XX:CMSInitiatingOccupancyFraction=70\n-XX:+UseCMSInitiatingOccupancyOnly\n-XX:+UseParNewGC\n-XX:+CMSConcurrentMTEnabled\n-XX:ConcGCThreads=2\n-XX:ParallelGCThreads=2\n-XX:+CMSIncrementalPacing\n-XX:CMSIncrementalDutyCycleMin=0\n-XX:CMSIncrementalDutyCycle=5\n-XX:GCTimeRatio=49\n-XX:MaxGCPauseMillis=20\n-XX:GCPauseIntervalMillis=1000\n-XX:+UseCMSCompactAtFullCollection\n-XX:+CMSClassUnloadingEnabled\n-XX:+DoEscapeAnalysis\n-XX:+UseCompressedOops\n-XX:+AggressiveOpts\n-XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15352/" ]
142,391
<p>I am making extensive use of <code>boost:shared_ptr</code> in my code. In fact, most of the objects that are allocated on the heap are held by a <code>shared_ptr</code>. Unfortunately this means that I can't pass <code>this</code> into any function that takes a <code>shared_ptr</code>. Consider this code:</p> <pre><code>void bar(boost::shared_ptr&lt;Foo&gt; pFoo) { ... } void Foo::someFunction() { bar(this); } </code></pre> <p>There are two problems here. First, this won't compile because the T* constructor for <code>shared_ptr</code> is explicit. Second, if I force it to build with <code>bar(boost::shared_ptr&lt;Foo&gt;(this))</code> I will have created a second shared pointer to my object that will eventually lead to a double-delete.</p> <p>This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?</p>
[ { "answer_id": 142401, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 8, "selected": true, "text": "#include <boost/enable_shared_from_this.hpp>\n\nclass Y: public boost::enable_shared_from_this<Y>\n{\npublic:\n\n shared_ptr<Y> f()\n {\n return shared_from_this();\n }\n}\n\nint main()\n{\n shared_ptr<Y> p(new Y);\n shared_ptr<Y> q = p->f();\n assert(p == q);\n assert(!(p < q || q < p)); // p and q must share ownership\n}\n" }, { "answer_id": 142440, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "\nvoid bar(Foo &foo)\n{\n // ...\n}\n" }, { "answer_id": 14030930, "author": "Johan Lundberg", "author_id": 1149664, "author_profile": "https://Stackoverflow.com/users/1149664", "pm_score": 3, "selected": false, "text": "shared_ptr enable_shared_from_this struct Good: std::enable_shared_from_this<Good>{\n std::shared_ptr<Good> getptr() {\n return shared_from_this();\n }\n};\n std::shared_ptr<Good> gp1(new Good);\nstd::shared_ptr<Good> gp2 = gp1->getptr();\nstd::cout << \"gp2.use_count() = \" << gp2.use_count() << '\\n';\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031/" ]
142,400
<p>I've had a hard time finding good ways of taking a time format and easily determining if it's valid then producing a resulting element that has some formatting using XSLT 1.0.</p> <p>Given the following xml:</p> <pre><code>&lt;root&gt; &lt;srcTime&gt;2300&lt;/srcTime&gt; &lt;/root&gt; </code></pre> <p>It would be great to produce the resulting xml:</p> <pre><code>&lt;root&gt; &lt;dstTime&gt;23:00&lt;/dstTime&gt; &lt;/root&gt; </code></pre> <p>However, if the source xml contains an invalid 24 hour time format, the resulting <em>dstTime</em> element should be blank.</p> <p>For example, when the invalid source xml is the following:</p> <pre><code>&lt;root&gt; &lt;srcTime&gt;NOON&lt;/srcTime&gt; &lt;/root&gt; </code></pre> <p>The resulting xml should be:</p> <pre><code>&lt;root&gt; &lt;dstTime&gt;&lt;/dstTime&gt; &lt;/root&gt; </code></pre> <p>The question is, what's the <strong>best XSLT 1.0</strong> fragment that could be written to produce the desired results? The hope would be to keep it quite simple and not have to parse the every piece of the time (i.e. pattern matching would be sweet if possible).</p>
[ { "answer_id": 144536, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "<srcTime>23:00</srcTime> <dstTime>\n <xsl:if test=\"string-length(srcTime) = 4 or\n string-length(srcTime) = 5\">\n <xsl:variable name=\"hour\" select=\"substring(srcTime, 1, 2)\" />\n <xsl:if test=\"$hour >= 0 and 24 > $hour\">\n <xsl:variable name=\"minute\">\n <xsl:choose>\n <xsl:when test=\"string-length(srcTime) = 5 and\n substring(srcTime, 3, 1) = ':'\">\n <xsl:value-of select=\"substring(srcTime, 4, 2)\" />\n </xsl:when>\n <xsl:when test=\"string-length(srcTime) = 4\">\n <xsl:value-of select=\"substring(srcTime, 3, 2)\" />\n </xsl:when>\n </xsl:choose>\n </xsl:variable>\n <xsl:if test=\"$minute >= 0 and 60 > $minute\">\n <xsl:value-of select=\"concat($hour, ':', $minute)\" />\n </xsl:if>\n </xsl:if>\n </xsl:if>\n</dstTime>\n <dstTime>\n <xsl:if test=\"string-length(srcTime) = 4\">\n <xsl:variable name=\"hour\" select=\"substring(srcTime, 1, 2)\" />\n <xsl:if test=\"$hour >= 0 and 24 > $hour\">\n <xsl:variable name=\"minute\" select=\"substring(srcTime, 3, 2)\" />\n <xsl:if test=\"$minute >= 0 and 60 > $minute\">\n <xsl:value-of select=\"concat($hour, ':', $minute)\" />\n </xsl:if>\n </xsl:if>\n </xsl:if>\n</dstTime>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ]
142,407
<p>I am testing a Ruby Rails website and wanted to get started with Unit and Functional testing.</p>
[ { "answer_id": 142540, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 3, "selected": false, "text": "describe \"hello_world\"\n it \"should say hello to the world\" do\n # RSpec comes with its own mock-object framework built in,\n # though it lets you use others if you prefer\n world = mock(\"World\", :population => 6e9)\n world.should_receive(:hello)\n hello_world(world)\n end\nend\n Story: Commenting on articles\n\n As a visitor to the blog\n I want to post comments on articles\n So that I can have my 15 minutes of fame\n\n Scenario: Post a new comment\n\n Given I am viewing an article\n When I add a comment \"Me too!\"\n And I fill in the CAPTCHA correctly\n Then I should see a comment \"Me too!\"\n" }, { "answer_id": 142544, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "Test::Unit" }, { "answer_id": 143353, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 2, "selected": false, "text": "RSpec Test::Unit" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22883/" ]
142,417
<p>Recently, <a href="https://stackoverflow.com/users/5200/lee-baldwin">Lee Baldwin</a> showed how to write a <a href="https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function#141689">generic, variable argument memoize function</a>. I thought it would be better to return a simpler function where only one parameter is required. Here is my total bogus attempt:</p> <pre><code>local function memoize(f) local cache = {} if select('#', ...) == 1 then return function (x) if cache[x] then return cache[x] else local y = f(x) cache[x] = y return y end end else return function (...) local al = varg_tostring(...) if cache[al] then return cache[al] else local y = f(...) cache[al] = y return y end end end end </code></pre> <p>Obviously, <code>select('#', ...)</code> fails in this context and wouldn't really do what I want anyway. Is there any way to tell inside <strong>memoize</strong> how many arguments <strong>f</strong> expects? </p> <hr> <p>"No" is a fine answer if you know for sure. It's not a big deal to use two separate <strong>memoize</strong> functions.</p>
[ { "answer_id": 24216007, "author": "Tom Blodget", "author_id": 2226988, "author_profile": "https://Stackoverflow.com/users/2226988", "pm_score": 2, "selected": false, "text": "debug.getlocal ... debug.sethook assert(_VERSION==\"Lua 5.2\", \"Must be compatible with Lua 5.2\")\n local function getlocals(l)\n local i = 0\n local direction = 1\n return function ()\n i = i + direction\n local k,v = debug.getlocal(l,i)\n if (direction == 1 and (k == nil or k.sub(k,1,1) == '(')) then \n i = -1 \n direction = -1 \n k,v = debug.getlocal(l,i) \n end\n return k,v\n end\nend\n local function dumpsig(f)\n assert(type(f) == 'function', \n \"bad argument #1 to 'dumpsig' (function expected)\")\n local p = {}\n pcall (function() \n local oldhook\n local hook = function(event, line)\n for k,v in getlocals(3) do \n if k == \"(*vararg)\" then \n table.insert(p,\"...\") \n break\n end \n table.insert(p,k) end\n debug.sethook(oldhook)\n error('aborting the call')\n end\n oldhook = debug.sethook(hook, \"c\")\n -- To test for vararg must pass a least one vararg parameter\n f(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)\n end)\n return \"function(\"..table.concat(p,\",\")..\")\" \nend\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
142,420
<p>I have a method lets say:</p> <pre><code>private static String drawCellValue( int maxCellLength, String cellValue, String align) { } </code></pre> <p>and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?</p> <p>Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.</p> <p>Any ideas?</p>
[ { "answer_id": 142428, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 7, "selected": true, "text": "private enum Alignment { LEFT, RIGHT }; \nString drawCellValue (int maxCellLength, String cellValue, Alignment align){\n if (align == Alignment.LEFT)\n {\n //Process it...\n }\n}\n" }, { "answer_id": 142435, "author": "Michael Bobick", "author_id": 3425, "author_profile": "https://Stackoverflow.com/users/3425", "pm_score": 1, "selected": false, "text": "enum Alignment {\n LEFT,\n RIGHT\n}\n" }, { "answer_id": 144571, "author": "Joshua DeWald", "author_id": 22752, "author_profile": "https://Stackoverflow.com/users/22752", "pm_score": 4, "selected": false, "text": "switch (align) {\n case LEFT: { \n // do stuff\n break;\n }\n case RIGHT: {\n // do stuff\n break;\n }\n default: { //added TOP_RIGHT but forgot about it?\n throw new IllegalArgumentException(\"Can't yet handle \" + align);\n\n }\n}\n" }, { "answer_id": 263230, "author": "Zamir", "author_id": 21274, "author_profile": "https://Stackoverflow.com/users/21274", "pm_score": 3, "selected": false, "text": "private enum Alignment { LEFT, RIGHT;\n\nvoid process() {\n//Process it...\n} \n}; \nString drawCellValue (int maxCellLength, String cellValue, Alignment align){\n align.process();\n}\n String process(...) {\n//Process it...\n} \n" }, { "answer_id": 41705363, "author": "Alex Pawelko", "author_id": 7297891, "author_profile": "https://Stackoverflow.com/users/7297891", "pm_score": 1, "selected": false, "text": "public enum Alignment { LEFT, RIGHT }\nprivate static String drawCellValue(\nint maxCellLength, String cellValue, Alignment align) {}\n switch(align) {\ncase LEFT: //something\ncase RIGHT: //something\ndefault: //something\n}\n\nif(align == Alignment.RIGHT) { /*code*/}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6618/" ]
142,431
<p>I'm setting up a server to offer JIRA and SVN. I figure, I'll use LDAP to keep the identity management simple. </p> <p>So, before I write one.... is there a good app out there to let users change their ldap password? I want something that lets a user authenticate with ldap and update their password. A form with username, old password, new password and verification would be enough. </p> <p>I can write my own, but it seems silly to do so if there's already a good app out there that handles this....</p> <p>Thanks for the help.</p>
[ { "answer_id": 142428, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 7, "selected": true, "text": "private enum Alignment { LEFT, RIGHT }; \nString drawCellValue (int maxCellLength, String cellValue, Alignment align){\n if (align == Alignment.LEFT)\n {\n //Process it...\n }\n}\n" }, { "answer_id": 142435, "author": "Michael Bobick", "author_id": 3425, "author_profile": "https://Stackoverflow.com/users/3425", "pm_score": 1, "selected": false, "text": "enum Alignment {\n LEFT,\n RIGHT\n}\n" }, { "answer_id": 144571, "author": "Joshua DeWald", "author_id": 22752, "author_profile": "https://Stackoverflow.com/users/22752", "pm_score": 4, "selected": false, "text": "switch (align) {\n case LEFT: { \n // do stuff\n break;\n }\n case RIGHT: {\n // do stuff\n break;\n }\n default: { //added TOP_RIGHT but forgot about it?\n throw new IllegalArgumentException(\"Can't yet handle \" + align);\n\n }\n}\n" }, { "answer_id": 263230, "author": "Zamir", "author_id": 21274, "author_profile": "https://Stackoverflow.com/users/21274", "pm_score": 3, "selected": false, "text": "private enum Alignment { LEFT, RIGHT;\n\nvoid process() {\n//Process it...\n} \n}; \nString drawCellValue (int maxCellLength, String cellValue, Alignment align){\n align.process();\n}\n String process(...) {\n//Process it...\n} \n" }, { "answer_id": 41705363, "author": "Alex Pawelko", "author_id": 7297891, "author_profile": "https://Stackoverflow.com/users/7297891", "pm_score": 1, "selected": false, "text": "public enum Alignment { LEFT, RIGHT }\nprivate static String drawCellValue(\nint maxCellLength, String cellValue, Alignment align) {}\n switch(align) {\ncase LEFT: //something\ncase RIGHT: //something\ndefault: //something\n}\n\nif(align == Alignment.RIGHT) { /*code*/}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9950/" ]
142,452
<p>There are many scenarios where it would be useful to call a Win32 function or some other DLL from a PowerShell script. to Given the following function signature:</p> <pre><code>bool MyFunction( char* buffer, int* bufferSize ) </code></pre> <p>I hear there is something that makes this easier in PowerShell CTP 2, but I'm curious how this is <strong>best done in PowerShell 1.0</strong>. The fact that the function needing to be called <strong><em>is using pointers</em></strong> could affect the solution (yet I don't really know).</p> <p>So the question is what's the best way to write a PowerShell script that can call an exported Win32 function like the one above?</p> <p><strong>Remember for PowerShell 1.0.</strong></p>
[ { "answer_id": 142516, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 3, "selected": false, "text": "PS C:\\> Invoke-Win32 \"msvcrt.dll\" ([Int32]) \"puts\" ([String]) \"Test\"\nTest\n0\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ]
142,478
<p>In handling a WM_GETMINMAXINFO message, I attempt to alter the parameter MINMAXINFO structure by changing the ptMaxSize. It doesn't seem to have any effect. When I receive the WM_SIZE message, I always get the same value, no matter whether I increase or decrease the ptMaxSize in the WM_GETMINMAXINFO.</p>
[ { "answer_id": 61550191, "author": "metablaster", "author_id": 12091999, "author_profile": "https://Stackoverflow.com/users/12091999", "pm_score": 0, "selected": false, "text": "WS_THICKFRAME WS_CAPTION WM_GETMINMAXINFO" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965047/" ]
142,481
<p>Is there such a thing as unit test generation? If so...</p> <p>...does it work well? </p> <p>...What are the auto generation solutions that are available for .NET?</p> <p>...are there examples of using a technology like this?</p> <p>...is this only good for certain types of applications, or could it be used to replace all manually written unit testing?</p>
[ { "answer_id": 40569949, "author": "johng", "author_id": 2390625, "author_profile": "https://Stackoverflow.com/users/2390625", "pm_score": 2, "selected": false, "text": "ErrorUnit MSTest NUnit Visual Studio" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ]
142,504
<h3>What are some methods of utilising Eclipse for Dependency Management?</h3>
[ { "answer_id": 203256, "author": "Ken Liu", "author_id": 25688, "author_profile": "https://Stackoverflow.com/users/25688", "pm_score": 2, "selected": false, "text": "mvn eclipse:eclipse" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ]
142,508
<p>I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:</p> <pre><code>#ifdef OSisWindows // do Windows-specific stuff #else // do Unix-specific stuff #endif </code></pre> <p>Is there a way to do this? Is there a better way to do the same thing?</p>
[ { "answer_id": 142522, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "__WIN32__ touch foo.h; gcc -dM foo.h" }, { "answer_id": 142524, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "#define OSsymbol #ifdef OSsymbol #define" }, { "answer_id": 142529, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 3, "selected": false, "text": "pipe()" }, { "answer_id": 142539, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "_WIN32 _WIN64 __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__" }, { "answer_id": 142563, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "-D MACRO gcc -D Windows\ngcc -D UNIX\n #if defined(Windows)\n// do some cool Windows stuff\n#elif defined(UNIX)\n// do some cool Unix stuff\n#else\n# error Unsupported operating system\n#endif\n" }, { "answer_id": 647640, "author": "qwer", "author_id": 78243, "author_profile": "https://Stackoverflow.com/users/78243", "pm_score": 6, "selected": false, "text": "gcc -dM -E - <NUL:\n gcc -dM -E - </dev/null\n WIN32 _WIN32 __WIN32 __WIN32__ __MINGW32__ WINNT __WINNT __WINNT__ _X86_ i386 __i386\n unix __unix__ __unix\n" }, { "answer_id": 8249232, "author": "Lambda Fairy", "author_id": 617159, "author_profile": "https://Stackoverflow.com/users/617159", "pm_score": 10, "selected": true, "text": "_WIN32 _WIN64 __CYGWIN__ unix __unix __unix__ __APPLE__ __MACH__ __linux__ linux __linux __FreeBSD__ __ANDROID__" }, { "answer_id": 21940094, "author": "Arjun Sreedharan", "author_id": 997813, "author_profile": "https://Stackoverflow.com/users/997813", "pm_score": 3, "selected": false, "text": "#ifdef _WIN32\n// do something for windows like include <windows.h>\n#elif defined __unix__\n// do something for unix like include <unistd.h>\n#elif defined __APPLE__\n// do something for mac\n#endif\n" }, { "answer_id": 41896671, "author": "anakod", "author_id": 1315814, "author_profile": "https://Stackoverflow.com/users/1315814", "pm_score": 3, "selected": false, "text": "_WIN32 #if defined(_WIN32) || defined(__CYGWIN__)\n // Windows (x86 or x64)\n // ...\n#elif defined(__linux__)\n // Linux\n // ...\n#elif defined(__APPLE__) && defined(__MACH__)\n // Mac OS\n // ...\n#elif defined(unix) || defined(__unix__) || defined(__unix)\n // Unix like OS\n // ...\n#else\n #error Unknown environment!\n#endif\n" }, { "answer_id": 42040445, "author": "PADYMKO", "author_id": 6003870, "author_profile": "https://Stackoverflow.com/users/6003870", "pm_score": 6, "selected": false, "text": "#include <stdio.h>\n\n/**\n * Determination a platform of an operation system\n * Fully supported supported only GNU GCC/G++, partially on Clang/LLVM\n */\n\n#if defined(_WIN32)\n #define PLATFORM_NAME \"windows\" // Windows\n#elif defined(_WIN64)\n #define PLATFORM_NAME \"windows\" // Windows\n#elif defined(__CYGWIN__) && !defined(_WIN32)\n #define PLATFORM_NAME \"windows\" // Windows (Cygwin POSIX under Microsoft Window)\n#elif defined(__ANDROID__)\n #define PLATFORM_NAME \"android\" // Android (implies Linux, so it must come first)\n#elif defined(__linux__)\n #define PLATFORM_NAME \"linux\" // Debian, Ubuntu, Gentoo, Fedora, openSUSE, RedHat, Centos and other\n#elif defined(__unix__) || !defined(__APPLE__) && defined(__MACH__)\n #include <sys/param.h>\n #if defined(BSD)\n #define PLATFORM_NAME \"bsd\" // FreeBSD, NetBSD, OpenBSD, DragonFly BSD\n #endif\n#elif defined(__hpux)\n #define PLATFORM_NAME \"hp-ux\" // HP-UX\n#elif defined(_AIX)\n #define PLATFORM_NAME \"aix\" // IBM AIX\n#elif defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin)\n #include <TargetConditionals.h>\n #if TARGET_IPHONE_SIMULATOR == 1\n #define PLATFORM_NAME \"ios\" // Apple iOS\n #elif TARGET_OS_IPHONE == 1\n #define PLATFORM_NAME \"ios\" // Apple iOS\n #elif TARGET_OS_MAC == 1\n #define PLATFORM_NAME \"osx\" // Apple OSX\n #endif\n#elif defined(__sun) && defined(__SVR4)\n #define PLATFORM_NAME \"solaris\" // Oracle Solaris, Open Indiana\n#else\n #define PLATFORM_NAME NULL\n#endif\n\n// Return a name of platform, if determined, otherwise - an empty string\nconst char *get_platform_name() {\n return (PLATFORM_NAME == NULL) ? \"\" : PLATFORM_NAME;\n}\n\nint main(int argc, char *argv[]) {\n puts(get_platform_name());\n return 0;\n}\n" }, { "answer_id": 42686138, "author": "MD XF", "author_id": 7659995, "author_profile": "https://Stackoverflow.com/users/7659995", "pm_score": 2, "selected": false, "text": "libportable" }, { "answer_id": 48196597, "author": "Haseeb Mir", "author_id": 6219626, "author_profile": "https://Stackoverflow.com/users/6219626", "pm_score": 0, "selected": false, "text": "#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)\n #error Windows_OS\n#elif defined(__linux__)\n #error Linux_OS\n#elif defined(__APPLE__) && defined(__MACH__)\n #error Mach_OS\n#elif defined(unix) || defined(__unix__) || defined(__unix)\n #error Unix_OS\n#else\n #error Unknown_OS\n#endif\n\n#include <stdio.h>\nint main(void)\n{\n return 0;\n}\n" }, { "answer_id": 52768132, "author": "TadejP", "author_id": 4292145, "author_profile": "https://Stackoverflow.com/users/4292145", "pm_score": 1, "selected": false, "text": "__HAIKU__" }, { "answer_id": 52992284, "author": "phuclv", "author_id": 995714, "author_profile": "https://Stackoverflow.com/users/995714", "pm_score": 2, "selected": false, "text": "Boost.Predef BOOST_OS_* #include <boost/predef.h>\n// or just include the necessary header\n// #include <boost/predef/os.h>\n\n#if BOOST_OS_WINDOWS\n#elif BOOST_OS_ANDROID\n#elif BOOST_OS_LINUX\n#elif BOOST_OS_BSD\n#elif BOOST_OS_AIX\n#elif BOOST_OS_HAIKU\n...\n#endif\n BOOST_OS" }, { "answer_id": 53267287, "author": "Abraham Calf", "author_id": 7602110, "author_profile": "https://Stackoverflow.com/users/7602110", "pm_score": -1, "selected": false, "text": "$ clib install abranhe/os.c\n #include <stdio.h>\n#include \"os.h\"\n\nint main()\n{\n printf(\"%s\\n\", operating_system());\n // macOS\n return 0;\n}\n char*" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10601/" ]
142,527
<p>Is it possible to highlight text inside of a textarea using javascript? Either changing the background of just a portion of the text area or making a portion of the text <em>selected</em>?</p>
[ { "answer_id": 7599199, "author": "Julien L", "author_id": 690236, "author_profile": "https://Stackoverflow.com/users/690236", "pm_score": 4, "selected": false, "text": "<html>\n <head>\n <title></title>\n <!-- Load jQuery -->\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\"></script>\n <!-- The javascript xontaining the plugin and the code to init the plugin -->\n <script type=\"text/javascript\">\n $(function() {\n // let's init the plugin, that we called \"highlight\".\n // We will highlight the words \"hello\" and \"world\", \n // and set the input area to a widht and height of 500 and 250 respectively.\n $(\"#container\").highlight({\n words: [\"hello\",\"world\"],\n width: 500,\n height: 250\n });\n });\n\n // the plugin that would do the trick\n (function($){\n $.fn.extend({\n highlight: function() {\n // the main class\n var pluginClass = function() {};\n // init the class\n // Bootloader\n pluginClass.prototype.__init = function (element) {\n try {\n this.element = element;\n } catch (err) {\n this.error(err);\n }\n };\n // centralized error handler\n pluginClass.prototype.error = function (e) {\n // manage error and exceptions here\n //console.info(\"error!\",e);\n };\n // Centralized routing function\n pluginClass.prototype.execute = function (fn, options) {\n try {\n options = $.extend({},options);\n if (typeof(this[fn]) == \"function\") {\n var output = this[fn].apply(this, [options]);\n } else {\n this.error(\"undefined_function\");\n }\n } catch (err) {\n this.error(err);\n }\n };\n // **********************\n // Plugin Class starts here\n // **********************\n // init the component\n pluginClass.prototype.init = function (options) {\n try {\n // the element's reference ( $(\"#container\") ) is stored into \"this.element\"\n var scope = this;\n this.options = options;\n\n // just find the different elements we'll need\n this.highlighterContainer = this.element.find('#highlighterContainer');\n this.inputContainer = this.element.find('#inputContainer');\n this.textarea = this.inputContainer.find('textarea');\n this.highlighter = this.highlighterContainer.find('#highlighter');\n\n // apply the css\n this.element.css('position','relative');\n\n // place both the highlight container and the textarea container\n // on the same coordonate to superpose them.\n this.highlighterContainer.css({\n 'position': 'absolute',\n 'left': '0',\n 'top': '0',\n 'border': '1px dashed #ff0000',\n 'width': this.options.width,\n 'height': this.options.height,\n 'cursor': 'text'\n });\n this.inputContainer.css({\n 'position': 'absolute',\n 'left': '0',\n 'top': '0',\n 'border': '1px solid #000000'\n });\n // now let's make sure the highlit div and the textarea will superpose,\n // by applying the same font size and stuffs.\n // the highlighter must have a white text so it will be invisible\n this.highlighter.css({\n\n 'padding': '7px',\n 'color': '#eeeeee',\n 'background-color': '#ffffff',\n 'margin': '0px',\n 'font-size': '11px',\n 'font-family': '\"lucida grande\",tahoma,verdana,arial,sans-serif'\n });\n // the textarea must have a transparent background so we can see the highlight div behind it\n this.textarea.css({\n 'background-color': 'transparent',\n 'padding': '5px',\n 'margin': '0px',\n 'font-size': '11px',\n 'width': this.options.width,\n 'height': this.options.height,\n 'font-family': '\"lucida grande\",tahoma,verdana,arial,sans-serif'\n });\n\n // apply the hooks\n this.highlighterContainer.bind('click', function() {\n scope.textarea.focus();\n });\n this.textarea.bind('keyup', function() {\n // when we type in the textarea, \n // we want the text to be processed and re-injected into the div behind it.\n scope.applyText($(this).val());\n });\n } catch (err) {\n this.error(err);\n }\n return true;\n };\n pluginClass.prototype.applyText = function (text) {\n try {\n var scope = this;\n\n // parse the text:\n // replace all the line braks by <br/>, and all the double spaces by the html version &nbsp;\n text = this.replaceAll(text,'\\n','<br/>');\n text = this.replaceAll(text,' ','&nbsp;&nbsp;');\n\n // replace the words by a highlighted version of the words\n for (var i=0;i<this.options.words.length;i++) {\n text = this.replaceAll(text,this.options.words[i],'<span style=\"background-color: #D8DFEA;\">'+this.options.words[i]+'</span>');\n }\n\n // re-inject the processed text into the div\n this.highlighter.html(text);\n\n } catch (err) {\n this.error(err);\n }\n return true;\n };\n // \"replace all\" function\n pluginClass.prototype.replaceAll = function(txt, replace, with_this) {\n return txt.replace(new RegExp(replace, 'g'),with_this);\n }\n\n // don't worry about this part, it's just the required code for the plugin to hadle the methods and stuffs. Not relevant here.\n //**********************\n // process\n var fn;\n var options;\n if (arguments.length == 0) {\n fn = \"init\";\n options = {};\n } else if (arguments.length == 1 && typeof(arguments[0]) == 'object') {\n fn = \"init\";\n options = $.extend({},arguments[0]);\n } else {\n fn = arguments[0];\n options = $.extend({},arguments[1]);\n }\n\n $.each(this, function(idx, item) {\n // if the component is not yet existing, create it.\n if ($(item).data('highlightPlugin') == null) {\n $(item).data('highlightPlugin', new pluginClass());\n $(item).data('highlightPlugin').__init($(item));\n }\n $(item).data('highlightPlugin').execute(fn, options);\n });\n return this;\n }\n });\n\n })(jQuery);\n\n\n </script>\n </head>\n <body>\n\n <div id=\"container\">\n <div id=\"highlighterContainer\">\n <div id=\"highlighter\">\n\n </div>\n </div>\n <div id=\"inputContainer\">\n <textarea cols=\"30\" rows=\"10\">\n\n </textarea>\n </div>\n </div>\n\n </body>\n</html>\n" }, { "answer_id": 10562853, "author": "mhausi", "author_id": 1390913, "author_profile": "https://Stackoverflow.com/users/1390913", "pm_score": 0, "selected": false, "text": "<html>\n <head>\n <title></title>\n <!-- Load jQuery -->\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\"></script>\n <!-- The javascript xontaining the plugin and the code to init the plugin -->\n <script type=\"text/javascript\">\n $(function() {\n // let's init the plugin, that we called \"highlight\".\n // We will highlight the words \"hello\" and \"world\", \n // and set the input area to a widht and height of 500 and 250 respectively.\n $(\"#container0\").highlight({\n words: [[\"hello\",\"hello\"],[\"world\",\"world\"],[\"(\\\\[b])(.+?)(\\\\[/b])\",\"$1$2$3\"]],\n width: 500,\n height: 125,\n count:0\n });\n $(\"#container1\").highlight({\n words: [[\"hello\",\"hello\"],[\"world\",\"world\"],[\"(\\\\[b])(.+?)(\\\\[/b])\",\"$1$2$3\"]],\n width: 500,\n height: 125,\n count: 1\n });\n });\n\n // the plugin that would do the trick\n (function($){\n $.fn.extend({\n highlight: function() {\n // the main class\n var pluginClass = function() {};\n // init the class\n // Bootloader\n pluginClass.prototype.__init = function (element) {\n try {\n this.element = element;\n } catch (err) {\n this.error(err);\n }\n };\n // centralized error handler\n pluginClass.prototype.error = function (e) {\n // manage error and exceptions here\n //console.info(\"error!\",e);\n };\n // Centralized routing function\n pluginClass.prototype.execute = function (fn, options) {\n try {\n options = $.extend({},options);\n if (typeof(this[fn]) == \"function\") {\n var output = this[fn].apply(this, [options]);\n } else {\n this.error(\"undefined_function\");\n }\n } catch (err) {\n this.error(err);\n }\n };\n // **********************\n // Plugin Class starts here\n // **********************\n // init the component\n pluginClass.prototype.init = function (options) {\n try {\n // the element's reference ( $(\"#container\") ) is stored into \"this.element\"\n var scope = this;\n this.options = options;\n\n // just find the different elements we'll need\n\n this.highlighterContainer = this.element.find('#highlighterContainer'+this.options.count);\n this.inputContainer = this.element.find('#inputContainer'+this.options.count);\n this.textarea = this.inputContainer.find('textarea');\n this.highlighter = this.highlighterContainer.find('#highlighter'+this.options.count);\n\n // apply the css\n this.element.css({'position':'relative',\n 'overflow':'auto',\n 'background':'none repeat scroll 0 0 #FFFFFF',\n 'height':this.options.height+2,\n 'width':this.options.width+19,\n 'border':'1px solid'\n });\n\n // place both the highlight container and the textarea container\n // on the same coordonate to superpose them.\n this.highlighterContainer.css({\n 'position': 'absolute',\n 'left': '0',\n 'top': '0',\n 'border': '1px dashed #ff0000', \n 'width': this.options.width,\n 'height': this.options.height,\n 'cursor': 'text',\n 'z-index': '1'\n });\n this.inputContainer.css({\n 'position': 'absolute',\n 'left': '0',\n 'top': '0',\n 'border': '0px solid #000000',\n 'z-index': '2',\n 'background': 'none repeat scroll 0 0 transparent'\n });\n // now let's make sure the highlit div and the textarea will superpose,\n // by applying the same font size and stuffs.\n // the highlighter must have a white text so it will be invisible\n var isWebKit = navigator.userAgent.indexOf(\"WebKit\") > -1,\n isOpera = navigator.userAgent.indexOf(\"Opera\") > -1,\nisIE /*@cc_on = true @*/,\nisIE6 = isIE && !window.XMLHttpRequest; // Despite the variable name, this means if IE lower than v7\n\nif (isIE || isOpera){\nvar padding = '6px 5px';\n}\nelse {\nvar padding = '5px 6px';\n}\n this.highlighter.css({\n 'padding': padding,\n 'color': '#eeeeee',\n 'background-color': '#ffffff',\n 'margin': '0px',\n 'font-size': '11px' ,\n 'line-height': '12px' ,\n 'font-family': '\"lucida grande\",tahoma,verdana,arial,sans-serif'\n });\n\n // the textarea must have a transparent background so we can see the highlight div behind it\n this.textarea.css({\n 'background-color': 'transparent',\n 'padding': '5px',\n 'margin': '0px',\n 'width': this.options.width,\n 'height': this.options.height,\n 'font-size': '11px',\n 'line-height': '12px' ,\n 'font-family': '\"lucida grande\",tahoma,verdana,arial,sans-serif',\n 'overflow': 'hidden',\n 'border': '0px solid #000000'\n });\n\n // apply the hooks\n this.highlighterContainer.bind('click', function() {\n scope.textarea.focus();\n });\n this.textarea.bind('keyup', function() {\n // when we type in the textarea, \n // we want the text to be processed and re-injected into the div behind it.\n scope.applyText($(this).val());\n });\n\n scope.applyText(this.textarea.val());\n\n } catch (err) {\n this.error(err)\n }\n return true;\n };\n pluginClass.prototype.applyText = function (text) {\n try {\n var scope = this;\n\n // parse the text:\n // replace all the line braks by <br/>, and all the double spaces by the html version &nbsp;\n text = this.replaceAll(text,'\\n','<br/>');\n text = this.replaceAll(text,' ','&nbsp;&nbsp;');\n text = this.replaceAll(text,' ','&nbsp;');\n\n // replace the words by a highlighted version of the words\n for (var i=0;i<this.options.words.length;i++) {\n text = this.replaceAll(text,this.options.words[i][0],'<span style=\"background-color: #D8DFEA;\">'+this.options.words[i][1]+'</span>');\n //text = this.replaceAll(text,'(\\\\[b])(.+?)(\\\\[/b])','<span style=\"font-weight:bold;background-color: #D8DFEA;\">$1$2$3</span>');\n }\n\n // re-inject the processed text into the div\n this.highlighter.html(text);\n if (this.highlighter[0].clientHeight > this.options.height) {\n // document.getElementById(\"highlighter0\")\n this.textarea[0].style.height=this.highlighter[0].clientHeight +19+\"px\";\n }\n else {\n this.textarea[0].style.height=this.options.height;\n }\n\n } catch (err) {\n this.error(err);\n }\n return true;\n };\n // \"replace all\" function\n pluginClass.prototype.replaceAll = function(txt, replace, with_this) {\n return txt.replace(new RegExp(replace, 'g'),with_this);\n }\n\n // don't worry about this part, it's just the required code for the plugin to hadle the methods and stuffs. Not relevant here.\n //**********************\n // process\n var fn;\n var options;\n if (arguments.length == 0) {\n fn = \"init\";\n options = {};\n } else if (arguments.length == 1 && typeof(arguments[0]) == 'object') {\n fn = \"init\";\n options = $.extend({},arguments[0]);\n } else {\n fn = arguments[0];\n options = $.extend({},arguments[1]);\n }\n\n $.each(this, function(idx, item) {\n // if the component is not yet existing, create it.\n if ($(item).data('highlightPlugin') == null) {\n $(item).data('highlightPlugin', new pluginClass());\n $(item).data('highlightPlugin').__init($(item));\n }\n $(item).data('highlightPlugin').execute(fn, options);\n });\n return this;\n }\n });\n\n })(jQuery);\n\n\n </script>\n</head>\n<body>\n\n <div id=\"container0\">\n <div id=\"highlighterContainer0\">\n <div id=\"highlighter0\"></div>\n </div>\n <div id=\"inputContainer0\">\n <textarea id=\"text1\" cols=\"30\" rows=\"15\">hello world</textarea>\n </div>\n </div>\n<h1> haus </h1>\n <div id=\"container1\">\n <div id=\"highlighterContainer1\">\n <div id=\"highlighter1\"></div>\n </div>\n <div id=\"inputContainer1\">\n <textarea cols=\"30\" rows=\"15\">hipp hipp\n hurra, \n [b]ich hab es jetzt![/b]</textarea>\n </div>\n </div>\n\n</body>\n" }, { "answer_id": 18282831, "author": "Shlomi Hassid", "author_id": 1486486, "author_profile": "https://Stackoverflow.com/users/1486486", "pm_score": 2, "selected": false, "text": "//include function like in the fiddle!\n\n//CREATE ELEMENT:\n\ncreate_bind_textarea_highlight({ \n eleId:\"wrap_all_highlighter\",\n width:400,\n height:110,\n padding:5, \n background:'white',\n backgroundControls:'#585858',\n radius:5,\n fontFamilly:'Arial',\n fontSize:13,\n lineHeight:18,\n counterlettres:true,\n counterFont:'red',\n matchpatterns:[[\"(#[0-9A-Za-z]{0,})\",\"$1\"],[\"(@[0-9A-Za-z]{0,})\",\"$1\"]],\n hightlightsColor:['#00d2ff','#FFBF00'],\n objectsCopy:[\"copy_hashes\",\"copy_at\"]\n //PRESS Ctrl + SHIFT for direction swip!\n });\n\n //HTML EXAMPLE:\n <div id=\"wrap_all_highlighter\" placer='1'></div>\n <div id='copy_hashes'></div><!--Optional-->\n <div id='copy_at'></div><!--Optional-->\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80/" ]
142,545
<p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p> <p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
[ { "answer_id": 142561, "author": "awatts", "author_id": 22847, "author_profile": "https://Stackoverflow.com/users/22847", "pm_score": 1, "selected": false, "text": "__builtin__ import __builtin__\n__builtin__.foo = 'some-value'\n __builtins__ foo foo = 'some-other-value'" }, { "answer_id": 142566, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 8, "selected": true, "text": "__builtin__ __builtin__ print foo\n import __builtin__\n__builtin__.foo = 1\nimport a\n __builtin__ __builtins__ __builtin__ builtins" }, { "answer_id": 142581, "author": "hayalci", "author_id": 16084, "author_profile": "https://Stackoverflow.com/users/16084", "pm_score": 5, "selected": false, "text": "var_name = \"my_useful_string\"\n" }, { "answer_id": 142601, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": false, "text": "var = 1\n import a\nprint a.var\nimport c\nprint a.var\n import a\na.var = 2\n $ python b.py\n# -> 1 2\n django.conf.settings" }, { "answer_id": 142669, "author": "spiv", "author_id": 22701, "author_profile": "https://Stackoverflow.com/users/22701", "pm_score": 3, "selected": false, "text": "__builtins__ __builtins__.foo = 'something'\nprint foo\n my_globals.py # my_globals.py\nfoo = 'something'\n import my_globals\nprint my_globals.foo\n __builtins__" }, { "answer_id": 3269974, "author": "user394430", "author_id": 394430, "author_profile": "https://Stackoverflow.com/users/394430", "pm_score": 4, "selected": false, "text": "import module_b\nmy_var=2\nmodule_b.do_something_with_my_globals(globals())\nprint my_var\n def do_something_with_my_globals(glob): # glob is simply a dict.\n glob[\"my_var\"]=3\n" }, { "answer_id": 10158462, "author": "Brian Arsuaga", "author_id": 1038218, "author_profile": "https://Stackoverflow.com/users/1038218", "pm_score": 1, "selected": false, "text": "def builtin_find(f, x, d=None):\n for i in x:\n if f(i):\n return i\n return d\n\nimport __builtin__\n__builtin__.find = builtin_find\n find(lambda i: i < 0, [1, 3, 0, -5, -10]) # Yields -5, the first negative.\n" }, { "answer_id": 20331768, "author": "foudfou", "author_id": 421846, "author_profile": "https://Stackoverflow.com/users/421846", "pm_score": 1, "selected": false, "text": "# in myapp.__init__\nTimeouts = {} # cross-modules global mutable variables for testing purpose\nTimeouts['WAIT_APP_UP_IN_SECONDS'] = 60\n\n# in myapp.mod1\nfrom myapp import Timeouts\n\ndef wait_app_up(project_name, port):\n # wait for app until Timeouts['WAIT_APP_UP_IN_SECONDS']\n # ...\n\n# in myapp.test.test_mod1\nfrom myapp import Timeouts\n\ndef test_wait_app_up_fail(self):\n timeout_bak = Timeouts['WAIT_APP_UP_IN_SECONDS']\n Timeouts['WAIT_APP_UP_IN_SECONDS'] = 3\n with self.assertRaises(hlp.TimeoutException) as cm:\n wait_app_up(PROJECT_NAME, PROJECT_PORT)\n self.assertEqual(\"Timeout while waiting for App to start\", str(cm.exception))\n Timeouts['WAIT_JENKINS_UP_TIMEOUT_IN_SECONDS'] = timeout_bak\n test_wait_app_up_fail" }, { "answer_id": 31737507, "author": "Jonathan", "author_id": 1689770, "author_profile": "https://Stackoverflow.com/users/1689770", "pm_score": 2, "selected": false, "text": "import second\nvar = 1\n import first\nprint(first.var) # will throw an error because the order of execution happens before var gets declared.\n import first\n" }, { "answer_id": 49830730, "author": "robertofbaycot", "author_id": 9473313, "author_profile": "https://Stackoverflow.com/users/9473313", "pm_score": 2, "selected": false, "text": "# Note no definition of global variables\n\nclass router:\n \"\"\" Empty class \"\"\"\n import wall\ndef sourcefn():\n msg = 'Hello world!'\n wall.msg = msg\n wall.router.msg = msg\n sourcefn wall.msg wall.router.message import wall\ndef destfn():\n\n if hasattr(wall, 'msg'):\n print 'global: ' + wall.msg\n del wall.msg\n else:\n print 'global: ' + 'no message'\n\n if hasattr(wall.router, 'msg'):\n print 'router: ' + wall.router.msg\n del wall.router.msg\n else:\n print 'router: ' + 'no message'\n destfn destfn import source, dest\n\nsource.sourcefn()\n\ndest.destfn() # variables deleted after this call\ndest.destfn()\n dest.destfn wall.msg wall.router.msg" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22897/" ]
142,548
<p>Is there a way to deploy a given war file on Tomcat server? I want to do this without using the web interface.</p>
[ { "answer_id": 142554, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 2, "selected": false, "text": " <Context path=\"/strutsDisplayTag\" \n reloadable=\"true\" \n docBase=\"C:\\work\\learn\\jsp\\strutsDisplayTag\" \n workDir=\"C:\\work\\learn\\jsp\\strutsDisplayTag\\work\" />\n" }, { "answer_id": 143267, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 5, "selected": false, "text": "pom.xml mvn tomcat:deploy pom.xml $CATALINA_BASE/conf/tomcat-users.xml" }, { "answer_id": 14134435, "author": "kotfu", "author_id": 1944623, "author_profile": "https://Stackoverflow.com/users/1944623", "pm_score": 1, "selected": false, "text": "$ tomcat-manager --user=admin --password=newenglandclamchowder \\\n> http://localhost:8080/manager/ stop /myapp\n $ tomcat-manager --user=admin --password=newenglandclamchowder \\\n> http://localhost:8080/manager deploy /myapp ~/src/myapp/myapp.war\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
142,559
<p>I have pushed my .htaccess files to the production severs, but they don't work. Would a restart be the next step, or should I check something else.</p>
[ { "answer_id": 142576, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 6, "selected": false, "text": ".htaccess" }, { "answer_id": 43694908, "author": "Abhishek Gurjar", "author_id": 5345150, "author_profile": "https://Stackoverflow.com/users/5345150", "pm_score": 2, "selected": false, "text": "Options -Indexes deny all" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22325/" ]
142,602
<p>I was a C++ developer (mostly ATL/COM stuff) until, as many of us, I switched to C# in 2001. I didn't do much C++ programming since then.</p> <p>Do you have any tips on how to revive my C++ skills? What has changed in C++ in the last years? Are there good books, articles or blogs covering the language. The problem is that most material I could find either targets people who are new to the language or those with a lot of experience.</p> <p>Which C++ libraries are popular these days? I guess I will need to read on the STL because I didn't use it much. What else? Boost? ATL? WTL?</p>
[ { "answer_id": 142871, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 2, "selected": false, "text": "gtest" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/712/" ]
142,614
<p>Does anyone have C# code handy for doing a ping and traceroute to a target computer? I am looking for a pure code solution, not what I'm doing now, which is invoking the ping.exe and tracert.exe program and parsing the output. I would like something more robust.</p>
[ { "answer_id": 2688152, "author": "Scott", "author_id": 6042, "author_profile": "https://Stackoverflow.com/users/6042", "pm_score": 6, "selected": false, "text": "using System.Collections.Generic;\nusing System.Net.NetworkInformation;\nusing System.Text;\nusing System.Net;\n\nnamespace Answer\n{ \n public class TraceRoute\n {\n private const string Data = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\n\n public static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress)\n {\n return GetTraceRoute(hostNameOrAddress, 1);\n }\n private static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress, int ttl)\n {\n Ping pinger = new Ping();\n PingOptions pingerOptions = new PingOptions(ttl, true);\n int timeout = 10000;\n byte[] buffer = Encoding.ASCII.GetBytes(Data);\n PingReply reply = default(PingReply);\n\n reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions);\n\n List<IPAddress> result = new List<IPAddress>();\n if (reply.Status == IPStatus.Success)\n {\n result.Add(reply.Address);\n }\n else if (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.TimedOut)\n {\n //add the currently returned address if an address was found with this TTL\n if (reply.Status == IPStatus.TtlExpired) result.Add(reply.Address);\n //recurse to get the next address...\n IEnumerable<IPAddress> tempResult = default(IEnumerable<IPAddress>);\n tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1);\n result.AddRange(tempResult);\n }\n else\n {\n //failure \n }\n\n return result;\n }\n }\n}\n Public Class TraceRoute\n Private Const Data As String = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n\n Public Shared Function GetTraceRoute(ByVal hostNameOrAddress As String) As IEnumerable(Of IPAddress)\n Return GetTraceRoute(hostNameOrAddress, 1)\n End Function\n Private Shared Function GetTraceRoute(ByVal hostNameOrAddress As String, ByVal ttl As Integer) As IEnumerable(Of IPAddress)\n Dim pinger As Ping = New Ping\n Dim pingerOptions As PingOptions = New PingOptions(ttl, True)\n Dim timeout As Integer = 10000\n Dim buffer() As Byte = Encoding.ASCII.GetBytes(Data)\n Dim reply As PingReply\n\n reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions)\n\n Dim result As List(Of IPAddress) = New List(Of IPAddress)\n If reply.Status = IPStatus.Success Then\n result.Add(reply.Address)\n ElseIf reply.Status = IPStatus.TtlExpired Then\n 'add the currently returned address\n result.Add(reply.Address)\n 'recurse to get the next address...\n Dim tempResult As IEnumerable(Of IPAddress)\n tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1)\n result.AddRange(tempResult)\n Else\n 'failure \n End If\n\n Return result\n End Function\nEnd Class\n" }, { "answer_id": 42683738, "author": "Nigel Thomas", "author_id": 5221568, "author_profile": "https://Stackoverflow.com/users/5221568", "pm_score": 0, "selected": false, "text": " using System.Collections.Generic;\n using System.Net.NetworkInformation;\n using System.Text;\n using System.Net;\n\n ...\n\n public static void TraceRoute(string hostNameOrAddress)\n {\n for (int i = 1; i < 20; i++)\n {\n IPAddress ip = GetTraceRoute(hostNameOrAddress, i);\n if(ip == null)\n {\n break;\n }\n Console.WriteLine(ip.ToString());\n }\n }\n\n private static IPAddress GetTraceRoute(string hostNameOrAddress, int ttl)\n {\n const string Data = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\n Ping pinger = new Ping();\n PingOptions pingerOptions = new PingOptions(ttl, true);\n int timeout = 10000;\n byte[] buffer = Encoding.ASCII.GetBytes(Data);\n PingReply reply = default(PingReply);\n\n reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions);\n\n List<IPAddress> result = new List<IPAddress>();\n if (reply.Status == IPStatus.Success || reply.Status == IPStatus.TtlExpired)\n {\n return reply.Address;\n }\n else\n {\n return null;\n }\n }\n" }, { "answer_id": 45565253, "author": "caesay", "author_id": 184746, "author_profile": "https://Stackoverflow.com/users/184746", "pm_score": 4, "selected": false, "text": "public static IEnumerable<IPAddress> GetTraceRoute(string hostname)\n{\n // following are similar to the defaults in the \"traceroute\" unix command.\n const int timeout = 10000;\n const int maxTTL = 30;\n const int bufferSize = 32;\n\n byte[] buffer = new byte[bufferSize];\n new Random().NextBytes(buffer);\n\n using (var pinger = new Ping())\n {\n for (int ttl = 1; ttl <= maxTTL; ttl++)\n {\n PingOptions options = new PingOptions(ttl, true);\n PingReply reply = pinger.Send(hostname, timeout, buffer, options);\n\n // we've found a route at this ttl\n if (reply.Status == IPStatus.Success || reply.Status == IPStatus.TtlExpired)\n yield return reply.Address;\n\n // if we reach a status other than expired or timed out, we're done searching or there has been an error\n if (reply.Status != IPStatus.TtlExpired && reply.Status != IPStatus.TimedOut)\n break;\n }\n }\n}\n" }, { "answer_id": 49236896, "author": "Stephen Kennedy", "author_id": 397817, "author_profile": "https://Stackoverflow.com/users/397817", "pm_score": 1, "selected": false, "text": "Ping Ping PingCompleted Ping pingSender = new Ping();\npingSender.PingCompleted += PingCompletedCallback;\n string data = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\nbyte[] buffer = Encoding.ASCII.GetBytes(data);\nstring who = \"www.google.com\";\nAutoResetEvent waiter = new AutoResetEvent(false);\nint timeout = 12000;\n\nPingOptions options = new PingOptions(64, true);\n\npingSender.SendAsync(who, timeout, buffer, options, waiter);\n PingCompletedEventHandler public static void PingCompletedCallback(object sender, PingCompletedEventArgs e)\n{\n ... Do stuff here\n}\n public static void Main(string[] args)\n{\n string who = \"www.google.com\";\n AutoResetEvent waiter = new AutoResetEvent(false);\n\n Ping pingSender = new Ping();\n\n // When the PingCompleted event is raised,\n // the PingCompletedCallback method is called.\n pingSender.PingCompleted += PingCompletedCallback;\n\n // Create a buffer of 32 bytes of data to be transmitted.\n string data = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\n byte[] buffer = Encoding.ASCII.GetBytes(data);\n\n // Wait 12 seconds for a reply.\n int timeout = 12000;\n\n // Set options for transmission:\n // The data can go through 64 gateways or routers\n // before it is destroyed, and the data packet\n // cannot be fragmented.\n PingOptions options = new PingOptions(64, true);\n\n Console.WriteLine(\"Time to live: {0}\", options.Ttl);\n Console.WriteLine(\"Don't fragment: {0}\", options.DontFragment);\n\n // Send the ping asynchronously.\n // Use the waiter as the user token.\n // When the callback completes, it can wake up this thread.\n pingSender.SendAsync(who, timeout, buffer, options, waiter);\n\n // Prevent this example application from ending.\n // A real application should do something useful\n // when possible.\n waiter.WaitOne();\n Console.WriteLine(\"Ping example completed.\");\n}\n\npublic static void PingCompletedCallback(object sender, PingCompletedEventArgs e)\n{\n // If the operation was canceled, display a message to the user.\n if (e.Cancelled)\n {\n Console.WriteLine(\"Ping canceled.\");\n\n // Let the main thread resume. \n // UserToken is the AutoResetEvent object that the main thread \n // is waiting for.\n ((AutoResetEvent)e.UserState).Set();\n }\n\n // If an error occurred, display the exception to the user.\n if (e.Error != null)\n {\n Console.WriteLine(\"Ping failed:\");\n Console.WriteLine(e.Error.ToString());\n\n // Let the main thread resume. \n ((AutoResetEvent)e.UserState).Set();\n }\n\n Console.WriteLine($\"Roundtrip Time: {e.Reply.RoundtripTime}\");\n\n // Let the main thread resume.\n ((AutoResetEvent)e.UserState).Set();\n}\n" }, { "answer_id": 65828108, "author": "Wasp", "author_id": 2514630, "author_profile": "https://Stackoverflow.com/users/2514630", "pm_score": 2, "selected": false, "text": " using System;\n using System.Collections.Generic;\n using System.Net.NetworkInformation;\n\n namespace NetRouteAnalysis\n {\n class Program\n {\n static void Main(string[] args)\n {\n var route = TraceRoute.GetTraceRoute(\"8.8.8.8\")\n\n foreach (var step in route)\n {\n Console.WriteLine($\"{step.Address,-20} {step.Status,-20} \\t{step.RoundtripTime} ms\");\n }\n }\n }\n\n public static class TraceRoute\n {\n public static IEnumerable<PingReply> GetTraceRoute(string hostnameOrIp)\n {\n // Initial variables\n var limit = 1000;\n var buffer = new byte[32];\n var pingOpts = new PingOptions(1, true);\n var ping = new Ping(); \n\n // Result holder.\n PingReply result = null;\n\n do\n {\n result = ping.Send(hostnameOrIp, 4000, buffer, pingOpts);\n pingOpts = new PingOptions(pingOpts.Ttl + 1, pingOpts.DontFragment);\n\n if (result.Status != IPStatus.TimedOut)\n {\n yield return result;\n }\n }\n while (result.Status != IPStatus.Success && pingOpts.Ttl < limit);\n }\n } \n }\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
142,633
<p>I have a Button inside an UpdatePanel. The button is being used as the OK button for a ModalPopupExtender. For some reason, the button click event is not firing. Any ideas? Am I missing something?</p> <pre><code>&lt;asp:updatepanel id="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;cc1:ModalPopupExtender ID="ModalDialog" runat="server" TargetControlID="OpenDialogLinkButton" PopupControlID="ModalDialogPanel" OkControlID="ModalOKButton" BackgroundCssClass="ModalBackground"&gt; &lt;/cc1:ModalPopupExtender&gt; &lt;asp:Panel ID="ModalDialogPanel" CssClass="ModalPopup" runat="server"&gt; ... &lt;asp:Button ID="ModalOKButton" runat="server" Text="OK" onclick="ModalOKButton_Click" /&gt; &lt;/asp:Panel&gt; &lt;/ContentTemplate&gt; &lt;/asp:updatepanel&gt; </code></pre>
[ { "answer_id": 142656, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 3, "selected": false, "text": "OkControlID=\"ModalOKButton\"\n" }, { "answer_id": 383911, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 3, "selected": false, "text": "<asp:Panel ID=\"pnlResetPanelsView\" CssClass=\"modalPopup\" runat=\"server\" Style=\"display:none;\">\n <h2>\n Warning</h2>\n <p>\n Do you really want to reset the panels to the default view?</p>\n <div style=\"text-align: center;\">\n <asp:Button ID=\"btnResetPanelsViewOK\" Width=\"60\" runat=\"server\" Text=\"Yes\" \n CssClass=\"buttonSuperOfficeLayout\" OnClick=\"btnResetPanelsViewOK_Click\" />&nbsp;\n <asp:Button ID=\"btnResetPanelsViewCancel\" Width=\"60\" runat=\"server\" Text=\"No\" CssClass=\"buttonSuperOfficeLayout\" />\n </div>\n</asp:Panel>\n<ajax:ModalPopupExtender ID=\"mpeResetPanelsView\" runat=\"server\" TargetControlID=\"btnResetView\"\n PopupControlID=\"pnlResetPanelsView\" BackgroundCssClass=\"modalBackground\" DropShadow=\"true\"\n CancelControlID=\"btnResetPanelsViewCancel\" />\n" }, { "answer_id": 487272, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 2, "selected": false, "text": "<div>\n <cc1:ModalPopupExtender PopupControlID=\"Panel1\" \n ID=\"ModalPopupExtender1\"\n runat=\"server\" TargetControlID=\"LinkButton1\" OkControlID=\"Ok\" \n OnOkScript=\"__doPostBack('Ok','')\">\n </cc1:ModalPopupExtender>\n\n <asp:LinkButton ID=\"LinkButton1\" runat=\"server\">LinkButton</asp:LinkButton> \n</div> \n\n\n<asp:Panel ID=\"Panel1\" runat=\"server\">\n <asp:Button ID=\"Ok\" runat=\"server\" Text=\"Ok\" onclick=\"Ok_Click\" /> \n</asp:Panel> \n" }, { "answer_id": 1166869, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<ajax:ModalPopupExtender runat=\"server\" ID=\"modalPop\" \n PopupControlID=\"pnlpopup\" \n TargetControlID=\"btnGo\"\n BackgroundCssClass=\"modalBackground\"\n DropShadow=\"true\"\n CancelControlID=\"btnCancel\" X=\"470\" Y=\"300\" />\n\n\n//Codebehind \nprotected void OkButton_Clicked(object sender, EventArgs e)\n {\n\n modalPop.Hide();\n //Do something in codebehind\n }\n" }, { "answer_id": 4270107, "author": "user519205", "author_id": 519205, "author_profile": "https://Stackoverflow.com/users/519205", "pm_score": 2, "selected": false, "text": "<asp:Label ID=\"lblghost\" runat=\"server\" Text=\"\" />" }, { "answer_id": 37715348, "author": "Fandango68", "author_id": 2181188, "author_profile": "https://Stackoverflow.com/users/2181188", "pm_score": 1, "selected": false, "text": "__doPostBack function ValidateBeforePostBack(){ \n Page_ClientValidate('MyValidationGroupName'); \n if (Page_IsValid) { __doPostBack('',''); } \n else { $find('mpeBehaviourID').show(); } \n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21461/" ]
142,644
<p>We recently attempted to break apart some of our Visual Studio projects into libraries, and everything seemed to compile and build fine in a test project with one of the library projects as a dependency. However, attempting to run the application gave us the following nasty run-time error message:</p> <blockquote> <p>Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function pointer declared with a different calling convention.</p> </blockquote> <p>We have never even specified calling conventions (__cdecl etc.) for our functions, leaving all the compiler switches on the default. I checked and the project settings are consistent for calling convention across the library and test projects.</p> <p>Update: One of our devs changed the "Basic Runtime Checks" project setting from "Both (/RTC1, equiv. to /RTCsu)" to "Default" and the run-time vanished, leaving the program running apparently correctly. I do not trust this at all. Was this a proper solution, or a dangerous hack?</p>
[ { "answer_id": 142893, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": "esp int a, b[2];\n b[3] a esp" }, { "answer_id": 143387, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 0, "selected": false, "text": "CALLBACK WINAPI __stdcall __stdcall" }, { "answer_id": 863789, "author": "Tinclon", "author_id": 63029, "author_profile": "https://Stackoverflow.com/users/63029", "pm_score": 3, "selected": false, "text": "Child1* pMyChild = 0;\n...\npMyChild = pSomeClass->GetTheObj();// This call actually returned a Child2 object\npMyChild->SomeFunction(); // \"...value of ESP...\" error occurs here\n" }, { "answer_id": 1332874, "author": "Nikola Gedelovski", "author_id": 128900, "author_profile": "https://Stackoverflow.com/users/128900", "pm_score": 6, "selected": false, "text": "_stdcall _cdecl _stdcall" }, { "answer_id": 3333171, "author": "Khaled", "author_id": 402042, "author_profile": "https://Stackoverflow.com/users/402042", "pm_score": 4, "selected": false, "text": "HMODULE hPowerFunctions = LoadLibrary(\"Powrprof.dll\");\ntypedef bool (*tSetSuspendStateSig)(BOOL, BOOL, BOOL);\n\ntSetSuspendState SetSuspendState = (tSuspendStateSig)GetProcAddress(hPowerfunctions, \"SetSuspendState\");\n\nresult = SetSuspendState(false, false, false); <---- This line was where the error popped up. \n typedef bool (WINAPI*tSetSuspendStateSig)(BOOL, BOOL, BOOL);\n BOOLEAN WINAPI SetSuspendState(BOOLEAN, BOOLEAN, BOOLEAN);\n" }, { "answer_id": 10745412, "author": "Eric Leschinski", "author_id": 445131, "author_profile": "https://Stackoverflow.com/users/445131", "pm_score": 0, "selected": false, "text": "#include \"stdafx.h\"\nchar* blah(char *a){\n char p[1];\n strcat(p, a);\n return (char*)p;\n}\nint main(){\n std::cout << blah(\"a\");\n std::cin.get();\n}\n" }, { "answer_id": 11070124, "author": "Chandan", "author_id": 1461610, "author_profile": "https://Stackoverflow.com/users/1461610", "pm_score": 3, "selected": false, "text": " typedef long (*AU3_RunFn)(LPCWSTR, LPCWSTR);\n typedef long (WINAPI *AU3_RunFn)(LPCWSTR, LPCWSTR);\n\nAU3_RunFn _AU3_RunFn;\nHINSTANCE hInstLibrary = LoadLibrary(\"AutoItX3.dll\");\nif (hInstLibrary)\n{\n _AU3_RunFn = (AU3_RunFn)GetProcAddress(hInstLibrary, \"AU3_WinActivate\");\n if (_AU3_RunFn)\n _AU3_RunFn(L\"Untitled - Notepad\",L\"\");\n FreeLibrary(hInstLibrary);\n}\n" }, { "answer_id": 23775780, "author": "oli_arborum", "author_id": 116662, "author_profile": "https://Stackoverflow.com/users/116662", "pm_score": 2, "selected": false, "text": "LONG WINAPI myFunc( time_t, SYSTEMTIME*, BOOL* );\n time_t _time64_t WINAPI #define _USE_32BIT_TIME_T\n _time32_t #if _MSC_VER >= 1400\nLONG WINAPI myFunc( _time32_t, SYSTEMTIME*, BOOL* );\n#else\nLONG WINAPI myFunc( time_t, SYSTEMTIME*, BOOL* );\n#endif\n _time32_t time_t" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11180/" ]
142,653
<p>I have DocumentRoot /var/www/test in my .htaccess file. This is causing the apache server to give me a 500 internal server error.</p> <p>The error log file shows: alert] [client 127.0.0.1] /var/www/.htaccess: DocumentRoot not allowed here</p> <p>AllowOveride All is set in my conf file.</p> <p>Any idea why this is happening?</p>
[ { "answer_id": 142657, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": ".htaccess httpd.conf" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
142,693
<p>You know those websites that let you type in your checking account number and the routing number, and then they can transfer money to and from your account?</p> <p>How does that work? Any good services or APIs for doing that? Any gotchas?</p>
[ { "answer_id": 13636783, "author": "Christopher Ashley", "author_id": 654553, "author_profile": "https://Stackoverflow.com/users/654553", "pm_score": 1, "selected": false, "text": "<?php\n\nrequire \"../mpgClasses.php\";\n\n/************************ Request Variables **********************************/\n\n$store_id='monusqa002'; //account credentials\n$api_token='qatoken';\n\n/************************ Transaction Object******************************/\n\n\n$txnArray=array(type=>'us_ach_debit',\n order_id=>'ach-'.date(\"dmy-G:i:s\"),\n cust_id=> 'my cust id',\n amount=>'1.00'\n );\n\n$achTemplate = array(\n sec =>'ppd',\n cust_first_name => 'Bob',\n cust_last_name => 'Smith',\n cust_address1 => '101 Main St',\n cust_address2 => 'Apt 102,\n cust_city => 'Chicago',\n cust_state => 'IL',\n cust_zip =>'123456',\n routing_num => '490000018',\n account_num => '23456',\n check_num => '100',\n account_type => 'savings'\n );\n\n$mpgAchInfo = new mpgAchInfo ($achTemplate);\n$mpgTxn = new mpgTransaction($txnArray);\n$mpgTxn->setAchInfo($mpgAchInfo);\n\n$mpgRequest = new mpgRequest($mpgTxn);\n$mpgHttpPost = new mpgHttpsPost($store_id,$api_token,$mpgRequest);\n\n/************************ Response Object **********************************/\n\n$mpgResponse=$mpgHttpPost->getMpgResponse();\n\n\nprint(\"\\nCardType = \" . $mpgResponse->getCardType());\nprint(\"\\nTransAmount = \" . $mpgResponse->getTransAmount());\nprint(\"\\nTxnNumber = \" . $mpgResponse->getTxnNumber());\nprint(\"\\nReceiptId = \" . $mpgResponse->getReceiptId());\nprint(\"\\nTransType = \" . $mpgResponse->getTransType());\nprint(\"\\nReferenceNum = \" . $mpgResponse->getReferenceNum());\nprint(\"\\nResponseCode = \" . $mpgResponse->getResponseCode());\nprint(\"\\nMessage = \" . $mpgResponse->getMessage());\nprint(\"\\nAuthCode = \" . $mpgResponse->getAuthCode());\nprint(\"\\nComplete = \" . $mpgResponse->getComplete());\nprint(\"\\nTransDate = \" . $mpgResponse->getTransDate());\nprint(\"\\nTransTime = \" . $mpgResponse->getTransTime());\nprint(\"\\nTicket = \" . $mpgResponse->getTicket());\nprint(\"\\nTimedOut = \" . $mpgResponse->getTimedOut());\n\n?>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17076/" ]
142,708
<p>I can't seem to find any <em>useful</em> documentation from Microsoft about how one would use the <code>Delimiter</code> and <code>InheritsFromParent</code> attributes in the <code>UserMacro</code> element when defining user Macros in <code>.vsprops</code> property sheet files for Visual Studio.</p> <p>Here's sample usage:</p> <pre><code>&lt;UserMacro Name="INCLUDEPATH" Value="$(VCROOT)\Inc" InheritsFromParent="TRUE" Delimiter=";"/&gt; </code></pre> <p>From the above example, I'm guessing that <em>"inherit"</em> really means <em>"a) if definition is non-empty then append delimiter, and b) append new definition"</em> where as the non-inherit behavior would be to simply replace any current macro definition. Does anyone know for sure? Even better, does anyone have any suggested source of alternative documentation for Visual Studio <code>.vsprops</code> files and macros?</p> <p>NOTE: this is <em>not</em> the same as the <code>InheritedPropertySheets</code> attribute of the <code>VisualStudioPropertySheet</code> element, for example:</p> <pre><code>&lt;VisualStudioPropertySheet ... InheritedPropertySheets=".\my.vsprops"&gt; </code></pre> <p>In this case <em>"inherit"</em> basically means <em>"include"</em>.</p>
[ { "answer_id": 145260, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 4, "selected": true, "text": "InheritsFromParent p.vcproj d.vsprops InheritedPropertySheets d.vsprops b.vsprops p.vcproj .vsprops ...\n<UserMacro Name=\"NOENV\" Value=\"B\"/>\n<UserMacro Name=\"OVERRIDE\" Value=\"B\" PerformEnvironmentSet=\"true\"/>\n<UserMacro Name=\"PREPEND\" Value=\"B\" PerformEnvironmentSet=\"true\"/>\n...\n ...\n<VisualStudioPropertySheet ... InheritedPropertySheets=\".\\b.vsprops\">\n<UserMacro Name=\"ENV\" Value=\"$(NOENV)\" PerformEnvironmentSet=\"true\"/>\n<UserMacro Name=\"OVERRIDE\" Value=\"D\" PerformEnvironmentSet=\"true\"/>\n<UserMacro Name=\"PREPEND\" Value=\"D\" InheritsFromParent=\"true\"\n Delimiter=\"+\" PerformEnvironmentSet=\"true\"/>\n...\n ...\n<Configuration ... InheritedPropertySheets=\".\\d.vsprops\">\n<Tool Name=\"VCPreBuildEventTool\" CommandLine=\"set | sort\"/>\n...\n ...\nENV=B\nOVERRIDE=D\nPREPEND=D+B\n...\n PerformEnvironmentSet=\"true\" NOENV PerformEnvironmentSet InheritsFromParent b.vsprops NOENV d.vsprops InheritsFromParent OVERRIDE D B InheritsFromParent=\"true\" Delimiter PREPEND D+B D B+D .vsprops" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
142,710
<p>A legacy embedded system is implemented using a cooperative multi-tasking scheduler. </p> <p>The system essentially works along the following lines:</p> <ul> <li>Task A does work</li> <li>When Task A is done, it yields the processor.</li> <li>Task B gets the processor and does work.</li> <li>Task B yields<br> ... </li> <li>Task n yields</li> <li>Task A gets scheduled and does work</li> </ul> <p>One big Circular Queue: A -> B -> C -> ... -> n -> A</p> <p>We are porting the system to a new platform and want to minimize system redesign.</p> <p>Is there a way to implement that type of cooperative multi-tasking in vxWorks?</p>
[ { "answer_id": 313159, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 0, "selected": false, "text": "void scheduler()\n{\n while (1)\n {\n int st = microseconds();\n a();\n b();\n c();\n sleep(microseconds() - st);\n }\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
142,740
<p>I want to do something like the following in spring:</p> <pre><code>&lt;beans&gt; ... &lt;bean id="bean1" ... /&gt; &lt;bean id="bean2"&gt; &lt;property name="propName" value="bean1.foo" /&gt; ... </code></pre> <p>I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work.</p>
[ { "answer_id": 142765, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": -1, "selected": false, "text": "foo class SpringRef {\n private String targetProperty;\n private Object targetBean;\n\n //getters/setters\n\n public Object getValue() {\n //resolve the value of the targetProperty on targetBean. \n }\n}\n" }, { "answer_id": 142796, "author": "Pablo Fernandez", "author_id": 7595, "author_profile": "https://Stackoverflow.com/users/7595", "pm_score": 4, "selected": true, "text": "<beans>\n...\n<bean id=\"foo\" class=\"foopackage.foo\"/>\n<bean id=\"bean1\" class=\"foopackage.bean1\">\n <property name=\"foo\" ref=\"foo\"/>\n</bean> \n<bean id=\"bean2\" class=\"foopackage.bean2\">\n <property name=\"propName\" ref=\"foo\"/>\n</bean>\n....\n</beans>\n <util:property-path id=\"propName\" path=\"bean1.foo\"/>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22063/" ]
142,750
<p>I'm trying to get either CreateProcess or CreateProcessW to execute a process with a name &lt; MAX&#95;PATH characters but in a path that's greater than MAX&#95;PATH characters. According to the docs at: <a href="http://msdn.microsoft.com/en-us/library/ms682425.aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/ms682425.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms682425.aspx</a></a>, I need to make sure lpApplicationName isn't NULL and then lpCommandLine can be up to 32,768 characters.</p> <p>I tried that, but I get ERROR&#95;PATH&#95;NOT&#95;FOUND.</p> <p>I changed to CreateProcessW, but still get the same error. When I prefix lpApplicationName with \\?\ as described in <a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx</a></a> when calling CreateProcessW I get a different error that makes me think I'm a bit closer: ERROR&#95;SXS&#95;CANT&#95;GEN&#95;ACTCTX.</p> <p>My call to CreateProcessW is:</p> <p><code> CreateProcessW(w&#95;argv0,arg_string,NULL,NULL,0,NULL,NULL,&amp;si,&amp;ipi); </code></p> <p>where w_argv0 is <code>\\?\&lt;long absolute path&gt;\foo.exe.</code></p> <p>arg_string contains "&lt;long absolute path&gt;\foo.exe" foo </p> <p>si is set as follows:</p> <pre> memset(&si,0,sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;> </pre> <p>and pi is empty, as in:</p> <pre> memset(&pi,0,sizeof(pi)); </pre> <p>I looked in the system event log and there's a new entry each time I try this with event id 59, source SideBySide: Generate Activation Context failed for .Manifest. Reference error message: The operation completed successfully.</p> <p>The file I'm trying to execute runs fine in a path &lt; MAX_PATH characters.</p> <p>To clarify, no one component of &lt;long absolute path&gt; is greater than MAX&#95;PATH characters. The name of the executable itself certainly isn't, even with .manifest on the end. But, the entire path together is greater than MAX&#95;PATH characters long.</p> <p>I get the same error whether I embed its manifest or not. The manifest is named foo.exe.manifest and lives in the same directory as the executable when it's not embedded. It contains:</p> <pre> &lt;?xml version='1.0' encoding='UTF-8' standalone='yes'?> &lt;assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> &lt;dependency> &lt;dependentAssembly> &lt;assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50727.762' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> &lt;/dependentAssembly> &lt;/dependency> &lt;/assembly> </pre> <p>Anyone know how to get this to work? Possibly:</p> <ul> <li><p>some other way to call CreateProcess or CreateProcessW to execute a process in a path > MAX_PATH characters</p></li> <li><p>something I can do in the manifest file</p></li> </ul> <p>I'm building with Visual Studio 2005 on XP SP2 and running native.</p> <p>Thanks for your help.</p>
[ { "answer_id": 143399, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 1, "selected": false, "text": "MAX_PATH lpCommandLine PATH lpEnvironment" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9572/" ]
142,764
<p>I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.</p> <p>Thanks Dirk</p>
[ { "answer_id": 142770, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "./configure && make && sudo make install /usr/bin/python /usr/bin/python2.5 ln -s /usr/local/bin/python2.6 /usr/bin/python /usr/lib/python2.5/site-packages/ /usr/local/lib/python2.5/site-packages/ sudo easy_install <name>" }, { "answer_id": 142777, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 1, "selected": false, "text": "./configure\nmake\nsudo make install\n" }, { "answer_id": 152185, "author": "Dickon Reed", "author_id": 22668, "author_profile": "https://Stackoverflow.com/users/22668", "pm_score": 1, "selected": false, "text": "./configure\nmake\nsudo make install\nls -l /usr/local/bin\n python /usr/bin python2.6" }, { "answer_id": 633753, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 3, "selected": false, "text": "# Python 2.6\ndeb http://ppa.launchpad.net/doko/ubuntu intrepid main\ndeb-src http://ppa.launchpad.net/doko/ubuntu intrepid main\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
142,789
<p>From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story). </p> <p>I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task. I just don't understand how they get set up and how they actually work. Any examples would be appreciated.</p>
[ { "answer_id": 142792, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "on_event() watch_events()" }, { "answer_id": 142809, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 9, "selected": true, "text": "void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))\n{\n for (size_t i=0; i<arraySize; i++)\n array[i] = getNextValue();\n}\n\nint getNextRandomValue(void)\n{\n return rand();\n}\n\nint main(void)\n{\n int myarray[10];\n populate_array(myarray, 10, getNextRandomValue);\n ...\n}\n populate_array getNextRandomValue populate_array populate_array" }, { "answer_id": 147241, "author": "Russell Bryant", "author_id": 23224, "author_profile": "https://Stackoverflow.com/users/23224", "pm_score": 7, "selected": false, "text": "typedef void (*event_cb_t)(const struct event *evt, void *userdata);\n int event_cb_register(event_cb_t cb, void *userdata);\n static void my_event_cb(const struct event *evt, void *data)\n{\n /* do stuff and things with the event */\n}\n\n...\n event_cb_register(my_event_cb, &my_custom_data);\n...\n struct event_cb {\n event_cb_t cb;\n void *data;\n};\n struct event_cb *callback;\n\n...\n\n/* Get the event_cb that you want to execute */\n\ncallback->cb(event, callback->data);\n" }, { "answer_id": 13580715, "author": "Gautham Kantharaju", "author_id": 1855959, "author_profile": "https://Stackoverflow.com/users/1855959", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <string.h>\n#include \"../../common_typedef.h\"\n\ntypedef void (*call_back) (S32, S32);\n\nvoid test_call_back(S32 a, S32 b)\n{\n printf(\"In call back function, a:%d \\t b:%d \\n\", a, b);\n}\n\nvoid call_callback_func(call_back back)\n{\n S32 a = 5;\n S32 b = 7;\n\n back(a, b);\n}\n\nS32 main(S32 argc, S8 *argv[])\n{\n S32 ret = SUCCESS;\n\n call_back back;\n\n back = test_call_back;\n\n call_callback_func(back);\n\n return ret;\n}\n" }, { "answer_id": 32429847, "author": "daemondave", "author_id": 4603962, "author_profile": "https://Stackoverflow.com/users/4603962", "pm_score": 4, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n\n/* The calling function takes a single callback as a parameter. */\nvoid PrintTwoNumbers(int (*numberSource)(void)) {\n printf(\"%d and %d\\n\", numberSource(), numberSource());\n}\n\n/* A possible callback */\nint overNineThousand(void) {\n return (rand() % 1000) + 9001;\n}\n\n/* Another possible callback. */\nint meaningOfLife(void) {\n return 42;\n}\n\n/* Here we call PrintTwoNumbers() with three different callbacks. */\nint main(void) {\n PrintTwoNumbers(&rand);\n PrintTwoNumbers(&overNineThousand);\n PrintTwoNumbers(&meaningOfLife);\n return 0;\n}\n" }, { "answer_id": 49072888, "author": "Richard Chambers", "author_id": 1466970, "author_profile": "https://Stackoverflow.com/users/1466970", "pm_score": 3, "selected": false, "text": "bsearch() qsort() bsearch() qsort() bsearch() bsearch() bsearch() #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct {\n int iValue;\n int kValue;\n char label[6];\n} MyData;\n\nint cmpMyData_iValue (MyData *item1, MyData *item2)\n{\n if (item1->iValue < item2->iValue) return -1;\n if (item1->iValue > item2->iValue) return 1;\n return 0;\n}\n\nint cmpMyData_kValue (MyData *item1, MyData *item2)\n{\n if (item1->kValue < item2->kValue) return -1;\n if (item1->kValue > item2->kValue) return 1;\n return 0;\n}\n\nint cmpMyData_label (MyData *item1, MyData *item2)\n{\n return strcmp (item1->label, item2->label);\n}\n\nvoid bsearch_results (MyData *srch, MyData *found)\n{\n if (found) {\n printf (\"found - iValue = %d, kValue = %d, label = %s\\n\", found->iValue, found->kValue, found->label);\n } else {\n printf (\"item not found, iValue = %d, kValue = %d, label = %s\\n\", srch->iValue, srch->kValue, srch->label);\n }\n}\n\nint main ()\n{\n MyData dataList[256] = {0};\n\n {\n int i;\n for (i = 0; i < 20; i++) {\n dataList[i].iValue = i + 100;\n dataList[i].kValue = i + 1000;\n sprintf (dataList[i].label, \"%2.2d\", i + 10);\n }\n }\n\n// ... some code then we do a search\n {\n MyData srchItem = { 105, 1018, \"13\"};\n MyData *foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_iValue );\n\n bsearch_results (&srchItem, foundItem);\n\n foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_kValue );\n bsearch_results (&srchItem, foundItem);\n\n foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_label );\n bsearch_results (&srchItem, foundItem);\n }\n}\n telnet accept() listen() telnet 127.0.0.1 8282 http://127.0.0.1:8282/ pthreads #include <stdio.h>\n#include <winsock2.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <Windows.h>\n\n// Need to link with Ws2_32.lib\n#pragma comment(lib, \"Ws2_32.lib\")\n\n// function for the thread we are going to start up with _beginthreadex().\n// this function/thread will create a listen server waiting for a TCP\n// connection request to come into the designated port.\n// _stdcall modifier required by _beginthreadex().\nint _stdcall ioThread(void (*pOutput)())\n{\n //----------------------\n // Initialize Winsock.\n WSADATA wsaData;\n int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);\n if (iResult != NO_ERROR) {\n printf(\"WSAStartup failed with error: %ld\\n\", iResult);\n return 1;\n }\n //----------------------\n // Create a SOCKET for listening for\n // incoming connection requests.\n SOCKET ListenSocket;\n ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (ListenSocket == INVALID_SOCKET) {\n wprintf(L\"socket failed with error: %ld\\n\", WSAGetLastError());\n WSACleanup();\n return 1;\n }\n //----------------------\n // The sockaddr_in structure specifies the address family,\n // IP address, and port for the socket that is being bound.\n struct sockaddr_in service;\n service.sin_family = AF_INET;\n service.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n service.sin_port = htons(8282);\n\n if (bind(ListenSocket, (SOCKADDR *)& service, sizeof(service)) == SOCKET_ERROR) {\n printf(\"bind failed with error: %ld\\n\", WSAGetLastError());\n closesocket(ListenSocket);\n WSACleanup();\n return 1;\n }\n //----------------------\n // Listen for incoming connection requests.\n // on the created socket\n if (listen(ListenSocket, 1) == SOCKET_ERROR) {\n printf(\"listen failed with error: %ld\\n\", WSAGetLastError());\n closesocket(ListenSocket);\n WSACleanup();\n return 1;\n }\n //----------------------\n // Create a SOCKET for accepting incoming requests.\n SOCKET AcceptSocket;\n printf(\"Waiting for client to connect...\\n\");\n\n //----------------------\n // Accept the connection.\n AcceptSocket = accept(ListenSocket, NULL, NULL);\n if (AcceptSocket == INVALID_SOCKET) {\n printf(\"accept failed with error: %ld\\n\", WSAGetLastError());\n closesocket(ListenSocket);\n WSACleanup();\n return 1;\n }\n else\n pOutput (); // we have a connection request so do the callback\n\n // No longer need server socket\n closesocket(ListenSocket);\n\n WSACleanup();\n return 0;\n}\n\n// our callback which is invoked whenever a connection is made.\nvoid printOut(void)\n{\n printf(\"connection received.\\n\");\n}\n\n#include <process.h>\n\nint main()\n{\n // start up our listen server and provide a callback\n _beginthreadex(NULL, 0, ioThread, printOut, 0, NULL);\n // do other things while waiting for a connection. In this case\n // just sleep for a while.\n Sleep(30000);\n}\n" }, { "answer_id": 53622778, "author": "Asif", "author_id": 8638742, "author_profile": "https://Stackoverflow.com/users/8638742", "pm_score": 1, "selected": false, "text": "qsort(arr,N,sizeof(int),compare_s2b);\n #include <stdio.h>\n#include <stdlib.h>\n\nint arr[]={56,90,45,1234,12,3,7,18};\n//function prototype declaration \n\nint compare_s2b(const void *a,const void *b);\n\nint compare_b2s(const void *a,const void *b);\n\n//arranges the array number from the smallest to the biggest\nint compare_s2b(const void* a, const void* b)\n{\n const int* p=(const int*)a;\n const int* q=(const int*)b;\n\n return *p-*q;\n}\n\n//arranges the array number from the biggest to the smallest\nint compare_b2s(const void* a, const void* b)\n{\n const int* p=(const int*)a;\n const int* q=(const int*)b;\n\n return *q-*p;\n}\n\nint main()\n{\n printf(\"Before sorting\\n\\n\");\n\n int N=sizeof(arr)/sizeof(int);\n\n for(int i=0;i<N;i++)\n {\n printf(\"%d\\t\",arr[i]);\n }\n\n printf(\"\\n\");\n\n qsort(arr,N,sizeof(int),compare_s2b);\n\n printf(\"\\nSorted small to big\\n\\n\");\n\n for(int j=0;j<N;j++)\n {\n printf(\"%d\\t\",arr[j]);\n }\n\n qsort(arr,N,sizeof(int),compare_b2s);\n\n printf(\"\\nSorted big to small\\n\\n\");\n\n for(int j=0;j<N;j++)\n {\n printf(\"%d\\t\",arr[j]);\n }\n\n exit(0);\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22913/" ]
142,812
<p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
[ { "answer_id": 265491, "author": "MattG", "author_id": 23048, "author_profile": "https://Stackoverflow.com/users/23048", "pm_score": 3, "selected": false, "text": "testA = 2**0\ntestB = 2**1\ntestC = 2**3\n table = table | testB\n table = table & (~testC)\n bitfield_length = 0xff\nif ((table & testB & bitfield_length) != 0):\n print \"Field B set\"\n" }, { "answer_id": 1574928, "author": "Scott Griffiths", "author_id": 87699, "author_profile": "https://Stackoverflow.com/users/87699", "pm_score": 4, "selected": false, "text": "BitString a = BitString('0xed44')\nb = BitString('0b11010010')\nc = BitString(int=100, length=14)\nd = BitString('uintle:16=55, 0b110, 0o34')\ne = BitString(bytes='hello')\nf = pack('<2H, bin:3', 5, 17, '001') \n a.prepend('0b110')\nif '0b11' in b:\n c.reverse()\ng = a.join([b, d, e])\ng.replace('0b101', '0x3400ee1')\nif g[14]:\n del g[14:17]\nelse:\n g[55:58] = 'uint:11=33, int:9=-1'\n w = g.read(10).uint\nx, y, z = g.readlist('int:4, int:4, hex:32')\nif g.peek(8) == '0x00':\n g.pos += 10\n" }, { "answer_id": 11481471, "author": "nealmcb", "author_id": 507544, "author_profile": "https://Stackoverflow.com/users/507544", "pm_score": 6, "selected": false, "text": "flags.asbyte import ctypes\nc_uint8 = ctypes.c_uint8\n\nclass Flags_bits(ctypes.LittleEndianStructure):\n _fields_ = [\n (\"logout\", c_uint8, 1),\n (\"userswitch\", c_uint8, 1),\n (\"suspend\", c_uint8, 1),\n (\"idle\", c_uint8, 1),\n ]\n\nclass Flags(ctypes.Union):\n _fields_ = [(\"b\", Flags_bits),\n (\"asbyte\", c_uint8)]\n\nflags = Flags()\nflags.asbyte = 0xc\n\nprint(flags.b.idle)\nprint(flags.b.suspend)\nprint(flags.b.userswitch)\nprint(flags.b.logout)\n" }, { "answer_id": 53981676, "author": "Matthias Urlichs", "author_id": 966179, "author_profile": "https://Stackoverflow.com/users/966179", "pm_score": 0, "selected": false, "text": "set" }, { "answer_id": 57240381, "author": "papa", "author_id": 11841149, "author_profile": "https://Stackoverflow.com/users/11841149", "pm_score": 0, "selected": false, "text": "\"\"\" The following bit-manipulation methods are written to take a tuple as input, which is provided by the Bitfield class. The construct \nlooks weired, however the call to a setBit() looks ok and the editor (PyCharm) suggests all \npossible bit names. I did not find a more elegant solution that calls the setBit()-function and needs \nonly one argument.\nExample call:\n setBit( STW1.bm01NoOff2() ) \"\"\"\n\ndef setBit(TupleBitField_BitMask):\n # word = word | bit_mask\n TupleBitField_BitMask[0].word = TupleBitField_BitMask[0].word | TupleBitField_BitMask[1]\n\n\ndef isBit(TupleBitField_BitMask):\n # (word & bit_mask) != 0\n return (TupleBitField_BitMask[0].word & TupleBitField_BitMask[1]) !=0\n\n\ndef clrBit(TupleBitField_BitMask):\n #word = word & (~ BitMask)\n TupleBitField_BitMask[0].word = TupleBitField_BitMask[0].word & (~ TupleBitField_BitMask[1])\n\n\ndef toggleBit(TupleBitField_BitMask):\n #word = word ^ BitMask\n TupleBitField_BitMask[0].word = TupleBitField_BitMask[0].word ^ TupleBitField_BitMask[1]\n\n\"\"\" Create a Bitfield type for each control word of the application. (e.g. 16bit length). \nAssign a name for each bit in order that the editor (e.g. PyCharm) suggests the names from outside. \nThe bits are defined as methods that return the corresponding bit mask in order that the bit masks are read-only\nand will not be corrupted by chance.\nThe return of each \"bit\"-function is a tuple (handle to bitfield, bit_mask) in order that they can be \nsent as arguments to the single bit manipulation functions (see above): isBit(), setBit(), clrBit(), toggleBit()\nThe complete word of the Bitfield is accessed from outside by xxx.word.\nExamples:\n STW1 = STW1Type(0x1234) # instanciates and inits the bitfield STW1, STW1.word = 0x1234\n setBit(STW1.bm00() ) # set the bit with the name bm00(), e.g. bm00 = bitmask 0x0001\n print(\"STW1.word =\", hex(STW1.word))\n\"\"\"\nclass STW1Type():\n # assign names to the bit masks for each bit (these names will be suggested by PyCharm)\n # tip: copy the application's manual description here\n def __init__(self, word):\n # word = initial value, e.g. 0x0000\n self.word = word\n\n # define all bits here and copy the description of each bit from the application manual. Then you can jump\n # to this explanation with \"F3\"\n # return the handle to the bitfield and the BitMask of the bit.\n def bm00NoOff1_MeansON(self):\n # 0001 0/1= ON (edge)(pulses can be enabled)\n # 0 = OFF1 (braking with ramp-function generator, then pulse suppression & ready for switching on)\n return self, 0x0001\n\n def bm01NoOff2(self):\n # 0002 1 = No OFF2 (enable is possible)\n # 0 = OFF2 (immediate pulse suppression and switching on inhibited)\n return self, 0x0002\n\n def bm02NoOff3(self):\n # 0004 1 = No OFF3 (enable possible)\n # 0 = OFF3 (braking with the OFF3 ramp p1135, then pulse suppression and switching on inhibited)\n return self, 0x0004\n\n def bm03EnableOperation(self):\n # 0008 1 = Enable operation (pulses can be enabled)\n # 0 = Inhibit operation (suppress pulses)\n return self, 0x0008\n\n def bm04RampGenEnable(self):\n # 0010 1 = Hochlaufgeber freigeben (the ramp-function generator can be enabled)\n # 0 = Inhibit ramp-function generator (set the ramp-function generator output to zero)\n return self, 0x0010\n\n def b05RampGenContinue(self):\n # 0020 1 = Continue ramp-function generator\n # 0 = Freeze ramp-function generator (freeze the ramp-function generator output)\n return self, 0x0020\n\n def b06RampGenEnable(self):\n # 0040 1 = Enable speed setpoint; Drehzahlsollwert freigeben\n # 0 = Inhibit setpoint; Drehzahlsollwert sperren (set the ramp-function generator input to zero)\n return self, 0x0040\n\n def b07AcknowledgeFaults(self):\n # 0080 0/1= 1. Acknowledge faults; 1. Quittieren Störung\n return self, 0x0080\n\n def b08Reserved(self):\n # 0100 Reserved\n return self, 0x0100\n\n def b09Reserved(self):\n # 0200 Reserved\n return self, 0x0200\n\n def b10ControlByPLC(self):\n # 0400 1 = Control by PLC; Führung durch PLC\n return self, 0x0400\n\n def b11SetpointInversion(self):\n # 0800 1 = Setpoint inversion; Sollwert Invertierung\n return self, 0x0800\n\n def b12Reserved(self):\n # 1000 Reserved\n return self, 0x1000\n\n def b13MotorPotiSPRaise(self):\n # 2000 1 = Motorized potentiometer setpoint raise; (Motorpotenziometer Sollwert höher)\n return self, 0x2000\n\n def b14MotorPotiSPLower(self):\n # 4000 1 = Motorized potentiometer setpoint lower; (Motorpotenziometer Sollwert tiefer)\n return self, 0x4000\n\n def b15Reserved(self):\n # 8000 Reserved\n return self, 0x8000\n\n\n\"\"\" test the constrution and methods \"\"\"\nSTW1 = STW1Type(0xffff)\nprint(\"STW1.word =\", hex(STW1.word))\n\nclrBit(STW1.bm00NoOff1_MeansON())\nprint(\"STW1.word =\", hex(STW1.word))\n\nSTW1.word = 0x1234\nprint(\"STW1.word =\", hex(STW1.word))\n\nsetBit( STW1.bm00NoOff1_MeansON() )\nprint(\"STW1.word =\", hex(STW1.word))\n\nclrBit( STW1.bm00NoOff1_MeansON() )\nprint(\"STW1.word =\", hex(STW1.word))\n\ntoggleBit(STW1.bm03EnableOperation())\nprint(\"STW1.word =\", hex(STW1.word))\n\ntoggleBit(STW1.bm03EnableOperation())\nprint(\"STW1.word =\", hex(STW1.word))\n\nprint(\"STW1.bm00ON =\", isBit(STW1.bm00NoOff1_MeansON() ) )\nprint(\"STW1.bm04 =\", isBit(STW1.bm04RampGenEnable() ) )\n STW1.word = 0xffff\nSTW1.word = 0xfffe\nSTW1.word = 0x1234\nSTW1.word = 0x1235\nSTW1.word = 0x1234\nSTW1.word = 0x123c\nSTW1.word = 0x1234\nSTW1.bm00ON = False\nSTW1.bm04 = True\n" }, { "answer_id": 65092767, "author": "Grégoire Piffault", "author_id": 3018705, "author_profile": "https://Stackoverflow.com/users/3018705", "pm_score": 1, "selected": false, "text": "import math\n\nclass Bitfield:\n def __init__(self, size):\n self.bytes = bytearray(math.ceil(size / 8))\n\n def __getitem__(self, idx):\n return self.bytes[idx // 8] >> (idx % 8) & 1\n\n def __setitem__(self, idx, value):\n mask = 1 << (idx % 8)\n if value:\n self.bytes[idx // 8] |= mask\n else:\n self.bytes[idx // 8] &= ~mask\n # if size is not a multiple of 8, actual size will be the next multiple of 8\nbf = Bitfield(1000)\nbf[432] # 0\nbf[432] = 1\nbf[432] # 1\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471/" ]
142,813
<p>I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#. </p> <p>Example:</p> <pre> 2748 to "ABC" </pre>
[ { "answer_id": 142819, "author": "Muxa", "author_id": 10793, "author_profile": "https://Stackoverflow.com/users/10793", "pm_score": 3, "selected": true, "text": "2748.ToString(\"X\")\n" }, { "answer_id": 142828, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "char hexCharacters[17] = \"0123456789ABCDEF\";\nvoid toHex(char * outputString, long input)\n{\n outputString[0] = hexCharacters[(input >> 8) & 0x0F];\n outputString[1] = hexCharacters[(input >> 4) & 0x0F];\n outputString[2] = hexCharacters[input & 0x0F];\n}\n" }, { "answer_id": 143478, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "i.ToString(\"X3\")\n (i % 0x1000).ToString(\"X3\")\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/609/" ]
142,820
<p>I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write </p> <pre><code>myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction); </code></pre> <p>this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too.</p>
[ { "answer_id": 142823, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 6, "selected": true, "text": "[Browsable(true)]\npublic event EventHandler MyCustomEvent;\n" }, { "answer_id": 41104603, "author": "Pierre-Olivier Pignon", "author_id": 969741, "author_profile": "https://Stackoverflow.com/users/969741", "pm_score": 0, "selected": false, "text": " public delegate void ItemAddedHandler(object sender, ItemEventArgs e)\n [Browsable(true)]\n public event ItemAddedHandler ItemAdded;\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403/" ]
142,826
<p>I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread.</p> <p>I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework.</p> <p>Is there any good general purpose way to indefinitely pause a worker thread in C# .NET.</p> <p>I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case.</p>
[ { "answer_id": 143153, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 8, "selected": true, "text": "Thread.Suspend SuspendThread ResumeThread SuspendThread ManualResetEvent while (true)\n{\n _suspendEvent.WaitOne(Timeout.Infinite);\n\n // Do some work...\n}\n ManualResetEvent _suspendEvent = new ManualResetEvent(true);\n true _suspendEvent.Reset();\n _suspendEvent.Set();\n public class Worker\n{\n ManualResetEvent _shutdownEvent = new ManualResetEvent(false);\n ManualResetEvent _pauseEvent = new ManualResetEvent(true);\n Thread _thread;\n\n public Worker() { }\n\n public void Start()\n {\n _thread = new Thread(DoWork);\n _thread.Start();\n }\n\n public void Pause()\n {\n _pauseEvent.Reset();\n }\n\n public void Resume()\n {\n _pauseEvent.Set();\n }\n\n public void Stop()\n {\n // Signal the shutdown event\n _shutdownEvent.Set();\n\n // Make sure to resume any paused threads\n _pauseEvent.Set();\n\n // Wait for the thread to exit\n _thread.Join();\n }\n\n public void DoWork()\n {\n while (true)\n {\n _pauseEvent.WaitOne(Timeout.Infinite);\n\n if (_shutdownEvent.WaitOne(0))\n break;\n\n // Do the work here..\n }\n }\n}\n" }, { "answer_id": 11320956, "author": "Matthias", "author_id": 568266, "author_profile": "https://Stackoverflow.com/users/568266", "pm_score": 1, "selected": false, "text": "LoopingThread WaitForPause() WaitForStop() TimeBetween Start() Pause() Start() IDisposable public class LoopingThread\n{\n private readonly Action _loopedAction;\n private readonly AutoResetEvent _pauseEvent;\n private readonly AutoResetEvent _resumeEvent;\n private readonly AutoResetEvent _stopEvent;\n private readonly AutoResetEvent _waitEvent;\n\n private readonly Thread _thread;\n\n public LoopingThread (Action loopedAction)\n {\n _loopedAction = loopedAction;\n _thread = new Thread (Loop);\n _pauseEvent = new AutoResetEvent (false);\n _resumeEvent = new AutoResetEvent (false);\n _stopEvent = new AutoResetEvent (false);\n _waitEvent = new AutoResetEvent (false);\n }\n\n public void Start ()\n {\n _thread.Start();\n }\n\n public void Pause (int timeout = 0)\n {\n _pauseEvent.Set();\n _waitEvent.WaitOne (timeout);\n }\n\n public void Resume ()\n {\n _resumeEvent.Set ();\n }\n\n public void Stop (int timeout = 0)\n {\n _stopEvent.Set();\n _resumeEvent.Set();\n _thread.Join (timeout);\n }\n\n public void WaitForPause ()\n {\n Pause (Timeout.Infinite);\n }\n\n public void WaitForStop ()\n {\n Stop (Timeout.Infinite);\n }\n\n public int PauseBetween { get; set; }\n\n private void Loop ()\n {\n do\n {\n _loopedAction ();\n\n if (_pauseEvent.WaitOne (PauseBetween))\n {\n _waitEvent.Set ();\n _resumeEvent.WaitOne (Timeout.Infinite);\n }\n } while (!_stopEvent.WaitOne (0));\n }\n}\n" }, { "answer_id": 40420796, "author": "Alberto", "author_id": 2987314, "author_profile": "https://Stackoverflow.com/users/2987314", "pm_score": 2, "selected": false, "text": "Thread.Sleep(Timeout.Infinite);" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
142,830
<p>I have seen the other questions <em>but I am still not satisfied with the way this subject is covered</em>.</p> <p><strong>I would like to extract a distiled list of things to check on comments at a code inspection.</strong> </p> <p>I am sure people will say things that will just cancel each other. But hey, maybe we can build a list for each camp. For those who don't comment at all the list will just be very short :)</p>
[ { "answer_id": 142876, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 1, "selected": false, "text": "/**\n * Class to clean variables\n *\n * @package Majyk\n * @author Martin Meredith <martin@sourceguru.net>\n * @licence GPL (v2 or later)\n * @copyright Copyright (c) 2008 Martin Meredith <martin@sourceguru.net>\n * @version 0.1\n */\nclass Majyk_Filter\n{\n /**\n * Class Constants for Cleaning Types\n */\n const Integer = 1;\n const PositiveInteger = 2;\n const String = 3;\n const NoHTML = 4;\n const DBEscapeString = 5;\n const NotNegativeInteger = 6;\n\n /**\n * Do the cleaning\n *\n * @param integer Type of Cleaning (as defined by constants)\n * @param mixed Value to be cleaned\n *\n * @return mixed Cleaned Variable\n *\n */\n // Register the Auto-Loader\nspl_autoload_register(\"majyk_autoload\");\n\n// Add an Exception Handler.\nset_exception_handler(array('Majyk_ExceptionHandler', 'handle_exception'));\n\n// Turn Errors into Exceptions\nset_error_handler(array('Majyk_ExceptionHandler', 'error_to_exception'), E_ALL);\n\n// Add the generic Auto-Loader to the auto-loader stack\nspl_autoload_register(\"spl_autoload\"); \n" }, { "answer_id": 142879, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 0, "selected": false, "text": "assert" }, { "answer_id": 68090254, "author": "Alonso del Arte", "author_id": 9104070, "author_profile": "https://Stackoverflow.com/users/9104070", "pm_score": 0, "selected": false, "text": "TODO TODO TODO" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14921/" ]
142,844
<p>I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.</p> <p>Is there some kind of configuration that needs to be done somewhere for this work?</p>
[ { "answer_id": 142854, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 7, "selected": true, "text": "Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Python.File\\shellex\\DropHandler]\n@=\"{60254CA5-953B-11CF-8C96-00AA00B8708C}\"\n 86C86720-42A0-1069-A2E8-08002B30309D .pyw .pyc Python.NoConFile Python.CompiledFile" }, { "answer_id": 10246159, "author": "marco", "author_id": 1346520, "author_profile": "https://Stackoverflow.com/users/1346520", "pm_score": 5, "selected": false, "text": "file.bat \"C:\\python27\\python.exe\" yourprogram.py %*\n %* file.bat" }, { "answer_id": 45617351, "author": "halanson", "author_id": 1984396, "author_profile": "https://Stackoverflow.com/users/1984396", "pm_score": 4, "selected": false, "text": "import sys\ndroppedFile = sys.argv[1]\nprint droppedFile\n sys.argv[0] sys.argv[n+1]" }, { "answer_id": 65873279, "author": "Pedro Lobito", "author_id": 797495, "author_profile": "https://Stackoverflow.com/users/797495", "pm_score": 2, "selected": false, "text": ".py HKEY_CLASSES_ROOT\\.py Python.File HKEY_CLASSES_ROOT\\Python.File\\Shell\\Open Command \"C:\\Windows\\py.exe\" \"%1\" %* CLASSES_ROOT\\Applications\\py.exe\\open\\command \"C:\\Windows\\py.exe\" \"%1\" %* CLASSES_ROOT\\Python.File\\ShellEx DropHandler {86C86720-42A0-1069-A2E8-08002B30309D} import sys\n\nargs = sys.argv\nprint(args)\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4859/" ]
142,845
<p>I'm working on an application that consists of an overall Quartz-based scheduler and "CycledJob" run using CronTriggers. The purpose of the application is to process inputs from different email inboxes based on the source country. </p> <p>Based on the country that it comes in from (i.e. US, UK, FR, etc.) the application triggers one job thread to run each country's processing cycle, so there would be a UK Worker thread, one for US, France, etc. When formatting the output to log4j, I'm using the thread parameter, so it emits [ApplicationName_Worker-1], [ApplicationName_Worker-2] etc. Try as I might, I can't find a way to name the threads since they're pulled out of Quartz's Thread Pools. Although I could possibly go so far as to extend Quartz, I'd like to work out a different solution instead of messing with the standard library.</p> <p>Here's the problem: When using log4j, I'd like to have all log items from the US thread output to a US only file, likewise for each of the country threads. I don't care if they stay in one unified ConsoleAppender, the FileAppender split is what I'm after here. I already know how to specify multiple file appenders and such, my issue is I can't differentiate based on country. There are 20+ classes within the application that can be on the execution chain, very few of which I want to burden with the knowledge of passing an extra "context" parameter through EVERY method... I've considered a Strategy pattern extending a log4j wrapper class, but unless I can let every class in the chain know which thread it's on to parameterize the logger call, that seems impossible. Without being able to name the thread also creates a challenge (or else this would be easy!).</p> <p>So here's the question: What would be a suggested approach to allow many subordinate classes in an application that are each used for every different thread to process the input know that they are within the context of a particular country thread when they are logging?</p> <p>Good luck understanding, and please ask clarifying questions! I hope someone is able to help me figure out a decent way to tackle this. All suggestions welcome.</p>
[ { "answer_id": 143018, "author": "jt.", "author_id": 4362, "author_profile": "https://Stackoverflow.com/users/4362", "pm_score": 1, "selected": false, "text": "log4j.additivity.my-us-logger=false\n" }, { "answer_id": 144184, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "Job ...\npublic static final String MDC_COUNTRY = \"com.y.foo.Country\";\npublic void execute(JobExecutionContext context)\n /* Just guessing that you have the country in your JobContext. */\n MDC.put(MDC_COUNTRY, context.get(MDC_COUNTRY));\n try {\n /* Perform your job here. */\n ...\n } finally {\n MDC.remove(MDC_COUNTRY);\n }\n}\n...\n package com.y.log4j;\n\nimport org.apache.log4j.spi.LoggingEvent;\n\n/**\n * This is a general purpose filter. If its \"value\" property is null, \n * it requires only that the specified key be set in the MDC. If its \n * value is not null, it further requires that the value in the MDC \n * is equal.\n */\npublic final class ContextFilter extends org.apache.log4j.spi.Filter {\n\n public int decide(LoggingEvent event) {\n Object ctx = event.getMDC(key);\n if (value == null)\n return (ctx != null) ? NEUTRAL : DENY;\n else\n return value.equals(ctx) ? NEUTRAL : DENY;\n }\n\n private String key;\n private String value;\n\n public void setContextKey(String key) { this.key = key; }\n public String getContextKey() { return key; }\n public void setValue(String value) { this.value = value; }\n public String getValue() { return value; }\n\n}\n <appender name=\"fr\" class=\"org.apache.log4j.FileAppender\">\n <param name=\"file\" value=\"france.log\"/>\n ...\n <filter class=\"com.y.log4j.ContextFilter\">\n <param name=\"key\" value=\"com.y.foo.Country\" />\n <param name=\"value\" value=\"fr\" />\n </filter>\n</appender> \n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18402/" ]
142,855
<p>What programming languages support arbitrary precision arithmetic and could you give a short example of how to print an arbitrary number of digits?</p>
[ { "answer_id": 142866, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 3, "selected": false, "text": "from math import log as _flog\nfrom decimal import getcontext, Decimal\n\ndef log(x):\n if x < 0:\n return Decimal(\"NaN\")\n if x == 0:\n return Decimal(\"-inf\")\n getcontext().prec += 3\n eps = Decimal(\"10\")**(-getcontext().prec+2)\n # A good initial estimate is needed\n r = Decimal(repr(_flog(float(x))))\n while 1:\n r2 = r - 1 + x/exp(r)\n if abs(r2-r) < eps:\n break\n else:\n r = r2\n getcontext().prec -= 3\n return +r\n" }, { "answer_id": 142873, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 3, "selected": false, "text": "(format t \"~D~%\" (expt 7 77))\n" }, { "answer_id": 143328, "author": "Peter Hession", "author_id": 441, "author_profile": "https://Stackoverflow.com/users/441", "pm_score": 1, "selected": false, "text": " using java.math;\n\n namespace MyNamespace\n {\n class Program\n {\n static void Main(string[] args)\n {\n BigDecimal bd = new BigDecimal(\"12345678901234567890.1234567890123456789\");\n\n Console.WriteLine(bd.ToString());\n }\n }\n }\n" }, { "answer_id": 143347, "author": "Oli", "author_id": 15296, "author_profile": "https://Stackoverflow.com/users/15296", "pm_score": 2, "selected": false, "text": "77 VALUE PIC S9(4)V9(4). \n DCL VALUE DEC FIXED (4,4);\n" }, { "answer_id": 160352, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 4, "selected": false, "text": "N[Pi, 100]\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068\n" }, { "answer_id": 7886396, "author": "Antonio Garcia Marin", "author_id": 1012339, "author_profile": "https://Stackoverflow.com/users/1012339", "pm_score": 2, "selected": false, "text": "<?php\n\n$a = '1.234';\n$b = '5';\n\necho bcadd($a, $b); // 6\necho bcadd($a, $b, 4); // 6.2340\n\n?>\n" }, { "answer_id": 13884310, "author": "MikeM", "author_id": 1565512, "author_profile": "https://Stackoverflow.com/users/1565512", "pm_score": 2, "selected": false, "text": "Big.DP = 20; // Decimal Places\nvar pi = Big(355).div(113) \n\nconsole.log( pi.toString() ); // '3.14159292035398230088'\n" }, { "answer_id": 41543370, "author": "vonjd", "author_id": 468305, "author_profile": "https://Stackoverflow.com/users/468305", "pm_score": 2, "selected": false, "text": "library(Rmpfr)\nexp(mpfr(1, 120))\n## 1 'mpfr' number of precision 120 bits \n## [1] 2.7182818284590452353602874713526624979\n" }, { "answer_id": 67429986, "author": "jbyler", "author_id": 2562319, "author_profile": "https://Stackoverflow.com/users/2562319", "pm_score": 0, "selected": false, "text": "Prelude> 2 ^ 2 ^ 12\n1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190336\n show module Test where\n\nmain = do\n let x = 2 ^ 2 ^ 12\n let xStr = show x\n putStrLn xStr\n Num -- Define a function to make big numbers. The (inferred) type is generic.\nPrelude> superbig n = 2 ^ 2 ^ n\n\n-- We can call this function with different concrete types and get different results.\nPrelude> superbig 5 :: Int\n4294967296\nPrelude> superbig 5 :: Float\n4.2949673e9\n\n-- The `Int` type is not arbitrary precision, and we might overflow.\nPrelude> superbig 6 :: Int\n0\n\n-- `Double` can hold bigger numbers.\nPrelude> superbig 6 :: Double\n1.8446744073709552e19\nPrelude> superbig 9 :: Double\n1.3407807929942597e154\n\n-- But it is also not arbitrary precision, and can still overflow.\nPrelude> superbig 10 :: Double\nInfinity\n\n-- The Integer type is arbitrary-precision though, and can go as big as we have memory for and patience to wait for the result.\nPrelude> superbig 12 :: Integer\n1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190336\n\n-- If we don't specify a type, Haskell will infer one with arbitrary precision.\nPrelude> superbig 12\n1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190336\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577/" ]
142,863
<p><em>Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate? I also believe the question, detail, and response is much better than the referenced question.</em></p> <p>I've been a C++ programmer for quite a while but I'm new to Java and new to Eclipse. I want to use the <a href="http://sourceforge.net/project/showfiles.php?group_id=30469&amp;package_id=23976" rel="nofollow noreferrer">touch graph "Graph Layout" code</a> to visualize some data I'm working with.</p> <p>This code is organized like this:</p> <pre><code>./com ./com/touchgraph ./com/touchgraph/graphlayout ./com/touchgraph/graphlayout/Edge.java ./com/touchgraph/graphlayout/GLPanel.java ./com/touchgraph/graphlayout/graphelements ./com/touchgraph/graphlayout/graphelements/GESUtils.java ./com/touchgraph/graphlayout/graphelements/GraphEltSet.java ./com/touchgraph/graphlayout/graphelements/ImmutableGraphEltSet.java ./com/touchgraph/graphlayout/graphelements/Locality.java ./com/touchgraph/graphlayout/graphelements/TGForEachEdge.java ./com/touchgraph/graphlayout/graphelements/TGForEachNode.java ./com/touchgraph/graphlayout/graphelements/TGForEachNodePair.java ./com/touchgraph/graphlayout/graphelements/TGNodeQueue.java ./com/touchgraph/graphlayout/graphelements/VisibleLocality.java ./com/touchgraph/graphlayout/GraphLayoutApplet.java ./com/touchgraph/graphlayout/GraphListener.java ./com/touchgraph/graphlayout/interaction ./com/touchgraph/graphlayout/interaction/DragAddUI.java ./com/touchgraph/graphlayout/interaction/DragMultiselectUI.java ./com/touchgraph/graphlayout/interaction/DragNodeUI.java ./com/touchgraph/graphlayout/interaction/GLEditUI.java ./com/touchgraph/graphlayout/interaction/GLNavigateUI.java ./com/touchgraph/graphlayout/interaction/HVRotateDragUI.java ./com/touchgraph/graphlayout/interaction/HVScroll.java ./com/touchgraph/graphlayout/interaction/HyperScroll.java ./com/touchgraph/graphlayout/interaction/LocalityScroll.java ./com/touchgraph/graphlayout/interaction/RotateScroll.java ./com/touchgraph/graphlayout/interaction/TGAbstractClickUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractDragUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMouseMotionUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMousePausedUI.java ./com/touchgraph/graphlayout/interaction/TGSelfDeactivatingUI.java ./com/touchgraph/graphlayout/interaction/TGUIManager.java ./com/touchgraph/graphlayout/interaction/TGUserInterface.java ./com/touchgraph/graphlayout/interaction/ZoomScroll.java ./com/touchgraph/graphlayout/LocalityUtils.java ./com/touchgraph/graphlayout/Node.java ./com/touchgraph/graphlayout/TGAbstractLens.java ./com/touchgraph/graphlayout/TGException.java ./com/touchgraph/graphlayout/TGLayout.java ./com/touchgraph/graphlayout/TGLensSet.java ./com/touchgraph/graphlayout/TGPaintListener.java ./com/touchgraph/graphlayout/TGPanel.java ./com/touchgraph/graphlayout/TGPoint2D.java ./com/touchgraph/graphlayout/TGScrollPane.java ./TG-APACHE-LICENSE.txt ./TGGL ReleaseNotes.txt ./TGGraphLayout.html ./TGGraphLayout.jar </code></pre> <p>How do I add this project in Eclipse and get it compiling and running quickly?</p>
[ { "answer_id": 142881, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 5, "selected": true, "text": "./com/* /src jar /lib TGGL jar /src jar files /lib right click jar file Build Path->Add" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22917/" ]
142,868
<p>How do I change Oracle from port 8080? My Eclipse is using 8080, so I can't use that.</p>
[ { "answer_id": 143090, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 1, "selected": false, "text": "<web-site xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:noNamespaceSchemaLocation=\"http://xmlns.oracle.com/oracleas/schema/web-site-10_0.xsd\"\nport=\"8888\" display-name=\"OC4J 10g (10.1.3) Default Web Site\"\nschema-major-version=\"10\" schema-minor-version=\"0\" > \n" }, { "answer_id": 1011180, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "SQL> -- set http port\nSQL> begin\n 2 dbms_xdb.sethttpport('9090');\n 3 end;\n 4 /\n" }, { "answer_id": 4097449, "author": "Nigel_V_Thomas", "author_id": 192040, "author_profile": "https://Stackoverflow.com/users/192040", "pm_score": 3, "selected": false, "text": "Exec DBMS_XDB.SETHTTPPORT(8181);" }, { "answer_id": 11839354, "author": "susheel", "author_id": 1580852, "author_profile": "https://Stackoverflow.com/users/1580852", "pm_score": 8, "selected": false, "text": "C:\\>sqlplus /nolog\nSQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008\nCopyright (c) 1982, 2005, Oracle. All rights reserved.\n\nSQL> connect\nEnter user-name: system\nEnter password: <enter password if will not be visible>\nConnected.\n\nSQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port] \nPL/SQL procedure successfully completed.\n\nSQL>quit \n" }, { "answer_id": 35176566, "author": "Hareesh Chowdary", "author_id": 3559196, "author_profile": "https://Stackoverflow.com/users/3559196", "pm_score": 4, "selected": false, "text": "Run SQL Command Line" }, { "answer_id": 57443244, "author": "Lova Chittumuri", "author_id": 5256337, "author_profile": "https://Stackoverflow.com/users/5256337", "pm_score": 0, "selected": false, "text": "begin\ndbms_xdb.sethttpport('Your Port Number');\nend;\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22916/" ]
142,877
<p>I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore. </p> <p>There are several places in the codebase where it would clean up the code substantially if only there were a way to make the pre-processor ignore certain <code>#includes</code> if the file didn't exist in the current folder. Does anyone know a way to achieve that?</p> <p>Presently, we use an <code>#ifdef</code> around the <code>#include</code> in the shared file, with a second project-specific file that #defines whether or not the <code>#include</code> exists in the project. This works, but it's ugly. People often forget to properly update the definitions when they add or remove files from the project. I've contemplated writing a pre-build tool to keep this file up to date, but if there's a platform-independent way to do this with the preprocessor I'd much rather do it that way instead. Any ideas?</p>
[ { "answer_id": 142884, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "#define EXISTS_FILE1_C\n#define EXISTS_FILE1_H\n#define EXISTS_FILE2_C\n EXISTS_*" }, { "answer_id": 142921, "author": "Logan", "author_id": 3518, "author_profile": "https://Stackoverflow.com/users/3518", "pm_score": 6, "selected": true, "text": "cat > .test.h <<'EOM'\n#include <asdf.h>\nEOM\nif gcc -E .test.h\n then\n echo '#define HAVE_ASDF_H 1' >> config.h\n else \n echo '#ifdef HAVE_ASDF_H' >> config.h\n echo '# undef HAVE_ASDF_H' >> config.h\n echo '#endif' >> config.h\n fi\n" }, { "answer_id": 142926, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 4, "selected": false, "text": "ifdef $(test -f filename && echo \"present\")\n DEFINE=-DFILENAME_PRESENT\nendif\n" }, { "answer_id": 142934, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 2, "selected": false, "text": "foo.o: foo.c\n if [ -f header1.h ]; then CFLAGS+=-DHEADER1_INC\n #ifdef HEADER1_INC\n#include <header1.h>\n#endif\n" }, { "answer_id": 142995, "author": "eugensk", "author_id": 17495, "author_profile": "https://Stackoverflow.com/users/17495", "pm_score": 6, "selected": false, "text": "#define header1_is_missing\n #include <header1.h>\n#ifdef header1_is_missing\n\n // there is no header1.h \n\n#endif\n" }, { "answer_id": 1073873, "author": "Ahmad Mushtaq", "author_id": 35065, "author_profile": "https://Stackoverflow.com/users/35065", "pm_score": 1, "selected": false, "text": "@echo off\n\nIF EXIST [\\epoc32\\include\\domain\\middleware\\file_strange] GOTO NEW_API\nGOTO OLD_API\nGOTO :EOF\n\n:NEW_API\necho.#define NEW_API_SUPPORTED>../inc/file_strange_supported.h\nGOTO :EOF\n\n:OLD_API\necho.#define OLD_API_SUPPORTED>../inc/file_strange_supported.h\nGOTO :EOF\n do_nothing :\n @rem do_nothing\n\nMAKMAKE : \n check.bat\n\nBLD : do_nothing\n\nCLEAN : do_nothing\n\nLIB : do_nothing\n\nCLEANLIB : do_nothing\n\nRESOURCE : do_nothing\n\nFREEZE : do_nothing\n\nSAVESPACE : do_nothing\n\nRELEASABLES : do_nothing\n\nFINAL : do_nothing\n PRJ_MMPFILES\ngnumakefile checkmedialist.mk\n file_strange_supported.h #include \"../inc/file_strange_supported.h\"\n#ifdef NEW_API_SUPPORTED\nLIBRARY newapi.lib\n#else\nLIBRARY oldapi.lib\n#endif\n #include \"../inc/file_strange_supported.h\"\n#ifdef NEW_API_SUPPORTED\nCStrangeApi* api = Api::NewLC();\n#else\n// ..\n#endif\n" }, { "answer_id": 33260104, "author": "Setepenre", "author_id": 2721950, "author_profile": "https://Stackoverflow.com/users/2721950", "pm_score": 7, "selected": false, "text": "__has_include ( header-name ) // Note the two possible file name string formats.\n#if __has_include(\"myinclude.h\") && __has_include(<stdint.h>)\n# include \"myinclude.h\"\n#endif\n" }, { "answer_id": 52275443, "author": "Christoph Lipka", "author_id": 8178357, "author_profile": "https://Stackoverflow.com/users/8178357", "pm_score": 2, "selected": false, "text": "__has_include" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
142,903
<p>I started playing around with Linq today and ran into a problem I couldn't find an answer to. I was querying a simple SQL Server database that had some employee records. One of the fields is the full name (cn). I thought it would be interesting to group by the first name by splitting the full name at the first space. I tried</p> <pre><code>group by person.cn.Split(separators)[0] </code></pre> <p>but ran into a lengthy runtime exception (looked a lot like a C++ template instantiation error).</p> <p>Then I tried grouping by a few letters of the first name:</p> <pre><code>group by person.cn.Substring(0,5) </code></pre> <p>and that worked fine but is not what I want.</p> <p>I'm wondering about two things:</p> <ul> <li>Why does the first example not work when it looks so close to the second?</li> <li>Knowing that behind the scenes it's SQL stuff going on, what's a good way to do this kind of thing efficiently</li> </ul> <p>Thanks,</p> <p>Andrew</p>
[ { "answer_id": 143078, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "string oneSpace = \" \";\nstring fiftySpace = \" \";\n\nvar query = \n from person in db.Persons\n let lastname = person.cn.Replace(oneSpace, fiftySpace).SubString(0, 50).Trim()\n group person by lastname into g\n select new { Key = g.Key, Count = g.Count };\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18321/" ]
142,944
<p>I remember seeing the code for a Highpass filter a few days back somewhere in the samples, however I can't find it anywhere now! Could someone remember me where the Highpass filter implementation code was?</p> <p>Or better yet post the algorithm?</p> <p>Thanks!</p>
[ { "answer_id": 142962, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 6, "selected": true, "text": "#define kFilteringFactor 0.1\nstatic UIAccelerationValue rollingX=0, rollingY=0, rollingZ=0;\n\n\n- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {\n\n // Calculate low pass values\n\n rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));\n rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor));\n rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor));\n\n // Subtract the low-pass value from the current value to get a simplified high-pass filter\n\n float accelX = acceleration.x - rollingX;\n float accelY = acceleration.y - rollingY;\n float accelZ = acceleration.z - rollingZ;\n\n // Use the acceleration data.\n\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
142,965
<p>An existing Java site is designed to run under "/" on tomcat and there are many specific references to fixed absolute paths like "/dir/dir/page".</p> <p>Want to migrate this to Java EE packaging, where the site will need to run under a context-root e.g. "/dir/dir/page" becomes "/my-context-root/dir/dir/page"</p> <p>Now, the context-root can be easily with ServletRequest.getContextPath(), but that still means a lot of code changes to migrate a large code base. Most of these references are in literal HTML.</p> <p>I've experimented with using servlet filters to do rewrites on the oubound HTML, and that seems to work fine. But it does introduce some overhead, and I wouldn't see it as a permanent solution. (see <a href="http://github.com/tardate/sources/tree/master%2FEnforceContextRootFilter-1.0-src.zip?raw=true" rel="nofollow noreferrer">EnforceContextRootFilter-1.0-src.zip</a> for the servlet filter approach).</p> <p>Are there any better approaches to solving this problem? Anything obvious I'm missing? All comments appreciated!</p>
[ { "answer_id": 143136, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 2, "selected": true, "text": "sed -e 's/<a/<t:a/g' -e 's/<\\/a>/<\\/t:a>/g' old/x.jsp > new/x.jsp\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6329/" ]
142,972
<p>I have a series of ASCII flat files coming in from a mainframe to be processed by a C# application. A new feed has been introduced with a Packed Decimal (COMP-3) field, which needs to be converted to a numerical value.</p> <p>The files are being transferred via FTP, using ASCII transfer mode. I am concerned that the binary field may contain what will be interpreted as very-low ASCII codes or control characters instead of a value - Or worse, may be lost in the FTP process.</p> <p>What's more, the fields are being read as strings. I may have the flexibility to work around this part (i.e. a stream of some sort), but the business will give me pushback.</p> <p>The requirement read "Convert from HEX to ASCII", but clearly that didn't yield the correct values. Any help would be appreciated; it need not be language-specific as long as you can explain the logic of the conversion process.</p>
[ { "answer_id": 143001, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 2, "selected": false, "text": "Imports System\nImports System.IO\nImports System.Text\nImports System.Text.Encoding\n\n\n\n'4/20/07 submission includes a line spacing addition when a control character is used:\n' The line spacing is calculated off of the 3rd control character.\n'\n' Also includes the 4/18 modification of determining end of file.\n\n'4/26/07 submission inclues an addition of 6 to the record length when the 4th control\n' character is an 8. This is because these records were being truncated.\n\n\n'Authored by Gary A. Lima, aka. VBRocks\n\n\n\n''' <summary>\n''' Translates an EBCDIC file to an ASCII file.\n''' </summary>\n''' <remarks></remarks>\nPublic Class EBCDIC_to_ASCII_Translator\n\n#Region \" Example\"\n\n Private Sub Example()\n 'Set your source file and destination file paths\n Dim sSourcePath As String = \"c:\\Temp\\MyEBCDICFile\"\n Dim sDestinationPath As String = \"c:\\Temp\\TranslatedFile.txt\"\n\n Dim trans As New EBCDIC_to_ASCII_Translator()\n\n 'If your EBCDIC file uses Control records to determine the length of a record, then this to True\n trans.UseControlRecord = True\n\n 'If the first record of your EBCDIC file is filler (junk), then set this to True\n trans.IgnoreFirstRecord = True\n\n 'EBCDIC files are written in block lengths, set your block length (Example: 134, 900, Etc.)\n trans.BlockLength = 900\n\n 'This method will actually translate your source file and output it to the specified destination file path\n trans.TranslateFile(sSourcePath, sDestinationPath)\n\n\n 'Here is a alternate example:\n 'No Control record is used\n 'trans.UseControlRecord = False\n\n 'Translate the whole file, including the first record\n 'trans.IgnoreFirstRecord = False\n\n 'Set the block length\n 'trans.BlockLength = 134\n\n 'Translate...\n 'trans.TranslateFile(sSourcePath, sDestinationPath)\n\n\n\n '*** Some additional methods that you can use are:\n\n 'Trim off leading characters from left side of string (position 0 to...)\n 'trans.LTrim = 15\n\n 'Translate 1 EBCDIC character to an ASCII character\n 'Dim strASCIIChar as String = trans.TranslateCharacter(\"S\")\n\n 'Translate an EBCDIC character array to an ASCII string\n 'trans.TranslateCharacters(chrEBCDICArray)\n\n 'Translates an EBCDIC string to an ASCII string\n 'Dim strASCII As String = trans.TranslateString(\"EBCDIC String\")\n\n\n End Sub\n\n#End Region 'Example\n\n 'Translate characters from EBCDIC to ASCII\n\n Private ASCIIEncoding As Encoding = Encoding.ASCII\n Private EBCDICEncoding As Encoding = Encoding.GetEncoding(37) 'EBCDIC\n\n 'Block Length: Can be fixed (Ex: 134). \n Private miBlockLength As Integer = 0\n Private mbUseControlRec As Boolean = True 'If set to False, will return exact block length\n Private mbIgnoreFirstRecord As Boolean = True 'Will Ignore first record if set to true (First record may be filler)\n Private miLTrim As Integer = 0\n\n ''' <summary>\n ''' Translates SourceFile from EBCDIC to ASCII. Writes output to file path specified by DestinationFile parameter.\n ''' Set the BlockLength Property to designate block size to read.\n ''' </summary>\n ''' <param name=\"SourceFile\">Enter the path of the Source File.</param>\n ''' <param name=\"DestinationFile\">Enter the path of the Destination File.</param>\n ''' <remarks></remarks>\n Public Sub TranslateFile(ByVal SourceFile As String, ByVal DestinationFile As String)\n\n Dim iRecordLength As Integer 'Stores length of a record, not including the length of the Control Record (if used)\n Dim sRecord As String = \"\" 'Stores the actual record\n Dim iLineSpace As Integer = 1 'LineSpace: 1 for Single Space, 2 for Double Space, 3 for Triple Space...\n\n Dim iControlPosSix As Byte() 'Stores the 6th character of a Control Record (used to calculate record length)\n Dim iControlRec As Byte() 'Stores the EBCDIC Control Record (First 6 characters of record)\n Dim bEOR As Boolean 'End of Record Flag\n Dim bBOF As Boolean = True 'Beginning of file\n Dim iConsumedChars As Integer = 0 'Stores the number of consumed characters in the current block\n Dim bIgnoreRecord As Boolean = mbIgnoreFirstRecord 'Ignores the first record if set.\n\n Dim ControlArray(5) As Char 'Stores Control Record (first 6 bytes)\n Dim chrArray As Char() 'Stores characters just after read from file\n\n Dim sr As New StreamReader(SourceFile, EBCDICEncoding)\n Dim sw As New StreamWriter(DestinationFile)\n\n 'Set the RecordLength to the RecordLength Property (below)\n iRecordLength = miBlockLength\n\n 'Loop through entire file\n Do Until sr.EndOfStream = True\n\n 'If using a Control Record, then check record for valid data.\n If mbUseControlRec = True Then\n 'Read the Control Record (first 6 characters of the record)\n sr.ReadBlock(ControlArray, 0, 6)\n\n 'Update the value of consumed (read) characters\n iConsumedChars += ControlArray.Length\n\n 'Get the bytes of the Control Record Array\n iControlRec = EBCDICEncoding.GetBytes(ControlArray)\n\n 'Set the line spacing (position 3 divided by 64)\n ' (64 decimal = Single Spacing; 128 decimal = Double Spacing)\n iLineSpace = iControlRec(2) / 64\n\n\n 'Check the Control record for End of File\n 'If the Control record has a 8 or 10 in position 1, and a 1 in postion 2, then it is the end of the file\n If (iControlRec(0) = 8 OrElse iControlRec(0) = 10) AndAlso _\n iControlRec(1) = 1 Then\n\n If bBOF = False Then\n Exit Do\n\n Else\n 'The Beginning of file flag is set to true by default, so when the first\n ' record is encountered, it is bypassed and the bBOF flag is set to False\n bBOF = False\n\n End If 'If bBOF = Fals\n\n End If 'If (iControlRec(0) = 8 OrElse\n\n\n\n 'Set the default value for the End of Record flag to True\n ' If the Control Record has all zeros, then it's True, else False\n bEOR = True\n\n 'If the Control record contains all zeros, bEOR will stay True, else it will be set to False\n For i As Integer = 0 To 5\n If iControlRec(i) > 0 Then\n bEOR = False\n\n Exit For\n\n End If 'If iControlRec(i) > 0\n\n Next 'For i As Integer = 0 To 5\n\n If bEOR = False Then\n 'Convert EBCDIC character to ASCII\n 'Multiply the 6th byte by 6 to get record length\n ' Why multiply by 6? Because it works.\n iControlPosSix = EBCDICEncoding.GetBytes(ControlArray(5))\n\n 'If the 4th position of the control record is an 8, then add 6\n ' to the record length to pick up remaining characters.\n If iControlRec(3) = 8 Then\n iRecordLength = CInt(iControlPosSix(0)) * 6 + 6\n\n Else\n iRecordLength = CInt(iControlPosSix(0)) * 6\n\n End If\n\n 'Add the length of the record to the Consumed Characters counter\n iConsumedChars += iRecordLength\n\n Else\n 'If the Control Record had all zeros in it, then it is the end of the Block.\n\n 'Consume the remainder of the block so we can continue at the beginning of the next block.\n ReDim chrArray(miBlockLength - iConsumedChars - 1)\n 'ReDim chrArray(iRecordLength - iConsumedChars - 1)\n\n 'Consume (read) the remaining characters in the block. \n ' We are not doing anything with them because they are not actual records.\n 'sr.ReadBlock(chrArray, 0, iRecordLength - iConsumedChars)\n sr.ReadBlock(chrArray, 0, miBlockLength - iConsumedChars)\n\n 'Reset the Consumed Characters counter\n iConsumedChars = 0\n\n 'Set the Record Length to 0 so it will not be processed below.\n iRecordLength = 0\n\n End If ' If bEOR = False\n\n End If 'If mbUseControlRec = True\n\n\n\n If iRecordLength > 0 Then\n 'Resize our array, dumping previous data. Because Arrays are Zero (0) based, subtract 1 from the Record length.\n ReDim chrArray(iRecordLength - 1)\n\n 'Read the specfied record length, without the Control Record, because we already consumed (read) it.\n sr.ReadBlock(chrArray, 0, iRecordLength)\n\n 'Copy Character Array to String Array, Converting in the process, then Join the Array to a string\n sRecord = Join(Array.ConvertAll(chrArray, New Converter(Of Char, String)(AddressOf ChrToStr)), \"\")\n\n 'If the record length was 0, then the Join method may return Nothing\n If IsNothing(sRecord) = False Then\n\n If bIgnoreRecord = True Then\n 'Do nothing - bypass record\n\n 'Reset flag\n bIgnoreRecord = False\n\n Else\n 'Write the line out, LTrimming the specified number of characters.\n If sRecord.Length >= miLTrim Then\n sw.WriteLine(sRecord.Remove(0, miLTrim))\n\n Else\n sw.WriteLine(sRecord.Remove(0, sRecord.Length))\n\n End If ' If sRecord.Length >= miLTrim\n\n 'Write out the number of blank lines specified by the 3rd control character.\n For i As Integer = 1 To iLineSpace - 1\n sw.WriteLine(\"\")\n\n Next 'For i As Integer = 1 To iLineSpace\n\n End If 'If bIgnoreRecord = True\n\n\n 'Obviously, if we have read more characters from the file than the designated size of the block,\n ' then subtract the number of characters we have read into the next block from the block size.\n If iConsumedChars > miBlockLength Then\n 'If iConsumedChars > iRecordLength Then\n iConsumedChars = iConsumedChars - miBlockLength\n 'iConsumedChars = iConsumedChars - iRecordLength\n\n End If\n\n End If 'If IsNothing(sRecord) = False\n\n End If 'If iRecordLength > 0\n\n 'Allow computer to process (works in a class module, not in a dll)\n 'Application.DoEvents()\n\n Loop\n\n 'Destroy StreamReader (sr)\n sr.Close()\n sr.Dispose()\n\n 'Destroy StreamWriter (sw)\n sw.Close()\n sw.Dispose()\n\n End Sub\n\n\n\n ''' <summary>\n ''' Translates 1 EBCDIC Character (Char) to an ASCII String\n ''' </summary>\n ''' <param name=\"chr\"></param>\n ''' <returns></returns>\n ''' <remarks></remarks>\n Private Function ChrToStr(ByVal chr As Char) As String\n Dim sReturn As String = \"\"\n\n 'Convert character into byte\n Dim EBCDICbyte As Byte() = EBCDICEncoding.GetBytes(chr)\n\n 'Convert EBCDIC byte to ASCII byte\n Dim ASCIIByte As Byte() = Encoding.Convert(EBCDICEncoding, ASCIIEncoding, EBCDICbyte)\n\n sReturn = Encoding.ASCII.GetString(ASCIIByte)\n\n Return sReturn\n\n End Function\n\n\n\n ''' <summary>\n ''' Translates an EBCDIC String to an ASCII String\n ''' </summary>\n ''' <param name=\"sStringToTranslate\"></param>\n ''' <returns>String</returns>\n ''' <remarks></remarks>\n Public Function TranslateString(ByVal sStringToTranslate As String) As String\n Dim i As Integer = 0\n Dim sReturn As New System.Text.StringBuilder()\n\n 'Loop through the string and translate each character\n For i = 0 To sStringToTranslate.Length - 1\n sReturn.Append(ChrToStr(sStringToTranslate.Substring(i, 1)))\n\n Next\n\n Return sReturn.ToString()\n\n\n End Function\n\n\n\n ''' <summary>\n ''' Translates 1 EBCDIC Character (Char) to an ASCII String\n ''' </summary>\n ''' <param name=\"sCharacterToTranslate\"></param>\n ''' <returns>String</returns>\n ''' <remarks></remarks>\n Public Function TranslateCharacter(ByVal sCharacterToTranslate As Char) As String\n\n Return ChrToStr(sCharacterToTranslate)\n\n End Function\n\n\n\n ''' <summary>\n ''' Translates an EBCDIC Character (Char) Array to an ASCII String\n ''' </summary>\n ''' <param name=\"sCharacterArrayToTranslate\"></param>\n ''' <returns>String</returns>\n ''' <remarks>Remarks</remarks>\n Public Function TranslateCharacters(ByVal sCharacterArrayToTranslate As Char()) As String\n Dim sReturn As String = \"\"\n\n 'Copy Character Array to String Array, Converting in the process, then Join the Array to a string\n sReturn = Join(Array.ConvertAll(sCharacterArrayToTranslate, _\n New Converter(Of Char, String)(AddressOf ChrToStr)), \"\")\n\n Return sReturn\n\n End Function\n\n\n ''' <summary>\n ''' Block Length must be set. You can set the BlockLength for specific block sizes (Ex: 134).\n ''' Set UseControlRecord = False for files with specific block sizes (Default is True)\n ''' </summary>\n ''' <value>0</value>\n ''' <returns>Integer</returns>\n ''' <remarks></remarks>\n Public Property BlockLength() As Integer\n Get\n Return miBlockLength\n\n End Get\n Set(ByVal value As Integer)\n miBlockLength = value\n\n End Set\n End Property\n\n\n\n ''' <summary>\n ''' Determines whether a ControlKey is used to calculate RecordLength of valid data\n ''' </summary>\n ''' <value>Default value is True</value>\n ''' <returns>Boolean</returns>\n ''' <remarks></remarks>\n Public Property UseControlRecord() As Boolean\n Get\n Return mbUseControlRec\n\n End Get\n Set(ByVal value As Boolean)\n mbUseControlRec = value\n\n End Set\n End Property\n\n\n\n ''' <summary>\n ''' Ignores first record if set (Default is True)\n ''' </summary>\n ''' <value>Default is True</value>\n ''' <returns>Boolean</returns>\n ''' <remarks></remarks>\n Public Property IgnoreFirstRecord() As Boolean\n Get\n Return mbIgnoreFirstRecord\n\n End Get\n\n Set(ByVal value As Boolean)\n mbIgnoreFirstRecord = value\n\n End Set\n End Property\n\n\n\n ''' <summary>\n ''' Trims the left side of every string the specfied number of characters. Default is 0.\n ''' </summary>\n ''' <value>Default is 0.</value>\n ''' <returns>Integer</returns>\n ''' <remarks></remarks>\n Public Property LTrim() As Integer\n Get\n Return miLTrim\n\n End Get\n\n Set(ByVal value As Integer)\n miLTrim = value\n\n End Set\n End Property\n\n\nEnd Class\n" }, { "answer_id": 143024, "author": "Paul Keister", "author_id": 19500, "author_profile": "https://Stackoverflow.com/users/19500", "pm_score": 4, "selected": true, "text": "Imports Microsoft.VisualBasic\n\nModule Module1\n\n'Sample COMP-3 conversion code\n'Adapted from http://support.microsoft.com/kb/65323\n'This code has not been tested\n\nSub Main()\n\n Dim Digits%(15) 'Holds the digits for each number (max = 16).\n Dim Basiceqv#(1000) 'Holds the Basic equivalent of each COMP-3 number.\n\n 'Added to make code compile\n Dim MyByte As Char, HighPower%, HighNibble%\n Dim LowNibble%, Digit%, E%, Decimal%, FileName$\n\n\n 'Clear the screen, get the filename and the amount of decimal places\n 'desired for each number, and open the file for sequential input:\n FileName$ = InputBox(\"Enter the COBOL data file name: \")\n Decimal% = InputBox(\"Enter the number of decimal places desired: \")\n\n FileOpen(1, FileName$, OpenMode.Binary)\n\n Do Until EOF(1) 'Loop until the end of the file is reached.\n Input(1, MyByte)\n If MyByte = Chr(0) Then 'Check if byte is 0 (ASC won't work on 0).\n Digits%(HighPower%) = 0 'Make next two digits 0. Increment\n Digits%(HighPower% + 1) = 0 'the high power to reflect the\n HighPower% = HighPower% + 2 'number of digits in the number\n 'plus 1.\n Else\n HighNibble% = Asc(MyByte) \\ 16 'Extract the high and low\n LowNibble% = Asc(MyByte) And &HF 'nibbles from the byte. The\n Digits%(HighPower%) = HighNibble% 'high nibble will always be a\n 'digit.\n If LowNibble% <= 9 Then 'If low nibble is a\n 'digit, assign it and\n Digits%(HighPower% + 1) = LowNibble% 'increment the high\n HighPower% = HighPower% + 2 'power accordingly.\n Else\n HighPower% = HighPower% + 1 'Low nibble was not a digit but a\n Digit% = 0 '+ or - signals end of number.\n\n 'Start at the highest power of 10 for the number and multiply\n 'each digit by the power of 10 place it occupies.\n For Power% = (HighPower% - 1) To 0 Step -1\n Basiceqv#(E%) = Basiceqv#(E%) + (Digits%(Digit%) * (10 ^ Power%))\n Digit% = Digit% + 1\n Next\n\n 'If the sign read was negative, make the number negative.\n If LowNibble% = 13 Then\n Basiceqv#(E%) = Basiceqv#(E%) - (2 * Basiceqv#(E%))\n End If\n\n 'Give the number the desired amount of decimal places, print\n 'the number, increment E% to point to the next number to be\n 'converted, and reinitialize the highest power.\n Basiceqv#(E%) = Basiceqv#(E%) / (10 ^ Decimal%)\n Print(Basiceqv#(E%))\n E% = E% + 1\n HighPower% = 0\n End If\n End If\n Loop\n\n FileClose() 'Close the COBOL data file, and end.\nEnd Sub\n\nEnd Module\n" }, { "answer_id": 1465911, "author": "bubbassauro", "author_id": 1328, "author_profile": "https://Stackoverflow.com/users/1328", "pm_score": 0, "selected": false, "text": "// 500 is the code page for IBM EBCDIC International \nSystem.Text.Encoding enc = new System.Text.Encoding(500);\nstring value = enc.GetString(byteArrayField);\n" }, { "answer_id": 10200388, "author": "John", "author_id": 1339951, "author_profile": "https://Stackoverflow.com/users/1339951", "pm_score": 3, "selected": false, "text": " private Decimal Unpack(byte[] inp, int scale)\n {\n long lo = 0;\n long mid = 0;\n long hi = 0;\n bool isNegative;\n\n // this nybble stores only the sign, not a digit. \n // \"C\" hex is positive, \"D\" hex is negative, and \"F\" hex is unsigned. \n switch (nibble(inp, 0))\n {\n case 0x0D:\n isNegative = true;\n break;\n case 0x0F:\n case 0x0C:\n isNegative = false;\n break;\n default:\n throw new Exception(\"Bad sign nibble\");\n }\n long intermediate;\n long carry;\n long digit;\n for (int j = inp.Length * 2 - 1; j > 0; j--)\n {\n // multiply by 10\n intermediate = lo * 10;\n lo = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n intermediate = mid * 10 + carry;\n mid = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n intermediate = hi * 10 + carry;\n hi = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n // By limiting input length to 14, we ensure overflow will never occur\n\n digit = nibble(inp, j);\n if (digit > 9)\n {\n throw new Exception(\"Bad digit\");\n }\n intermediate = lo + digit;\n lo = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n if (carry > 0)\n {\n intermediate = mid + carry;\n mid = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n if (carry > 0)\n {\n intermediate = hi + carry;\n hi = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n // carry should never be non-zero. Back up with validation\n }\n }\n }\n return new Decimal((int)lo, (int)mid, (int)hi, isNegative, (byte)scale);\n }\n\n private int nibble(byte[] inp, int nibbleNo)\n {\n int b = inp[inp.Length - 1 - nibbleNo / 2];\n return (nibbleNo % 2 == 0) ? (b & 0x0000000F) : (b >> 4);\n }\n" }, { "answer_id": 62224734, "author": "Sathyaraj Palanisamy", "author_id": 1693613, "author_profile": "https://Stackoverflow.com/users/1693613", "pm_score": 0, "selected": false, "text": " using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n using System.Threading.Tasks;\n\n namespace ConsoleApp2\n {\n class Program\n {\n static void Main(string[] args)\n {\n var path = @\"C:\\FileName.BIN.dat\";\n var templates = new List<Template>\n {\n new Template{StartPos=1,CharLength=4,Type=\"AlphaNum\"},\n new Template{StartPos=5,CharLength=1,Type=\"AlphaNum\"},\n new Template{StartPos=6,CharLength=8,Type=\"AlphaNum\"},\n new Template{StartPos=14,CharLength=1,Type=\"AlphaNum\"},\n new Template{StartPos=46,CharLength=4,Type=\"Packed\",DecimalPlace=2},\n new Template{StartPos=54,CharLength=5,Type=\"Packed\",DecimalPlace=0},\n new Template{StartPos=60,CharLength=4,Type=\"Packed\",DecimalPlace=2},\n new Template{StartPos=64,CharLength=1,Type=\"AlphaNum\"}\n };\n\n var allBytes = File.ReadAllBytes(path);\n for (int i = 0; i < allBytes.Length; i += 66)\n {\n var IsLastline = (allBytes.Length - i) < 66;\n var lineLength = IsLastline ? 64 : 66;\n byte[] lineBytes = new byte[lineLength];\n Array.Copy(allBytes, i, lineBytes, 0, lineLength);\n\n\n var outArray = new string[templates.Count];\n int index = 0;\n foreach (var temp in templates)\n {\n byte[] amoutBytes = new byte[temp.CharLength];\n Array.Copy(lineBytes, temp.StartPos - 1, amoutBytes, 0, \n temp.CharLength);\n var final = \"\";\n if (temp.Type == \"Packed\")\n {\n final = Unpack(amoutBytes, temp.DecimalPlace).ToString();\n }\n else\n {\n final = ConvertEbcdicString(amoutBytes);\n }\n\n outArray[index] = final;\n index++;\n\n }\n\n Console.WriteLine(string.Join(\" \", outArray));\n\n }\n\n Console.ReadLine();\n }\n\n\n private static string ConvertEbcdicString(byte[] ebcdicBytes)\n {\n if (ebcdicBytes.All(p => p == 0x00 || p == 0xFF))\n {\n //Every byte is either 0x00 or 0xFF (fillers)\n return string.Empty;\n }\n\n Encoding ebcdicEnc = Encoding.GetEncoding(\"IBM037\");\n string result = ebcdicEnc.GetString(ebcdicBytes); // convert EBCDIC Bytes -> \n Unicode string\n return result;\n }\n\n private static Decimal Unpack(byte[] inp, int scale)\n {\n long lo = 0;\n long mid = 0;\n long hi = 0;\n bool isNegative;\n\n // this nybble stores only the sign, not a digit. \n // \"C\" hex is positive, \"D\" hex is negative, AlphaNumd \"F\" hex is unsigned. \n var ff = nibble(inp, 0);\n switch (ff)\n {\n case 0x0D:\n isNegative = true;\n break;\n case 0x0F:\n case 0x0C:\n isNegative = false;\n break;\n default:\n throw new Exception(\"Bad sign nibble\");\n }\n long intermediate;\n long carry;\n long digit;\n for (int j = inp.Length * 2 - 1; j > 0; j--)\n {\n // multiply by 10\n intermediate = lo * 10;\n lo = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n intermediate = mid * 10 + carry;\n mid = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n intermediate = hi * 10 + carry;\n hi = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n // By limiting input length to 14, we ensure overflow will never occur\n\n digit = nibble(inp, j);\n if (digit > 9)\n {\n throw new Exception(\"Bad digit\");\n }\n intermediate = lo + digit;\n lo = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n if (carry > 0)\n {\n intermediate = mid + carry;\n mid = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n if (carry > 0)\n {\n intermediate = hi + carry;\n hi = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n // carry should never be non-zero. Back up with validation\n }\n }\n }\n return new Decimal((int)lo, (int)mid, (int)hi, isNegative, (byte)scale);\n }\n\n private static int nibble(byte[] inp, int nibbleNo)\n {\n int b = inp[inp.Length - 1 - nibbleNo / 2];\n return (nibbleNo % 2 == 0) ? (b & 0x0000000F) : (b >> 4);\n }\n\n class Template\n {\n public string Name { get; set; }\n public string Type { get; set; }\n public int StartPos { get; set; }\n public int CharLength { get; set; }\n public int DecimalPlace { get; set; }\n }\n }\n }\n" }, { "answer_id": 62325357, "author": "Will", "author_id": 13468495, "author_profile": "https://Stackoverflow.com/users/13468495", "pm_score": 0, "selected": false, "text": "using System.Linq;\n\nnamespace SomeNamespace\n{\n public static class SomeExtensionClass\n {\n /// <summary>\n /// computes the actual decimal value from an IBM \"Packed Decimal\" 9(x)v9 (COBOL) format\n /// </summary>\n /// <param name=\"value\">byte[]</param>\n /// <param name=\"precision\">byte; decimal places, default 2</param>\n /// <returns>decimal</returns>\n public static decimal FromPackedDecimal(this byte[] value, byte precision = 2)\n {\n if (value.Length < 1)\n {\n throw new System.InvalidOperationException(\"Cannot unpack empty bytes.\");\n }\n double power = System.Math.Pow(10, precision);\n if (power > long.MaxValue)\n {\n throw new System.InvalidOperationException(\n $\"Precision too large for valid calculation: {precision}\");\n }\n string hex = System.BitConverter.ToString(value).Replace(\"-\", \"\");\n var bytes = Enumerable.Range(0, hex.Length)\n .Select(x => System.Convert.ToByte($\"0{hex.Substring(x, 1)}\", 16))\n .ToList();\n long place = 1;\n decimal ret = 0;\n for (int i = bytes.Count - 2; i > -1; i--)\n {\n ret += (bytes[i] * place);\n place *= 10;\n }\n ret /= (long)power;\n return (bytes.Last() & (1 << 7)) != 0 ? ret * -1 : ret;\n }\n }\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11112/" ]
143,025
<pre><code>struct a { char *c; char b; }; </code></pre> <p>What is sizeof(a)? </p>
[ { "answer_id": 143048, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n\ntypedef struct { char* c; char b; } a;\n\nint main()\n{\n printf(\"sizeof(a) == %d\", sizeof(a));\n}\n #pragma pack(1)\ntypedef struct { char* c; char b; } a;\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
143,032
<p>I am developing a TCP/IP client that has to deal with a proprietary binary protocol. I was considering using user-defined types to represent the protocol headers, and using CopyMemory to shuffle data to and from the UDT and a byte array. However, it appears that VB6 adds padding bytes to align user-defined types. Is there any way to force VB6 to not pad UDT's, similar to the <code>#pragma pack</code> directive available in many C/C++ compilers? Perhaps a special switch passed to the compiler?</p>
[ { "answer_id": 143055, "author": "Uhall", "author_id": 19129, "author_profile": "https://Stackoverflow.com/users/19129", "pm_score": 4, "selected": true, "text": "#pragma pack" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17862/" ]
143,058
<p>ToolStripItems show Active highlighting when you mouse over them, even if the form they are in is not in focus. They do not, however, show their tooltips, unless the form is focused. I have seen the <a href="http://blogs.msdn.com/rickbrew/archive/2006/01/09/511003.aspx" rel="noreferrer">ToolStrip 'click-though' hack</a>. Anyone know how to make a ToolStripButton show its tooltip when its parent form is not in focus?</p> <p>Thanks!</p>
[ { "answer_id": 145483, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "public Form1()\n{\n InitializeComponent();\n\n tooltip = new ToolTip();\n tooltip.ShowAlways = true;\n}\n\nprivate ToolTip tooltip;\nprivate void toolStripButton_MouseHover(object sender, EventArgs e)\n{\n if (!this.Focused)\n {\n ToolStripItem tsi = (ToolStripItem)sender;\n tooltip.SetToolTip(toolStrip1, tsi.AutoToolTip ? tsi.ToolTipText : tsi.Text);\n /*tooltip.Show(tsi.AutoToolTip ? tsi.ToolTipText : tsi.Text, this, \n new Point(toolStrip1.Left, toolStrip1.Bottom));*/\n }\n}\n\nprivate void toolStripButton_MouseLeave(object sender, EventArgs e)\n{\n tooltip.RemoveAll();\n}\n" }, { "answer_id": 170334, "author": "foson", "author_id": 22539, "author_profile": "https://Stackoverflow.com/users/22539", "pm_score": 3, "selected": false, "text": "public class ToolStripDropDownEx : ToolStripDropDownButton\n{\n public ToolStripDropDownEx(string text)\n {\n }\n\n protected override void OnMouseHover(EventArgs e)\n {\n if (this.Parent != null)\n Parent.Focus();\n base.OnMouseHover(e);\n } \n}\n" }, { "answer_id": 307280, "author": "Maurice Flanagan", "author_id": 38791, "author_profile": "https://Stackoverflow.com/users/38791", "pm_score": 1, "selected": false, "text": "// refer VsWhidbey 498263: ToolTips should be shown only on active Windows.\nprivate bool IsWindowActive(IWin32Window window)\n{ \n Control windowControl = window as Control;\n // We want to enter in the IF block only if ShowParams does not return SW_SHOWNOACTIVATE. \n // for ToolStripDropDown ShowParams returns SW_SHOWNOACTIVATE, in which case we DONT want to check IsWindowActive and hence return true. \n if ((windowControl.ShowParams & 0xF) != NativeMethods.SW_SHOWNOACTIVATE)\n { \n IntPtr hWnd = UnsafeNativeMethods.GetActiveWindow();\n IntPtr rootHwnd =UnsafeNativeMethods.GetAncestor(new HandleRef(window, window.Handle), NativeMethods.GA_ROOT);\n if (hWnd != rootHwnd)\n { \n TipInfo tt = (TipInfo)tools[windowControl];\n if (tt != null && (tt.TipType & TipInfo.Type.SemiAbsolute) != 0) \n { \n tools.Remove(windowControl);\n DestroyRegion(windowControl); \n }\n return false;\n }\n } \n return true;\n} \n" }, { "answer_id": 8933286, "author": "KevinKode", "author_id": 1159456, "author_profile": "https://Stackoverflow.com/users/1159456", "pm_score": 2, "selected": false, "text": "private sub SomeCodeSnippet()\n\n Me.tooltipMain.ShowAlways = True\n\n Dim tsi As New ToolStripButton(String.Empty, myImage)\n tsi.ToolTipText = \"my tool tip text\"\n toolstripMain.Add(tsi)\n\n AddHandler tsi.MouseHover, AddressOf ToolStripItem_MouseHover\n\nend sub\n Private Sub ToolStripItem_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs)\n\n If TypeOf sender Is ToolStripButton Then\n Me.tooltipMain.SetToolTip(Me.toolstripMain, CType(sender, ToolStripButton).ToolTipText)\n End If\n\nEnd Sub\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22539/" ]
143,063
<p>I've recently seen the light of EventWaitHandle's powerful behavior in C# and decided to move some functionality in a sister application to do the same. The only problem is that the sister app is written in C.</p> <p>No big deal, I'm using pthreads, which have a pthread_cond_t datatype that allows for signalling. My only question is, is it possible for a cond to be 'signalled' before something is waiting on it?</p> <p>Right now my testing says no. That is, if ThreadA fires a signal before ThreadB is waiting, ThreadB will wait indefinately. Is there another pthread type that I can use that behaves closer to the functionality of the EventWaitHandle in C#? An object is signalled, meaning that the first thread to wait on it, will pass immediately, and set it to unsignalled.</p> <p>Wrapping the pthread_cond into another data structure wouldn't be too hard to achieve this. But again, is this functionality already available in the pthread library?</p>
[ { "answer_id": 143161, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "lock(lockobj);\nwhile (!signalled) {\n wait(condvar);\n}\nsignalled = false;\nunlock(lockobj);\n lock(lockobj);\nsignalled = true;\nnotify(condvar);\nunlock(lockobj);\n" }, { "answer_id": 143169, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "lock(lockobj);\nwhile (signalled != 0) {\n wait(condvar);\n}\n--signalled;\nunlock(lockobj);\n lock(lockobj);\n++signalled;\nnotify(condvar);\nunlock(lockobj);\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8945/" ]
143,072
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/91071/emacs-switch-to-previous-window">Emacs, switch to previous window</a> </p> </blockquote> <p><code>other-window</code> advances me to the next window in the current frame, but I also want a way to move back to the previous window.</p> <p>Emacs has <code>next-buffer</code> and <code>previous-buffer</code>, but no analogous interactive functions for window navigation. Just <code>other-window</code>.</p>
[ { "answer_id": 143080, "author": "Matt Curtis", "author_id": 17221, "author_profile": "https://Stackoverflow.com/users/17221", "pm_score": 6, "selected": true, "text": "(other-window -1) (other-frame -1)" }, { "answer_id": 153941, "author": "Florian Jenn", "author_id": 23813, "author_profile": "https://Stackoverflow.com/users/23813", "pm_score": 2, "selected": false, "text": "C-u - M-- M-- C-x o" }, { "answer_id": 5117049, "author": "ogrim", "author_id": 634065, "author_profile": "https://Stackoverflow.com/users/634065", "pm_score": 4, "selected": false, "text": "previous-multiframe-window C-x O (global-set-key (kbd \"C-x O\") 'previous-multiframe-window)" }, { "answer_id": 5519812, "author": "remcycles", "author_id": 182734, "author_profile": "https://Stackoverflow.com/users/182734", "pm_score": 3, "selected": false, "text": "C-- C-x o" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8913/" ]
143,073
<p>Windbg fans claim that it is quite powerful and I tend to agree. But when it comes to debugging STL containers, I am always stuck. If the variable is on the stack, the <code>!stl</code> extension sometimes figures it out, but when a container with a complex type (e.g. <code>std::vector&lt;TemplateField, std::allocator&lt;TemplateField&gt; &gt;</code>) is on the heap or part of some other structure, I just don't know how to view its contents.</p> <p>Appreciate any tips, pointers.</p>
[ { "answer_id": 143382, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 0, "selected": false, "text": "toString()" }, { "answer_id": 4604630, "author": "kizzx2", "author_id": 111021, "author_profile": "https://Stackoverflow.com/users/111021", "pm_score": 1, "selected": false, "text": "cdb -p <PID> -pv qd qd" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15071/" ]
143,075
<p>I'm trying to print out the date in a certain format:</p> <pre><code>NSDate *today = [[NSDate alloc] init]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyyMMddHHmmss"]; NSString *dateStr = [dateFormatter stringFromDate:today]; </code></pre> <p>If the iPhone is set to 24 hour time, this works fine, if on the other hand the user has set it to 24 hour time, then back to AM/PM (it works fine until you toggle this setting) then it appends the AM/PM on the end even though I didn't ask for it:</p> <pre><code>20080927030337 PM </code></pre> <p>Am I doing something wrong or is this a bug with firmware 2.1?</p> <p>Edit 1: Made description clearer</p> <p>Edit 2 workaround: It turns out this is a bug, to fix it I set the AM and PM characters to "":</p> <pre><code>[dateFormatter setAMSymbol:@""]; [dateFormatter setPMSymbol:@""]; </code></pre>
[ { "answer_id": 143114, "author": "Mike McMaster", "author_id": 544, "author_profile": "https://Stackoverflow.com/users/544", "pm_score": 5, "selected": true, "text": "NSLog(@\"%@\", dateStr);\n" }, { "answer_id": 3174866, "author": "jbg", "author_id": 91420, "author_profile": "https://Stackoverflow.com/users/91420", "pm_score": 1, "selected": false, "text": "NSString *dateStr = @\"2010-07-05\";\nNSString *timeStr = @\"13:30\";\n\nNSDateComponents *components = [[NSDateComponents alloc] init];\ncomponents.year = [[dateStr substringToIndex:4] intValue];\ncomponents.month = [[dateStr substringWithRange:NSMakeRange(5, 2)] intValue];\ncomponents.day = [[dateStr substringFromIndex:8] intValue];\ncomponents.hour = [[timeStr substringToIndex:2] intValue];\ncomponents.minute = [[timeStr substringFromIndex:3] intValue];\n\nNSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n\nNSDate *date = [calendar dateFromComponents:components];\n\n[components release];\n[calendar release];\n" }, { "answer_id": 3269073, "author": "Ethel", "author_id": 335698, "author_profile": "https://Stackoverflow.com/users/335698", "pm_score": 2, "selected": false, "text": "NSDateFormatter *df =[[NSDateFormatter alloc] init];\n [df setDateFormat:@\"yyyy-MM-dd HH:mm:ss\"];\n NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@\"en_US\"];\n\n[df setLocale: usLocale];\n\n[usLocale release];\n\n NSDate *documento_en_Linea =[[[NSDate alloc] init]autorelease];\n\ndocumento_en_Linea=[df dateFromString:@\"2010-07-16 21:40:33\"];\n\n[df release];\n\n NSLog(@\"fdocumentoenLineaUTC:%@!\",documento_en_Linea);\n\n\n//ouput \n fdocumentoenLineaUTC:2010-07-16 09:40:33 p.m. -0500!\n" }, { "answer_id": 3693419, "author": "valexa", "author_id": 314546, "author_profile": "https://Stackoverflow.com/users/314546", "pm_score": 0, "selected": false, "text": "-(NSString*)lowLevTime:(NSString*)stringFormat {\n char buffer[50];\n const char *format = [stringFormat UTF8String];\n time_t rawtime;\n struct tm * timeinfo;\n time(&rawtime);\n timeinfo = localtime(&rawtime);\n strftime(buffer, sizeof(buffer), format, timeinfo);\n return [NSString stringWithCString:buffer encoding:NSASCIIStringEncoding];\n}\n" }, { "answer_id": 6066695, "author": "DenNukem", "author_id": 118878, "author_profile": "https://Stackoverflow.com/users/118878", "pm_score": 3, "selected": false, "text": " NSDateFormatter * f = [[NSDateFormatter alloc] init];\n [f setDateFormat:@\"yyyy-MM-dd'T'HH:mm:ss'Z'\"];\n f.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];\n f.calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];\n f.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@\"en_US\"] autorelease];\n" }, { "answer_id": 11128870, "author": "Arthulia", "author_id": 1470567, "author_profile": "https://Stackoverflow.com/users/1470567", "pm_score": 0, "selected": false, "text": "[dateFormatter setDateFormat:@\"yyyyMMddhhmmss\"]; hh HH hh KK kk" }, { "answer_id": 19857973, "author": "Toseef Khilji", "author_id": 1597744, "author_profile": "https://Stackoverflow.com/users/1597744", "pm_score": 5, "selected": false, "text": "On iPhone OS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set. NSDate *today = [[NSDate alloc] init];\nNSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];\n[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@\"en_US_POSIX\"]];\n[dateFormatter setDateFormat:@\"yyyyMMddHHmmss\"];\nNSString *dateStr = [dateFormatter stringFromDate:today];\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
143,084
<p>Let's say I have one class <code>Foo</code> that has a bunch of logic in it and another class <code>Bar</code> which is essentially the same. However, as <code>Foo</code> and <code>Bar</code> are different (but related) entities I need the difference to be apparent from my code (i.e. I can tell whether an instance is a <code>Foo</code> or a <code>Bar</code>)</p> <p>As I was whacking this together without much thought I ended up with the following:</p> <pre><code>public class Foo { /* constructors, fields, method, logic and what-not */ } public class Bar extends Foo { /* nothing here but constructors */ } </code></pre> <p>Is this OK? Is it better to make <code>Bar</code> a composite class? e.g:</p> <pre><code>public class Bar { private Foo foo; /* constructors and a bunch of wrapper methods that call into foo */ } </code></pre> <p>Or even, while we're at it, something much more low-tech:</p> <pre><code>public class Foo { /* constructors, fields, method, logic and what-not */ private boolean isABar; // Could be an enum } </code></pre> <p>What do you think? <strong>How do you deal with these 'marker classes'?</strong></p> <hr> <p>As an example of how my code may wish to treat <code>Foo</code> and <code>Bar</code> differently, my code would need to be able to do stuff like <code>List&lt;Foo&gt;</code> and <code>List&lt;Bar&gt;</code>. A <code>Foo</code> couldn't go in a <code>List&lt;Bar&gt;</code> and vice versa.</p>
[ { "answer_id": 143091, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "Foo Bar AbstractFoo Foo Bar AbstractFoo if if (foo instanceof Bar) {\n // Do Bar-specific things\n}\n class Bar extends AbstractFoo {\n public void specialOp() {\n // Do Bar-specific things\n }\n}\n\n// ...\nfoo.specialOp();\n Foo if" }, { "answer_id": 143135, "author": "csmba", "author_id": 350, "author_profile": "https://Stackoverflow.com/users/350", "pm_score": 0, "selected": false, "text": "Class MainStuff;\nClass TypeA;\nClass TypeB;\n" }, { "answer_id": 143143, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 2, "selected": false, "text": "Foo Bar ThingThatIsEitherFooOrBar isFoo" }, { "answer_id": 143371, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "class FooBarImplementation\n{\n public void doSomething() { /* etc. */ }\n /* etc. */\n}\n\nclass Foo inherits FooBarImplementation { /* etc. */ }\nclass Bar inherits FooBarImplementation { /* etc. */ }\n class FooBarImplementation\n{\n public void doSomething() { /* etc. */ }\n /* etc. */\n}\n\nclass Foo\n{\n private FooBarImplementation fooBarImplementation = new FooBarImplementation() ;\n\n public void doSomething() { this.fooBarImplementation.doSomething() ; }\n /* etc. */\n}\n\n\nclass Bar\n{\n private FooBarImplementation fooBarImplementation = new FooBarImplementation() ;\n\n public void doSomething() { this.fooBarImplementation.doSomething() ; }\n /* etc. */\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
143,087
<p>I was recently tasked to document a large JavaScript application I have been maintaining for some time. So I do have a good knowledge of the system.</p> <p>But due the sheer size of the application, it will probably take a lot of time even with prior knowledge around the code and the source code itself in uncompressed form.</p> <p>So I'm looking for tools that would help me explore classes and methods and their relationships in JavaScript and if possible, document them along the way, is there one available?</p> <p>Something like object browser in VS would be nice, but any tools that help me get things done faster will do.</p> <p>Thanks!</p>
[ { "answer_id": 143217, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": true, "text": "window inspect(whatever)" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3055/" ]
143,108
<p>Just as in title. Is suspect it is, but I couldn't find it anywhere explicitly stated. And for this property I wouldn't like to rely on speculations.</p>
[ { "answer_id": 143116, "author": "mmcdole", "author_id": 2635, "author_profile": "https://Stackoverflow.com/users/2635", "pm_score": 2, "selected": false, "text": "rand() rand_s() rand()" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
143,122
<p>Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?</p> <p>I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.</p> <p>I've done it using the <a href="http://us3.php.net/manual/en/book.domxml.php" rel="noreferrer">DOMDocument functions</a>, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)</p>
[ { "answer_id": 143192, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 8, "selected": true, "text": "<?php\n$newsXML = new SimpleXMLElement(\"<news></news>\");\n$newsXML->addAttribute('newsPagePrefix', 'value goes here');\n$newsIntro = $newsXML->addChild('content');\n$newsIntro->addAttribute('type', 'latest');\nHeader('Content-type: text/xml');\necho $newsXML->asXML();\n?>\n <?xml version=\"1.0\"?>\n<news newsPagePrefix=\"value goes here\">\n <content type=\"latest\"/>\n</news>\n" }, { "answer_id": 143260, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 5, "selected": false, "text": "$domDoc = new DOMDocument;\n$rootElt = $domDoc->createElement('root');\n$rootNode = $domDoc->appendChild($rootElt);\n\n$subElt = $domDoc->createElement('foo');\n$attr = $domDoc->createAttribute('ah');\n$attrVal = $domDoc->createTextNode('OK');\n$attr->appendChild($attrVal);\n$subElt->appendChild($attr);\n$subNode = $rootNode->appendChild($subElt);\n\n$textNode = $domDoc->createTextNode('Wow, it works!');\n$subNode->appendChild($textNode);\n\necho htmlentities($domDoc->saveXML());\n" }, { "answer_id": 143350, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 4, "selected": false, "text": "$w=new XMLWriter();\n$w->openMemory();\n$w->startDocument('1.0','UTF-8');\n$w->startElement(\"root\");\n $w->writeAttribute(\"ah\", \"OK\");\n $w->text('Wow, it works!');\n$w->endElement();\necho htmlentities($w->outputMemory(true));\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20903/" ]
143,123
<p>Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method. What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character?</p>
[ { "answer_id": 143127, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 5, "selected": true, "text": "#define MY_BUFFER_SIZE 1024\n\nchar mybuffer[MY_BUFFER_SIZE];\nint nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);\n" }, { "answer_id": 204321, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "sizeof sizeof #define BUFSIZE 1500\nchar buffer[BUFSIZE];\nint n = read(sock, buffer, BUFSIZE);\n char buffer[1500];\nint n = read(sock, buffer, sizeof buffer);\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3484/" ]
143,130
<p>My company has a subsidiary with a slow Internet connection. Our developers there suffer to interact with our central <a href="http://en.wikipedia.org/wiki/Subversion_%28software%29" rel="noreferrer">Subversion</a> server. Is it possible to configure a slave/mirror for them? They would interact locally with the server and all the commits would be automatically synchronized to the master server. </p> <p>This should work as transparently as possible for the developers. Usability is a must.</p> <p>Please, no suggestions to change our version control system.</p>
[ { "answer_id": 143163, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 6, "selected": false, "text": "svn mirror" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10335/" ]
143,140
<p>Can anyone tell me, where on the web I can find an explanation for Bron-Kerbosch algorithm for clique finding or explain here how it works?</p> <p>I know it was published in "Algorithm 457: finding all cliques of an undirected graph" book, but I can't find free source that will describe the algorithm.</p> <p>I don't need a source code for the algorithm, I need an explanation of how it works.</p>
[ { "answer_id": 9047013, "author": "Amol", "author_id": 91966, "author_profile": "https://Stackoverflow.com/users/91966", "pm_score": 0, "selected": false, "text": "def bron(compsub, _not, candidates, graph, cliques):\n if len(candidates) == 0 and len(_not) == 0:\n cliques.append(tuple(compsub))\n return\n if len(candidates) == 0: return\n sel = candidates[0]\n candidates.remove(sel)\n newCandidates = removeDisconnected(candidates, sel, graph)\n newNot = removeDisconnected(_not, sel, graph)\n compsub.append(sel)\n bron(compsub, newNot, newCandidates, graph, cliques)\n compsub.remove(sel)\n _not.append(sel)\n bron(compsub, _not, candidates, graph, cliques)\n graph = # 2x2 boolean matrix\ncliques = []\nbron([], [], graph, cliques)\n cliques" }, { "answer_id": 24415469, "author": "Shahaf", "author_id": 593356, "author_profile": "https://Stackoverflow.com/users/593356", "pm_score": 2, "selected": false, "text": "class Node(object):\n\n def __init__(self, name):\n self.name = name\n self.neighbors = []\n\n def __repr__(self):\n return self.name\n\nA = Node('A')\nB = Node('B')\nC = Node('C')\nD = Node('D')\nE = Node('E')\n\nA.neighbors = [B, C]\nB.neighbors = [A, C]\nC.neighbors = [A, B, D]\nD.neighbors = [C, E]\nE.neighbors = [D]\n\nall_nodes = [A, B, C, D, E]\n\ndef find_cliques(potential_clique=[], remaining_nodes=[], skip_nodes=[], depth=0):\n\n # To understand the flow better, uncomment this:\n # print (' ' * depth), 'potential_clique:', potential_clique, 'remaining_nodes:', remaining_nodes, 'skip_nodes:', skip_nodes\n\n if len(remaining_nodes) == 0 and len(skip_nodes) == 0:\n print 'This is a clique:', potential_clique\n return\n\n for node in remaining_nodes:\n\n # Try adding the node to the current potential_clique to see if we can make it work.\n new_potential_clique = potential_clique + [node]\n new_remaining_nodes = [n for n in remaining_nodes if n in node.neighbors]\n new_skip_list = [n for n in skip_nodes if n in node.neighbors]\n find_cliques(new_potential_clique, new_remaining_nodes, new_skip_list, depth + 1)\n\n # We're done considering this node. If there was a way to form a clique with it, we\n # already discovered its maximal clique in the recursive call above. So, go ahead\n # and remove it from the list of remaining nodes and add it to the skip list.\n remaining_nodes.remove(node)\n skip_nodes.append(node)\n\nfind_cliques(remaining_nodes=all_nodes)\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11525/" ]
143,171
<p>I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names. When I try to string together <code>find</code> and <code>grep</code> with <code>xargs</code>, I get the following error:</p> <pre><code>find .|grep "FooBar"|xargs -I{} cp "{}" ~/foo/bar xargs: unterminated quote </code></pre> <p>Any suggestions for a more robust usage of xargs?</p> <p>This is on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="noreferrer">Mac&nbsp;OS&nbsp;X 10.5.3</a> (Leopard) with BSD <code>xargs</code>.</p>
[ { "answer_id": 143172, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 7, "selected": false, "text": "find . -print0 | grep --null 'FooBar' | xargs -0 ... grep --null xargs -0" }, { "answer_id": 143222, "author": "godbyk", "author_id": 4214, "author_profile": "https://Stackoverflow.com/users/4214", "pm_score": 9, "selected": true, "text": "find find . -iname \"*foobar*\" -exec cp -- \"{}\" ~/foo/bar \\;\n -name -- cp -" }, { "answer_id": 149026, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": 6, "selected": false, "text": "find -name '*FooBar*' -print0 | xargs -0 cp -t ~/foo/bar\n" }, { "answer_id": 474907, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "find /usr/pcapps/ -mount -type f -size +1000000c | perl -lpe ' s{ }{\\\\ }g ' | xargs ls -l | sort +4nr | head -200\n" }, { "answer_id": 1004726, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "find -type f | sed 's/./\\\\&/g' | xargs grep string_to_find\n" }, { "answer_id": 4064129, "author": "Carl Yamamoto-Furst", "author_id": 492879, "author_profile": "https://Stackoverflow.com/users/492879", "pm_score": 1, "selected": false, "text": "find . -mtime +2 | perl -pe 's{^}{\\\"};s{$}{\\\"}' > ~/output.file\n" }, { "answer_id": 9219776, "author": "mavit", "author_id": 487095, "author_profile": "https://Stackoverflow.com/users/487095", "pm_score": 3, "selected": false, "text": "find | perl -lne 'print quotemeta' | xargs ls -d\n" }, { "answer_id": 12067078, "author": "oyouareatubeo", "author_id": 1067630, "author_profile": "https://Stackoverflow.com/users/1067630", "pm_score": 6, "selected": false, "text": "find . -name '*FoooBar*' | sed 's/.*/\"&\"/' | xargs cp ~/foo/bar\n sed sed .* xargs: unterminated quote" }, { "answer_id": 17325049, "author": "fred", "author_id": 1289107, "author_profile": "https://Stackoverflow.com/users/1289107", "pm_score": 0, "selected": false, "text": "find . -name \"file.ext\"| grep \"FooBar\" | xargs -i cp -p \"{}\" .\n" }, { "answer_id": 17325825, "author": "jlliagre", "author_id": 211665, "author_profile": "https://Stackoverflow.com/users/211665", "pm_score": 4, "selected": false, "text": "xargs find find xargs cp find . -name \"*FooBar*\" -exec sh -c 'cp -- \"$@\" ~/foo/bar' sh {} +\n + ; xargs find {} fish" }, { "answer_id": 18496493, "author": "frediy", "author_id": 2559037, "author_profile": "https://Stackoverflow.com/users/2559037", "pm_score": 6, "selected": false, "text": "find . | grep FooBar | xargs -I{} cp {} ~/foo/bar\n" }, { "answer_id": 20868963, "author": "StackedCrooked", "author_id": 75889, "author_profile": "https://Stackoverflow.com/users/75889", "pm_score": 2, "selected": false, "text": "while read line ; do cp \"$line\" ~/bar ; done < <(find . | grep foo)\n" }, { "answer_id": 22535558, "author": "Aleksandr Guidrevitch", "author_id": 1199707, "author_profile": "https://Stackoverflow.com/users/1199707", "pm_score": 3, "selected": false, "text": "ls find . | grep \"FooBar\" | tr \\\\n \\\\0 | xargs -0 -I{} cp \"{}\" ~/foo/bar\n" }, { "answer_id": 23773189, "author": "Lenik", "author_id": 217071, "author_profile": "https://Stackoverflow.com/users/217071", "pm_score": -1, "selected": false, "text": "mapfile find . | grep \"FooBar\" | (mapfile -t; cp \"${MAPFILE[@]}\" ~/foobar)\n cp find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +\n" }, { "answer_id": 29303513, "author": "Jan Ptáčník", "author_id": 4101469, "author_profile": "https://Stackoverflow.com/users/4101469", "pm_score": 1, "selected": false, "text": "-print0 -0 find . -name \"*foo*\" | sed -e \"s/'/\\\\\\'/g\" -e 's/\"/\\\\\"/g' -e 's/ /\\\\ /g' | xargs cp /your/dest\n" }, { "answer_id": 31841671, "author": "John Allsup", "author_id": 2138913, "author_profile": "https://Stackoverflow.com/users/2138913", "pm_score": 1, "selected": false, "text": "find .|grep \"FooBar\"|yargs -l 203 cp --after ~/foo/bar\n" }, { "answer_id": 33005355, "author": "Moises", "author_id": 5420970, "author_profile": "https://Stackoverflow.com/users/5420970", "pm_score": 2, "selected": false, "text": "$ find . -type f -name '*.txt' | sed 's/'\"'\"'/\\'\"'\"'/g' | sed 's/.*/\"&\"/' | xargs -I{} cp -v {} ./tmp/\n" }, { "answer_id": 33528111, "author": "user87601", "author_id": 4364138, "author_profile": "https://Stackoverflow.com/users/4364138", "pm_score": 7, "selected": false, "text": "find whatever ... | xargs -d \"\\n\" cp -t /var/tmp\n" }, { "answer_id": 49340007, "author": "Guenther Brunthaler", "author_id": 4411491, "author_profile": "https://Stackoverflow.com/users/4411491", "pm_score": 1, "selected": false, "text": "$ true | xargs echo no data\nno data\n\n$ true | xargsL echo no data # No output\n #! /bin/sh\n# Line-based version of \"xargs\" (one pathname per line which may contain any\n# amount of whitespace except for newlines) with the added bonus feature that\n# it will not execute the command if the input file is empty.\n#\n# Version 2018.76.3\n#\n# Copyright (c) 2018 Guenther Brunthaler. All rights reserved.\n#\n# This script is free software.\n# Distribution is permitted under the terms of the GPLv3.\n\nset -e\ntrap 'test $? = 0 || echo \"$0 failed!\" >& 2' 0\n\nif IFS= read -r first\nthen\n {\n printf '%s\\n' \"$first\"\n cat\n } | sed 's/./\\\\&/g' | xargs ${1+\"$@\"}\nfi\n $ chmod +x xargsL" }, { "answer_id": 56803676, "author": "gerrit", "author_id": 974555, "author_profile": "https://Stackoverflow.com/users/974555", "pm_score": 2, "selected": false, "text": "user80168 find . -name '*FooBar*' -exec cp -t /tmp -- {} +\n cp -t cp man cp -t, --target-directory=DIRECTORY\n copy all SOURCE arguments into DIRECTORY\n -- cp - -- cp - -- cp find -exec command {} + man find -exec command {} + \n This variant of the -exec action runs the specified command on\n the selected files, but the command line is built by appending\n each selected file name at the end; the total number of invoca‐\n matched files. The command line is built in much the same way\n that xargs builds its command lines. Only one instance of `{}'\n is allowed within the command, and (when find is being invoked\n from a shell) it should be quoted (for example, '{}') to protect\n it from interpretation by shells. The command is executed in\n the starting directory. If any invocation returns a non-zero\n value as exit status, then find returns a non-zero exit status.\n If find encounters an error, this can sometimes cause an immedi‐\n ate exit, so some pending commands may not be run at all. This\n variant of -exec always returns true.\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17339/" ]
143,174
<p>Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)</p> <p>(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)</p>
[ { "answer_id": 143188, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n\nint main(int argc, char **argv) {\n char the_path[256];\n\n getcwd(the_path, 255);\n strcat(the_path, \"/\");\n strcat(the_path, argv[0]);\n\n printf(\"%s\\n\", the_path);\n\n return 0;\n}\n" }, { "answer_id": 145216, "author": "John Zwinck", "author_id": 4323, "author_profile": "https://Stackoverflow.com/users/4323", "pm_score": 0, "selected": false, "text": "initial_path() getcwd() argv[0] /foo/bar/../../baz/a.out /foo/bar//baz/a.out envp main()" }, { "answer_id": 145309, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 7, "selected": false, "text": "#include <stdio.h> /* defines FILENAME_MAX */\n#ifdef WINDOWS\n #include <direct.h>\n #define GetCurrentDir _getcwd\n#else\n #include <unistd.h>\n #define GetCurrentDir getcwd\n #endif\n\n char cCurrentPath[FILENAME_MAX];\n\n if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))\n {\n return errno;\n }\n\ncCurrentPath[sizeof(cCurrentPath) - 1] = '\\0'; /* not really required */\n\nprintf (\"The current working directory is %s\", cCurrentPath);\n" }, { "answer_id": 198099, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": true, "text": "char pBuf[256];\nsize_t len = sizeof(pBuf); \n int bytes = GetModuleFileName(NULL, pBuf, len);\nreturn bytes ? bytes : -1;\n int bytes = MIN(readlink(\"/proc/self/exe\", pBuf, len), len - 1);\nif(bytes >= 0)\n pBuf[bytes] = '\\0';\nreturn bytes;\n" }, { "answer_id": 16887756, "author": "Adam Yaxley", "author_id": 693967, "author_profile": "https://Stackoverflow.com/users/693967", "pm_score": 3, "selected": false, "text": "_get_pgmptr stdlib.h char* path;\n_get_pgmptr(&path);\nprintf(path); // Example output: C:/Projects/Hello/World.exe\n" }, { "answer_id": 17029008, "author": "Alexey1993", "author_id": 2471792, "author_profile": "https://Stackoverflow.com/users/2471792", "pm_score": 2, "selected": false, "text": "dir dir cmd ls int main()\n{\n system(\"dir\");\n system(\"pause\"); //this wait for Enter-key-press;\n return 0;\n}\n" }, { "answer_id": 19535628, "author": "Octopus", "author_id": 1475548, "author_profile": "https://Stackoverflow.com/users/1475548", "pm_score": 6, "selected": false, "text": "#include <string>\n#include <windows.h>\n\nstd::string getexepath()\n{\n char result[ MAX_PATH ];\n return std::string( result, GetModuleFileName( NULL, result, MAX_PATH ) );\n}\n #include <string>\n#include <limits.h>\n#include <unistd.h>\n\nstd::string getexepath()\n{\n char result[ PATH_MAX ];\n ssize_t count = readlink( \"/proc/self/exe\", result, PATH_MAX );\n return std::string( result, (count > 0) ? count : 0 );\n}\n #include <string>\n#include <limits.h>\n#define _PSTAT64\n#include <sys/pstat.h>\n#include <sys/types.h>\n#include <unistd.h>\n\nstd::string getexepath()\n{\n char result[ PATH_MAX ];\n struct pst_status ps;\n\n if (pstat_getproc( &ps, sizeof( ps ), 0, getpid() ) < 0)\n return std::string();\n\n if (pstat_getpathname( result, PATH_MAX, &ps.pst_fid_text ) < 0)\n return std::string();\n\n return std::string( result );\n}\n" }, { "answer_id": 21887613, "author": "freezotic", "author_id": 3329232, "author_profile": "https://Stackoverflow.com/users/3329232", "pm_score": 2, "selected": false, "text": "#include <windows.h>\nusing namespace std;\n\n// The directory path returned by native GetCurrentDirectory() no end backslash\nstring getCurrentDirectoryOnWindows()\n{\n const unsigned long maxDir = 260;\n char currentDir[maxDir];\n GetCurrentDirectory(maxDir, currentDir);\n return string(currentDir);\n}\n" }, { "answer_id": 29763572, "author": "FuzzyQuills", "author_id": 4156345, "author_profile": "https://Stackoverflow.com/users/4156345", "pm_score": 1, "selected": false, "text": "\"path/to/file/folder\"\n \"./path/to/file/folder\"\n \"resources/Example.data\"\n" }, { "answer_id": 32024051, "author": "Sam Redway", "author_id": 3940749, "author_profile": "https://Stackoverflow.com/users/3940749", "pm_score": 5, "selected": false, "text": "int main(int argc, char* argv[])\n{\n std::string argv_str(argv[0]);\n std::string base = argv_str.substr(0, argv_str.find_last_of(\"/\"));\n}\n main\n ----> test\n ----> src\n ----> bin\n std::string pathToWrite = base + \"/../test/test.log\";\n std::string base = argv[0].substr(0, argv[0].find_last_of(\"\\\\\"));\n" }, { "answer_id": 34832779, "author": "Marqin", "author_id": 898435, "author_profile": "https://Stackoverflow.com/users/898435", "pm_score": 5, "selected": false, "text": "current_path() std::string path = std::experimental::filesystem::current_path();\n #include <experimental/filesystem>\n -lstdc++fs" }, { "answer_id": 46561633, "author": "Joachim", "author_id": 1961484, "author_profile": "https://Stackoverflow.com/users/1961484", "pm_score": 1, "selected": false, "text": "QCoreApplication::applicationDirPath()" }, { "answer_id": 56060288, "author": "Manabu Nakazawa", "author_id": 4366470, "author_profile": "https://Stackoverflow.com/users/4366470", "pm_score": 0, "selected": false, "text": "realpath() stdlib.h char *working_dir_path = realpath(\".\", NULL);\n" }, { "answer_id": 56526330, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 2, "selected": false, "text": "#pragma once\n\n//\n// https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros\n//\n#ifdef __cpp_lib_filesystem\n#include <filesystem>\n#else\n#include <experimental/filesystem>\n\nnamespace std {\n namespace filesystem = experimental::filesystem;\n}\n#endif\n\nstd::filesystem::path getexepath();\n #include \"application.h\"\n#ifdef _WIN32\n#include <windows.h> //GetModuleFileNameW\n#else\n#include <limits.h>\n#include <unistd.h> //readlink\n#endif\n\nstd::filesystem::path getexepath()\n{\n#ifdef _WIN32\n wchar_t path[MAX_PATH] = { 0 };\n GetModuleFileNameW(NULL, path, MAX_PATH);\n return path;\n#else\n char result[PATH_MAX];\n ssize_t count = readlink(\"/proc/self/exe\", result, PATH_MAX);\n return std::string(result, (count > 0) ? count : 0);\n#endif\n}\n" }, { "answer_id": 60804126, "author": "nilo", "author_id": 3246135, "author_profile": "https://Stackoverflow.com/users/3246135", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <filesystem>\nnamespace fs = std::filesystem;\n\nint main(int argc, char* argv[])\n{\n std::cout << \"Path is \" << fs::path(argv[0]).parent_path() << '\\n';\n}\n std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = \"\");\n fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)\n{\n static auto exe_parent_path = fs::path(exe_path).parent_path();\n return exe_parent_path / filename;\n}\n main() (void) prepend_exe_path(\"\", argv[0]);\n" }, { "answer_id": 65474320, "author": "The Oathman", "author_id": 10860215, "author_profile": "https://Stackoverflow.com/users/10860215", "pm_score": 1, "selected": false, "text": "\n#include <Windows.h>\n\nstd::wstring getexepathW()\n{\n wchar_t result[MAX_PATH];\n return std::wstring(result, GetModuleFileNameW(NULL, result, MAX_PATH));\n}\n\nstd::wcout << getexepathW() << std::endl;\n\n// -------- OR --------\n\nstd::string getexepathA()\n{\n char result[MAX_PATH];\n return std::string(result, GetModuleFileNameA(NULL, result, MAX_PATH));\n}\n\nstd::cout << getexepathA() << std::endl;\n\n" }, { "answer_id": 71281252, "author": "Tareq Saif", "author_id": 3981013, "author_profile": "https://Stackoverflow.com/users/3981013", "pm_score": 0, "selected": false, "text": "brew install boost\n #include <iostream>\n#include <boost/filesystem.hpp>\n\nint main(int argc, char* argv[]){\n boost::filesystem::path p{argv[0]};\n p = absolute(p).parent_path();\n std::cout << p << std::endl;\n return 0;\n}\n g++ -Wall -std=c++11 -l boost_filesystem main.cpp\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
143,181
<p>If you have a project, that releases a library and an application, how you handle version-numbers between the two.</p> <p>Example: Your project delivers a library, that convert different file-formats into each other. The library is released for inclusion into other applications. But you also release a command-line-application, that uses this library and implements an interface to the functionality.</p> <p>New releases of the library lead to new releases of the application (to make use of all new features), but new releases of the application may not trigger new releases of the library. Now how are the versions numbers handled: Completely independent or should library- and application-version be dependent in some way?</p>
[ { "answer_id": 143452, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": true, "text": "$ xsltproc --version\nUsing libxml 20628, libxslt 10120 and libexslt 813\nxsltproc was compiled against libxml 20628, libxslt 10120 and libexslt 813\nlibxslt 10120 was compiled against libxml 20628\nlibexslt 813 was compiled against libxml 20628\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
143,194
<p>I have a pretty complicated Linq query that I can't seem to get into a LinqDataSsource for use in a GridView:</p> <pre><code>IEnumerable&lt;ticket&gt; tikPart = ( from p in db.comments where p.submitter == me.id &amp;&amp; p.ticket.closed == DateTime.Parse("1/1/2001") &amp;&amp; p.ticket.originating_group != me.sub_unit select p.ticket ).Distinct(); </code></pre> <p>How can I get this into a GridView? Thank you!</p>
[ { "answer_id": 143195, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "gridview.DataSource = tikPart.ToList();\ngridview.DataBind();\n" }, { "answer_id": 143210, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "using(MyDataContext ctx = new MyDataContext(){\n this.MyGridView.DataSource = from something in ctx.Somethings where something.SomeProperty == someValue select something;\n this.MyGridView.DataBind();\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
143,206
<p>I want to obtain the current number of window handles and the system-wide window handle limit in C#. How do I go about this?</p>
[ { "answer_id": 534991, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Runtime.InteropServices;\n\nnamespace StreamWrite.Proceedings.Client\n{\n public class HWndCounter\n {\n [DllImport(\"kernel32.dll\")]\n private static extern IntPtr GetCurrentProcess();\n\n [DllImport(\"user32.dll\")]\n private static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags);\n\n private enum ResourceType\n {\n Gdi = 0,\n User = 1\n }\n\n public static int GetWindowHandlesForCurrentProcess(IntPtr hWnd)\n {\n IntPtr processHandle = GetCurrentProcess();\n uint gdiObjects = GetGuiResources(processHandle, (uint)ResourceType.Gdi);\n uint userObjects = GetGuiResources(processHandle, (uint)ResourceType.User);\n\n return Convert.ToInt32(gdiObjects + userObjects);\n }\n }\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
143,215
<p>I've been trying to display text using a Quartz context, but no matter what I've tried I simply haven't had luck getting the text to display (I'm able to display all sorts of other Quartz objects though). Anybody knows what I might be doing wrong?</p> <p>example:</p> <pre><code>-(void)drawRect:(CGRect)rect { // Drawing code CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSelectFont(context, "Arial", 24, kCGEncodingFontSpecific); CGContextSetTextPosition(context,80,80); CGContextShowText(context, "hello", 6); //not even this works CGContextShowTextAtPoint(context, 1,1, "hello", 6); } </code></pre>
[ { "answer_id": 143352, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 4, "selected": true, "text": "UIColor *mainTextColor = [UIColor whiteColor];\n[mainTextColor set];\ndrawTextLjust(@\"Sample Text\", 8, 50, 185, 18, 16);\n static void drawTextLjust(NSString* text, CGFloat y, CGFloat left, CGFloat right,\n int maxFontSize, int minFontSize) {\n CGPoint point = CGPointMake(left, y);\n UIFont *font = [UIFont systemFontOfSize:maxFontSize];\n [text drawAtPoint:point forWidth:right - left withFont:font\n minFontSize:minFontSize actualFontSize:NULL\n lineBreakMode:UILineBreakModeTailTruncation\n baselineAdjustment:UIBaselineAdjustmentAlignBaselines];\n}\n" }, { "answer_id": 3458620, "author": "Ash", "author_id": 414476, "author_profile": "https://Stackoverflow.com/users/414476", "pm_score": 3, "selected": false, "text": "CGContextSetTextMatrix(canvas, CGAffineTransformMake(1, 0, 0, -1, 0, 0));\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
143,226
<p>let's assume i have a self referencing hierarchical table build the classical way like this one:</p> <pre><code>CREATE TABLE test (name text,id serial primary key,parent_id integer references test); insert into test (name,id,parent_id) values ('root1',1,NULL),('root2',2,NULL),('root1sub1',3,1),('root1sub2',4,1),('root 2sub1',5,2),('root2sub2',6,2); testdb=# select * from test; name | id | parent_id -----------+----+----------- root1 | 1 | root2 | 2 | root1sub1 | 3 | 1 root1sub2 | 4 | 1 root2sub1 | 5 | 2 root2sub2 | 6 | 2 </code></pre> <p>What i need now is a function (preferrably in plain sql) that would take the id of a test record and clone all attached records (including the given one). The cloned records need to have new ids of course. The desired result would like this for example:</p> <pre><code>Select * from cloningfunction(2); name | id | parent_id -----------+----+----------- root2 | 7 | root2sub1 | 8 | 7 root2sub2 | 9 | 7 </code></pre> <p>Any pointers? Im using PostgreSQL 8.3.</p>
[ { "answer_id": 143313, "author": "njr101", "author_id": 9625, "author_profile": "https://Stackoverflow.com/users/9625", "pm_score": 3, "selected": false, "text": "name | id | parent_id | upchain\nroot1 | 1 | NULL | 1:\nroot2 | 2 | NULL | 2:\nroot1sub1 | 3 | 1 | 1:3:\nroot1sub2 | 4 | 1 | 1:4:\nroot2sub1 | 5 | 2 | 2:5:\nroot2sub2 | 6 | 2 | 2:6:\nroot1sub1sub1 | 7 | 3 | 1:3:7:\n SELECT *\nFROM table\nWHERE upchain LIKE '1:%'\n" }, { "answer_id": 146569, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 1, "selected": false, "text": "CREATE PROCEDURE CloneNode\n @to_clone_id int, @parent_id int\nAS\n SET NOCOUNT ON\n DECLARE @new_node_id int, @child_id int\n\n INSERT INTO test (name, parent_id) \n SELECT name, @parent_id FROM test WHERE id = @to_clone_id\n SET @new_node_id = @@IDENTITY\n\n DECLARE @children_cursor CURSOR\n SET @children_cursor = CURSOR FOR \n SELECT id FROM test WHERE parent_id = @to_clone_id\n\n OPEN @children_cursor\n FETCH NEXT FROM @children_cursor INTO @child_id\n WHILE @@FETCH_STATUS = 0\n BEGIN\n EXECUTE CloneNode @child_id, @new_node_id\n FETCH NEXT FROM @children_cursor INTO @child_id\n END\n CLOSE @children_cursor\n DEALLOCATE @children_cursor\n EXECUTE CloneNode 2, null" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
143,231
<p>One of our next projects is supposed to be a MS Windows based game (written in C#, with a winform GUI and an integrated DirectX display-control) for a customer who wants to give away prizes to the best players. This project is meant to run for a couple of years, with championships, ladders, tournaments, player vs. player-action and so on.</p> <p>One of the main concerns here is cheating, as a player would benefit dramatically if he was able to - for instance - let a custom made bot play the game for him (more in terms of strategy-decisions than in terms of playing many hours).</p> <p>So my question is: what technical possibilites do we have to detect bot activity? We can of course track the number of hours played, analyze strategies to detect anomalies and so on, but as far as this question is concerned, I would be more interested in knowing details like</p> <ul> <li>how to detect if another application makes periodical screenshots?</li> <li>how to detect if another application scans our process memory?</li> <li>what are good ways to determine whether user input (mouse movement, keyboard input) is human-generated and not automated?</li> <li>is it possible to detect if another application requests informations about controls in our application (position of controls etc)?</li> <li>what other ways exist in which a cheater could gather informations about the current game state, feed those to a bot and send the determined actions back to the client?</li> </ul> <p>Your feedback is highly appreciated!</p>
[ { "answer_id": 143273, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "* how to detect if another application makes periodical screenshots?\n* how to detect if another application scans our process memory?\n* what are good ways to determine whether user input (mouse movement, keyboard input) is human-generated and not automated?\n* is it possible to detect if another application requests informations about controls in our application (position of controls etc)?\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17378/" ]
143,233
<p>I am using <a href="http://cxxtest.tigris.org/" rel="nofollow noreferrer">cxxtest</a> as the test framework for my C++ classes, and would like to figure out a way to simulate sending data to classes which would normally expect to receive it from standard input. I have several different files which I would like to send to the classes during different tests, so redirection from the command line to the test suite executable is not an option.</p> <p>Basically, what I would really like to do is find a way to redefine or redirect the 'stdin' handle to some other value that I create inside of my program, and then use fwrite() from these tests so that the corresponding fread() inside of the class pulls the data from within the program, not from the actual standard I/O handles associated with the executable.</p> <p>Is this even possible? Bonus points for a platform-independent solution, but at a very minimum, I need this to work with Visual Studio 9 under Windows.</p>
[ { "answer_id": 143262, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 2, "selected": false, "text": "std::cin stringstream \nstd::istringstream iss(\"1.0 2 3.1415\");\nsome_class.parse_nums(iss, one, two, pi);\n" }, { "answer_id": 143948, "author": "Rexxar", "author_id": 10016, "author_profile": "https://Stackoverflow.com/users/10016", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <fstream>\n#include <string>\n\nint main()\n{\n std::ifstream inputFile(\"Main.cpp\");\n std::streambuf *inbuf = std::cin.rdbuf(inputFile.rdbuf());\n\n string str;\n // print the content of the file without 'space' characters\n while(std::cin >> str)\n {\n std::cout << str;\n }\n\n // restore the initial buffer\n std::cin.rdbuf(inbuf);\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14302/" ]
143,234
<p>In Lua, using the = operator without an l-value seems to be equivalent to a print(r-value), here are a few examples run in the Lua standalone interpreter:</p> <pre><code>&gt; = a nil &gt; a = 8 &gt; = a 8 &gt; = 'hello' hello &gt; = print function: 003657C8 </code></pre> <p>And so on...</p> <p>My question is : where can I find a detailed description of this use for the = operator? How does it work? Is it by implying a special default l-value? I guess the root of my problem is that I have no clue what to type in Google to find info about it :-)</p> <p><strong>edit</strong>:</p> <p>Thanks for the answers, you are right it's a feature of the interpreter. Silly question, for I don't know which reason I completely overlooked the obvious. I should avoid posting before the morning coffee :-) For completeness, here is the code dealing with this in the interpreter:</p> <pre><code>while ((status = loadline(L)) != -1) { if (status == 0) status = docall(L, 0, 0); report(L, status); if (status == 0 &amp;&amp; lua_gettop(L) &gt; 0) { /* any result to print? */ lua_getglobal(L, "print"); lua_insert(L, 1); if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) l_message(progname, lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)", lua_tostring(L, -1))); } } </code></pre> <p><strong>edit2</strong>:</p> <p>To be really complete, the whole trick about pushing values on the stack is in the "pushline" function:</p> <pre><code>if (firstline &amp;&amp; b[0] == '=') /* first line starts with `=' ? */ lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ </code></pre>
[ { "answer_id": 143268, "author": "Arle Nadja", "author_id": 17774, "author_profile": "https://Stackoverflow.com/users/17774", "pm_score": 0, "selected": false, "text": "Lua C" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12291/" ]
143,285
<p>For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++</p>
[ { "answer_id": 143298, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 7, "selected": true, "text": "enum enum enum class Constants public enum Constants {\n ONE,\n TWO,\n THREE;\n}\n enum class javap Compiled from \"Constants.java\"\npublic final class Constants extends java.lang.Enum{\n public static final Constants ONE;\n public static final Constants TWO;\n public static final Constants THREE;\n public static Constants[] values();\n public static Constants valueOf(java.lang.String);\n static {};\n}\n enum Constants enum javap new Constants(String) enum" }, { "answer_id": 143306, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 1, "selected": false, "text": "printf(\"%d\", sizeof(enum));\n" }, { "answer_id": 143361, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 3, "selected": false, "text": "bool int" }, { "answer_id": 144732, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "int" }, { "answer_id": 145114, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 0, "selected": false, "text": "typedef enum {\n MY_ENUM0,\n MY_ENUM1,\n MY_ENUM2,\n MY_ENUM3,\n MY_ENUM4,\n MY_ENUM5\n} __attribute__((packed)) myEnum_e;\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
143,296
<p>I've got such a simple code:</p> <pre><code>&lt;div class="div1"&gt; &lt;div class="div2"&gt;Foo&lt;/div&gt; &lt;div class="div3"&gt; &lt;div class="div4"&gt; &lt;div class="div5"&gt; Bar &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and this CSS:</p> <pre class="lang-css prettyprint-override"><code>.div1{ position: relative; } .div1 .div3 { position: absolute; top: 30px; left: 0px; width: 250px; display: none; } .div1:hover .div3 { display: block; } .div2{ width: 200px; height: 30px; background: red; } .div4 { background-color: green; color: #000; } .div5 {} </code></pre> <p>The problem is: When I move the cursor from <code>.div2</code> to <code>.div3</code> (<code>.div3</code> should stay visible because it's the child of <code>.div1</code>) then the hover is disabled. I'm testing it in IE7, in FF it works fine. What am I doing wrong? I've also realized that when i remove <code>.div5</code> tag than it's working. Any ideas?</p>
[ { "answer_id": 143309, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": " <style type=\"text/css\">\n * {\n color: #fff;\n }\n .wrapper {\n\n }\n\n .trigger {\n background: #223;\n }\n\n .appear {\n background: #334;\n display: none;\n }\n\n .trigger:hover .appear {\n display: block;\n }\n </style>\n</head>\n\n<body>\n\n <div class=\"wrapper\">\n <div class=\"trigger\">\n <p>This is the trigger for the hover element.</p>\n <div class=\"appear\">\n <p>I'm <strong>alive!</strong></p>\n </div>\n </div>\n </div>\n\n</body>\n" }, { "answer_id": 144625, "author": "Justin Poliey", "author_id": 6967, "author_profile": "https://Stackoverflow.com/users/6967", "pm_score": 6, "selected": true, "text": ":hover <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20403/" ]
143,320
<p>I am trying to write a cronjob controller, so I can call one website and have all modules cronjob.php executed. Now my problem is how do I do that?</p> <p>Would curl be an option, so I also can count the errors and successes?</p> <p>[Update]</p> <p>I guess I have not explained it enough. </p> <p>What I want to do is have one file which I can call like from <a href="http://server/cronjob" rel="noreferrer">http://server/cronjob</a> and then make it execute every /application/modules/*/controller/CronjobController.php or have another way of doing it so all the cronjobs aren't at one place but at the same place the module is located. This would offer me the advantage, that if a module does not exist it does not try to run its cronjob.</p> <p>Now my question is how would you execute all the modules CronjobController or would you do it a completly different way so it still stays modular?</p> <p>And I want to be able to giveout how many cronjobs ran successfully and how many didn't</p>
[ { "answer_id": 144235, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 0, "selected": false, "text": "Zend_Http_Client Zend_Test_PHPUnit" }, { "answer_id": 733148, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Zend_Loader::registerAutoload() myModules_MyClass::doSomething();" }, { "answer_id": 1268635, "author": "gregor", "author_id": 154227, "author_profile": "https://Stackoverflow.com/users/154227", "pm_score": 3, "selected": false, "text": "//public/index.php\n\nif(!defined('DONT_RUN_APP') || DONT_RUN_APP == false) { \n $application->bootstrap()->run();\n}\n\n// application/../cron/cronjob.php\n\ndefine(\"DONT_RUN_APP\",true);\nrequire(realpath('/srv/www/project/public/index.php'));\n$application->bootstrap('config');\n$application->bootstrap('db');\n\n//cron code follows\n" }, { "answer_id": 4477842, "author": "takeshin", "author_id": 234780, "author_profile": "https://Stackoverflow.com/users/234780", "pm_score": 1, "selected": false, "text": "zf-cli" }, { "answer_id": 4675941, "author": "lony", "author_id": 227821, "author_profile": "https://Stackoverflow.com/users/227821", "pm_score": 0, "selected": false, "text": "//public/index.php \n\n// Run application, only if not started from command line (cli)\nif (php_sapi_name() != 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {\n $application->run();\n}\n" }, { "answer_id": 8097784, "author": "Gerald Ekosso", "author_id": 1042169, "author_profile": "https://Stackoverflow.com/users/1042169", "pm_score": 2, "selected": false, "text": "curl http://www.mysite.com/cron_controller/action bash /path/to/cron.sh" }, { "answer_id": 11686981, "author": "Octavian Vladu", "author_id": 1175138, "author_profile": "https://Stackoverflow.com/users/1175138", "pm_score": 0, "selected": false, "text": "public static function setupEnvironment()\n{\n ...\n self::setupFrontController();\n self::setupDatabase();\n self::setupRoutes();\n ...\n if (PHP_SAPI !== 'cli') { \n self::setupView();\n self::setupDbCaches();\n }\n ...\n}\n public function setupRoutes()\n{ \n ...\n if (PHP_SAPI == 'cli') { \n self::$frontController->setRouter(new App_Router_Cli());\n self::$frontController->setRequest(new Zend_Controller_Request_Http()); \n }\n}\n script.php controller=mail action=send class App_Router_Cli extends Zend_Controller_Router_Abstract \n{\n public function route (Zend_Controller_Request_Abstract $dispatcher) \n {\n $getopt = new Zend_Console_Getopt (array());\n $arguments = $getopt->getRemainingArgs();\n $controller = \"\";\n $action = \"\";\n $params = array();\n\n if ($arguments) {\n\n foreach($arguments as $index => $command) {\n\n $details = explode(\"=\", $command);\n\n if($details[0] == \"controller\") {\n $controller = $details[1];\n } else if($details[0] == \"action\") {\n $action = $details[1];\n } else {\n $params[$details[0]] = $details[1];\n }\n }\n\n if($action == \"\" || $controller == \"\") {\n die(\"Missing Controller and Action Arguments == You should have: \n php script.php controller=[controllername] action=[action]\");\n }\n $dispatcher->setControllerName($controller);\n $dispatcher->setActionName($action);\n $dispatcher->setParams($params);\n\n return $dispatcher;\n }\n echo \"Invalid command.\\n\", exit;\n echo \"No command given.\\n\", exit;\n }\n\n public function assemble ($userParams, $name = null, $reset = false, $encode = true)\n {\n throw new Exception(\"Assemble isnt implemented \", print_r($userParams, true));\n }\n}\n public function sendEmailCliAction()\n{ \n if (PHP_SAPI != 'cli' || !empty($_SERVER['REMOTE_ADDR'])) { \n echo \"Program cannot be run manually\\n\";\n exit(1);\n } \n // Each email sent has its status set to 0;\n * * * * * php /var/www/projectname/public/index.php controller=name action=send-email-cli >> /var/www/projectname/application/data/logs/cron.log\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19929/" ]
143,365
<p>I have a flash application running Flash 9 (CS3). Application is able to control the Softkeys when this flash application is loaded in the supported mobile device. But, the application doesn't have control when the same is embedded in HTML page and browsed via supported mobile device. Any ideas how to make this work?</p> <p>Thanks Keerthi</p>
[ { "answer_id": 144130, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 1, "selected": false, "text": "var myListener = new Object();\nmyListener.onKeyDown = function() {\n var code = Key.getCode();\n if (code==ExtendedKey.SOFT1) {\n trace(\"I got a soft key event\");\n }\n}\nKey.addListener(myListener);\n trace(System.capabilities.hasMappableSoftKeys);\ntrace(System.capabilities.softKeyCount); \n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
143,390
<p>I'm now in search for a Java Text to Speech (TTS) framework. During my investigations I've found several JSAPI1.0-(partially)-compatible frameworks listed on <a href="http://java.sun.com/products/java-media/speech/reference/codesamples/index.html" rel="noreferrer">JSAPI Implementations page</a>, as well as a pair of Java TTS frameworks which do not appear to follow JSAPI spec (<a href="http://mary.dfki.de/" rel="noreferrer">Mary</a>, <a href="http://www.say-it-now.com/mainsite.htm" rel="noreferrer">Say-It-Now</a>). I've also noted that currently no reference implementation exists for JSAPI.</p> <p>Brief tests I've done for FreeTTS (first one listed in JSAPI impls page) show that it is far from reading simple and obvious words (examples: ABC, blackboard). Other tests are currently in progress.</p> <p>And here goes the question (6, actually):</p> <ol> <li>Which of the Java-based TTS frameworks have you used?</li> <li>Which ones, by your opinion, are capable of reading the largest wordbase?</li> <li>What about their voice quality?</li> <li>What about their performance?</li> <li>Which non-Java frameworks with Java bindings are there on the scene?</li> <li>Which of them would you recommend?</li> </ol> <p>Thank you in advance for your comments and suggestions.</p>
[ { "answer_id": 148089, "author": "DiaWorD", "author_id": 17707, "author_profile": "https://Stackoverflow.com/users/17707", "pm_score": 1, "selected": false, "text": "java -jar freetts.jar some-more-args-here" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17707/" ]
143,405
<p>What are the differences in implementing interfaces <strong>implicitly</strong> and <strong>explicitly</strong> in C#?</p> <p>When should you use implicit and when should you use explicit?</p> <p>Are there any pros and/or cons to one or the other?</p> <hr> <p>Microsoft's official guidelines (from first edition <a href="https://rads.stackoverflow.com/amzn/click/com/0321246756" rel="noreferrer" rel="nofollow noreferrer">Framework Design Guidelines</a>) states that <strong>using explicit implementations are not recommended</strong>, since it gives the code unexpected behaviour.</p> <p>I think this guideline is very <strong>valid in a pre-IoC-time</strong>, when you don't pass things around as interfaces.</p> <p>Could anyone touch on that aspect as well?</p>
[ { "answer_id": 143423, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 10, "selected": true, "text": "IList.CopyTo public void CopyTo(Array array, int index)\n{\n throw new NotImplementedException();\n}\n void ICollection.CopyTo(Array array, int index)\n{\n throw new NotImplementedException();\n}\n MyClass myClass = new MyClass(); // Declared as concrete class\nmyclass.CopyTo //invalid with explicit\n((IList)myClass).CopyTo //valid with explicit.\n" }, { "answer_id": 143483, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 6, "selected": false, "text": "IEnumerable<T> public abstract class StringList : IEnumerable<string>\n{\n private string[] _list = new string[] {\"foo\", \"bar\", \"baz\"};\n\n // ...\n\n #region IEnumerable<string> Members\n public IEnumerator<string> GetEnumerator()\n {\n foreach (string s in _list)\n { yield return s; }\n }\n #endregion\n\n #region IEnumerable Members\n IEnumerator IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n #endregion\n}\n IEnumerable<string> IEnumerable StringList sl = new StringList();\n\n// uses the implicit definition.\nIEnumerator<string> enumerableString = sl.GetEnumerator();\n// same as above, only a little more explicit.\nIEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();\n// returns the same as above, but via the explicit definition\nIEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();\n" }, { "answer_id": 157490, "author": "Lee Oades", "author_id": 20508, "author_profile": "https://Stackoverflow.com/users/20508", "pm_score": 4, "selected": false, "text": "/// <summary>\n/// This is a Book\n/// </summary>\ninterface IBook\n{\n string Title { get; }\n string ISBN { get; }\n}\n\n/// <summary>\n/// This is a Person\n/// </summary>\ninterface IPerson\n{\n string Title { get; }\n string Forename { get; }\n string Surname { get; }\n}\n\n/// <summary>\n/// This is some freaky book-person.\n/// </summary>\nclass Class1 : IBook, IPerson\n{\n /// <summary>\n /// This method is shared by both Book and Person\n /// </summary>\n public string Title\n {\n get\n {\n string personTitle = \"Mr\";\n string bookTitle = \"The Hitchhikers Guide to the Galaxy\";\n\n // What do we do here?\n return null;\n }\n }\n\n #region IPerson Members\n\n public string Forename\n {\n get { return \"Lee\"; }\n }\n\n public string Surname\n {\n get { return \"Oades\"; }\n }\n\n #endregion\n\n #region IBook Members\n\n public string ISBN\n {\n get { return \"1-904048-46-3\"; }\n }\n\n #endregion\n}\n string IBook.Title\n{\n get\n {\n return \"The Hitchhikers Guide to the Galaxy\";\n }\n}\n\nstring IPerson.Title\n{\n get\n {\n return \"Mr\";\n }\n}\n\npublic string Title\n{\n get { return \"Still shared\"; }\n}\n" }, { "answer_id": 3034603, "author": "Jon Nadal", "author_id": 319002, "author_profile": "https://Stackoverflow.com/users/319002", "pm_score": 5, "selected": false, "text": "public interface INavigator {\n void Redirect(string url);\n}\n\npublic sealed class StandardNavigator : INavigator {\n void INavigator.Redirect(string url) {\n Response.Redirect(url);\n }\n}\n public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {\n private readonly CustomerComboBoxPresenter presenter;\n\n public CustomerComboBox() {\n presenter = new CustomerComboBoxPresenter(this);\n }\n\n protected override void OnLoad() {\n if (!Page.IsPostBack) presenter.HandleFirstLoad();\n }\n\n // Primary interface used by web page developers\n public Guid ClientId {\n get { return new Guid(SelectedItem.Value); }\n set { SelectedItem.Value = value.ToString(); }\n }\n\n // \"Hidden\" interface used by presenter\n IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }\n}\n" }, { "answer_id": 6140004, "author": "Yochai Timmer", "author_id": 536086, "author_profile": "https://Stackoverflow.com/users/536086", "pm_score": 3, "selected": false, "text": "interface I1\n{\n void implicitExample();\n}\n\ninterface I2\n{\n void explicitExample();\n}\n\n\nclass C : I1, I2\n{\n void implicitExample()\n {\n Console.WriteLine(\"I1.implicitExample()\");\n }\n\n\n void I2.explicitExample()\n {\n Console.WriteLine(\"I2.explicitExample()\");\n }\n}\n" }, { "answer_id": 23615330, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "Public Overridable Function Foo() As Integer Implements IFoo.Foo\n Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo\n IFoo_Foo IFoo IList<T>.Add NotSupportedException int IFoo.Foo() { return IFoo_Foo(); }\nprotected virtual int IFoo_Foo() { ... real code goes here ... }\n" }, { "answer_id": 25323397, "author": "scobi", "author_id": 14582, "author_profile": "https://Stackoverflow.com/users/14582", "pm_score": 4, "selected": false, "text": "public IMyInterface I { get { return this; } } foo.I.InterfaceMethod()" }, { "answer_id": 58412221, "author": "Marc Sigrist", "author_id": 270212, "author_profile": "https://Stackoverflow.com/users/270212", "pm_score": 2, "selected": false, "text": "public public // Given:\ninternal interface I { void M(); }\n\n// Then explicit implementation correctly observes encapsulation of I:\n// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.\npublic class CExplicit: I { void I.M() { } }\n\n// However, implicit implementation breaks encapsulation of I, because\n// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.\npublic class CImplicit: I { public void M() { } }\n public internal" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429/" ]
143,420
<p>Does anyone know how to modify an existing import specification in Microsoft Access 2007 or 2010? In older versions there used to be an Advanced button presented during the import wizard that allowed you to select and edit an existing specification. I no longer see this feature but hope that it still exists and has just been moved somewhere else.</p>
[ { "answer_id": 14443025, "author": "Mike Hansen", "author_id": 1997691, "author_profile": "https://Stackoverflow.com/users/1997691", "pm_score": 3, "selected": false, "text": "Public Sub MyExcelTransfer(myTempTable As String, myPath As String)\nOn Error GoTo ERR_Handler:\n Dim mySpec As ImportExportSpecification\n Dim myNewSpec As ImportExportSpecification\n Dim x As Integer\n\n For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1\n If CurrentProject.ImportExportSpecifications.Item(x).Name = \"TemporaryImport\" Then\n CurrentProject.ImportExportSpecifications.Item(\"TemporaryImport\").Delete\n x = CurrentProject.ImportExportSpecifications.Count\n End If\n Next x\n Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTempTable)\n CurrentProject.ImportExportSpecifications.Add \"TemporaryImport\", mySpec.XML\n Set myNewSpec = CurrentProject.ImportExportSpecifications.Item(\"TemporaryImport\")\n\n myNewSpec.XML = Replace(myNewSpec.XML, \"\\\\MyComputer\\ChangeThis\", myPath)\n myNewSpec.Execute\n myNewSpec.Delete\n Set mySpec = Nothing\n Set myNewSpec = Nothing\n exit_ErrHandler:\n For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1\n If CurrentProject.ImportExportSpecifications.Item(x).Name = \"TemporaryImport\" Then\n CurrentProject.ImportExportSpecifications.Item(\"TemporaryImport\").Delete\n x = CurrentProject.ImportExportSpecifications.Count\n End If\n Next x\nExit Sub \nERR_Handler:\n MsgBox Err.Description\n Resume exit_ErrHandler\nEnd Sub\n\nPublic Sub fixImportSpecs(myTable As String, strFind As String, strRepl As String)\n Dim mySpec As ImportExportSpecification \n Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTable) \n mySpec.XML = Replace(mySpec.XML, strFind, strRepl)\n Set mySpec = Nothing\nEnd Sub\n\n\nPublic Sub MyExcelChangeName(OldName As String, NewName As String)\n Dim mySpec As ImportExportSpecification\n Dim myNewSpec As ImportExportSpecification\n Set mySpec = CurrentProject.ImportExportSpecifications.Item(OldName) \n CurrentProject.ImportExportSpecifications.Add NewName, mySpec.XML\n mySpec.Delete\n Set mySpec = Nothing\n Set myNewSpec = Nothing\nEnd Sub\n" }, { "answer_id": 17913499, "author": "Andrew", "author_id": 2494935, "author_profile": "https://Stackoverflow.com/users/2494935", "pm_score": 2, "selected": false, "text": "SELECT \n MSysIMEXSpecs.SpecName,\n MSysIMexColumns.*\nFROM \n MSysIMEXSpecs\n LEFT JOIN MSysIMEXColumns \n ON MSysIMEXSpecs.SpecID = MSysIMEXColumns.SpecID\nWHERE\n SpecName = 'MySpecName'\nORDER BY\n MSysIMEXSpecs.SpecID, MSysIMEXColumns.Start;\n" }, { "answer_id": 64715647, "author": "Lyndra", "author_id": 7625157, "author_profile": "https://Stackoverflow.com/users/7625157", "pm_score": 0, "selected": false, "text": "Sub writeStringToFile(strPath As String, strText As String)\n '#### writes a given string into a given filePath, overwriting a document if it already exists\n Dim objStream\n \n Set objStream = CreateObject(\"ADODB.Stream\")\n objStream.Charset = \"utf-8\"\n objStream.Open\n objStream.WriteText strText\n objStream.SaveToFile strPath, 2\n End Sub\n <?xml version=\"1.0\"?>\n<ImportExportSpecification Path=\"mypath\\mydocument.xlsx\" xmlns=\"urn:www.microsoft.com/office/access/imexspec\">\n <ImportExcel FirstRowHasNames=\"true\" AppendToTable=\"myTableName\" Range=\"myExcelWorksheetName\">\n <Columns PrimaryKey=\"{Auto}\">\n <Column Name=\"Col1\" FieldName=\"SomeFieldName\" Indexed=\"NO\" SkipColumn=\"false\" DataType=\"Double\"/>\n <Column Name=\"Col2\" FieldName=\"SomeFieldName\" Indexed=\"NO\" SkipColumn=\"false\" DataType=\"Text\"/>\n </Columns>\n </ImportExcel>\n</ImportExportSpecification>\n Function modifyDataSourcePath(strNewPath As String, strXMLSpec As String) As String\n'#### Changes the path-name of an import-export specification\n Dim xDoc As MSXML2.DOMDocument60\n Dim childNodes As IXMLDOMNodeList\n Dim nodeImExSpec As MSXML2.IXMLDOMNode\n Dim childNode As MSXML2.IXMLDOMNode\n Dim attributesImExSpec As IXMLDOMNamedNodeMap\n Dim attributeImExSpec As IXMLDOMAttribute\n\n \n Set xDoc = New MSXML2.DOMDocument60\n xDoc.async = False: xDoc.validateOnParse = False\n xDoc.LoadXML (strXMLSpec)\n Set childNodes = xDoc.childNodes\n \n For Each childNode In childNodes\n If childNode.nodeName = \"ImportExportSpecification\" Then\n Set nodeImExSpec = childNode\n Exit For\n End If\n Next childNode\n \n Set attributesImExSpec = nodeImExSpec.Attributes\n \n For Each attributeImExSpec In attributesImExSpec\n If attributeImExSpec.nodeName = \"Path\" Then\n attributeImExSpec.Value = strNewPath\n Exit For\n End If\n Next attributeImExSpec\n \n modifyDataSourcePath = xDoc.XML\nEnd Function\n Set myNewSpec = CurrentProject.ImportExportSpecifications.item(\"TemporaryImport\")\n myNewSpec.XML = modifyDataSourcePath(myPath, myNewSpec.XML)\n Call writeStringToFile(Application.CurrentProject.Path & \"\\impExpSpec.xml\", myNewSpec.XML)\n myNewSpec.Execute\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
143,429
<p>We all know that commenting our code is an important part of coding style for making our code understandable to the next person who comes along, or even ourselves in 6 months or so.</p> <p>However, sometimes a comment just doesn't cut the mustard. I'm not talking about obvious jokes or vented frustraton, I'm talking about comments that appear to be making an attempt at explanation, but do it so poorly they might as well not be there. Comments that are <strong>too short</strong>, are <strong>too cryptic</strong>, or are <strong>just plain wrong</strong>. </p> <p>As a cautonary tale, could you share something you've seen that was really just <strong>that bad</strong>, and if it's not obvious, show the code it was referring to and point out what's wrong with it? What <strong>should</strong> have gone in there instead?</p> <p>See also: </p> <ul> <li><a href="https://stackoverflow.com/questions/163600/when-not-to-comment-code">When NOT to comment your code</a></li> <li><a href="https://stackoverflow.com/questions/121945/how-do-you-like-your-comments-best-practices">How do you like your comments? (Best Practices)</a></li> <li><a href="https://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered">What is the best comment in source code you have ever encountered?</a></li> </ul>
[ { "answer_id": 143439, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 8, "selected": true, "text": "$i = 0; //set i to 0\n\n$i++; //use sneaky trick to add 1 to i!\n\nif ($i==$j) { // I made sure to use == rather than = here to avoid a bug\n" }, { "answer_id": 143445, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 6, "selected": false, "text": "//@TODO: Rewrite this, it sucks. Seriously.\n" }, { "answer_id": 143453, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 5, "selected": false, "text": "// Do not remove this comment else compilation will fail.\n" }, { "answer_id": 143464, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 5, "selected": false, "text": "// Increase i by one\ni++;\n" }, { "answer_id": 143466, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 4, "selected": false, "text": "// Don't know why we have to do this\n" }, { "answer_id": 143556, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 5, "selected": false, "text": "Thread.Sleep(1000); // this will fix .NET's crappy threading implementation\n" }, { "answer_id": 143590, "author": "Axeman", "author_id": 22108, "author_profile": "https://Stackoverflow.com/users/22108", "pm_score": 3, "selected": false, "text": "dim J\nJ = 0 'magic\nJ = J 'more magic\nfor J=1 to 100\n...do stuff...\n" }, { "answer_id": 143600, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 6, "selected": false, "text": "/**\n * Method declaration\n *\n *\n * @param table\n * @param row\n *\n * @throws SQLException\n */\nvoid addTransactionDelete(Table table, Object row[]) throws SQLException {\n" }, { "answer_id": 143640, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "/**\n * @author SomeUserWhoShouldKnowBetter\n *\n * To change this generated comment edit the template variable \"typecomment\":\n * Window>Preferences>Java>Templates.\n * To enable and disable the creation of type comments go to\n * Window>Preferences>Java>Code Generation.\n */\n SWEAR_WORD_OF_CHOICE" }, { "answer_id": 143663, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 2, "selected": false, "text": "/**\n * Gets the something\n *\n * @param num The num\n * @param offset The offset\n */\npublic void getSomething(int num, bool offset)\n" }, { "answer_id": 144269, "author": "Mark", "author_id": 18264, "author_profile": "https://Stackoverflow.com/users/18264", "pm_score": 5, "selected": false, "text": "/// <summary>\n/// Toes the foo.\n/// </summary>\n/// <returns></returns>\npublic Foo ToFoo()\n" }, { "answer_id": 144289, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "/* our second do loop */\ndo {\n" }, { "answer_id": 144371, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 2, "selected": false, "text": "/* FIXME: documentation for the bellow functionality - and why are we doing it this way */\n" }, { "answer_id": 144725, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 4, "selected": false, "text": "\n /* Hmmm. A bit tricky. */\n" }, { "answer_id": 144729, "author": "Uri", "author_id": 23072, "author_profile": "https://Stackoverflow.com/users/23072", "pm_score": 2, "selected": false, "text": "// My class!\nClass myclass \n{\n //Default constructor\n public myClass()\n {\n ...\n }\n}\n" }, { "answer_id": 145458, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 2, "selected": false, "text": "# For each pose in the document\ndoc.elements.each('//pose') do |pose| ...\n\n# For each sprite in sprites\n@sprites.each do |sprite| ...\n\n# For each X in Y\nfor X in Y do ...\n" }, { "answer_id": 148622, "author": "Decio Lira", "author_id": 12423, "author_profile": "https://Stackoverflow.com/users/12423", "pm_score": 6, "selected": false, "text": "// remember to comment code\n" }, { "answer_id": 168803, "author": "Justin", "author_id": 401774, "author_profile": "https://Stackoverflow.com/users/401774", "pm_score": 5, "selected": false, "text": "// secret sauce\n" }, { "answer_id": 168840, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 3, "selected": false, "text": "/*\n MAB 08-05-2004: Who wrote this routine? When did they do it? Who should \n I call if I have questions about it? It's worth it to have a good header\n here. It should helps to set context, it should identify the author \n (hero or culprit!), including contact information, so that anyone who has\n questions can call or email. It's useful to have the date noted, and a \n brief statement of intention. On the other hand, this isn't meant to be \n busy work; it's meant to make maintenance easier--so don't go overboard.\n\n One other good reason to put your name on it: take credit! This is your\n craft\n*/\n #include \"xxxMsg.h\" // xxx messages\n/*\n MAB 08-05-2004: With respect to the comment above, I gathered that\n from the filename. I think I need either more or less here. For one\n thing, xxxMsg.h is automatically generated from the .mc file. That might\n be interesting information. Another thing is that xxxMsg.h should NOT be\n added to source control, because it's auto-generated. Alternatively, \n don't bother with a comment at all.\n*/\n /*\n MAB 08-05-2004: Defining a keyword?? This seems problemmatic [sic],\n in principle if not in practice. Is this a common idiom? \n*/\n" }, { "answer_id": 168873, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": false, "text": "//if you get here then you really f**ked\n" }, { "answer_id": 168881, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 5, "selected": false, "text": "// This method takes two integer values and adds them together via the built-in\n// .NET functionality. It would be possible to code the arithmetic function\n// by hand, but since .NET provides it, that would be a waste of time\nprivate int Add(int i, int j) // i is the first value, j is the second value\n{\n // add the numbers together using the .NET \"+\" operator\n int z = i + j;\n\n // return the value to the calling function\n // return z;\n\n // this code was updated to simplify the return statement, eliminating the need\n // for a separate variable.\n // this statement performs the add functionality using the + operator on the two\n // parameter values, and then returns the result to the calling function\n return i + j;\n}\n" }, { "answer_id": 168941, "author": "bouvard", "author_id": 24608, "author_profile": "https://Stackoverflow.com/users/24608", "pm_score": 2, "selected": false, "text": "// TODO: Documentation.\n" }, { "answer_id": 168950, "author": "CJP", "author_id": 13152, "author_profile": "https://Stackoverflow.com/users/13152", "pm_score": 2, "selected": false, "text": "/* Trickiness */\n" }, { "answer_id": 168962, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 3, "selected": false, "text": "if(some_condition){\n do_stuff();\n}\nelse{\n //An error occurred!\n}\n" }, { "answer_id": 169030, "author": "Levi Rosol", "author_id": 23458, "author_profile": "https://Stackoverflow.com/users/23458", "pm_score": 4, "selected": false, "text": "//' OOOO oooo that smell!! Can't you smell that smell!??!??!!!!11!??/!!!!!1!!!!!!1\n\nIf Not Me.CurrentMenuItem.Parent Is Nothing Then\n For Each childMenuItem As MenuItem In aMenuItem.Children\n do something\n Next\n\n If Not Me.CurrentMenuItem.Parent.Parent Is Nothing Then\n //'item is at least a grand child\n For Each childMenuItem As MenuItem In aMenuItem.Children\n For Each grandchildMenuItem As MenuItem In childMenuItem.Children\n do something\n Next\n Next\n\n If Not Me.CurrentMenuItem.Parent.Parent.Parent Is Nothing Then\n //'item is at least a grand grand child\n For Each childMenuItem As MenuItem In aMenuItem.Children\n For Each grandchildMenuItem As MenuItem In childMenuItem.Children\n For Each grandgrandchildMenuItem As MenuItem In grandchildMenuItem.Children\n do something\n Next\n Next\n Next\n\n End If\n End If\nEnd If\n" }, { "answer_id": 169092, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 4, "selected": false, "text": "try\n{\n...some code...\n}\ncatch\n{\n// Just don't crash, it wasn't that important anyway.\n}\n" }, { "answer_id": 175343, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 1, "selected": false, "text": "if #-- Whoa, now that's a big if condition.\n" }, { "answer_id": 176001, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 3, "selected": false, "text": "/******************************************************************************\n NAME: (repeat the trigger name)\n PURPOSE: To perform work as each row is inserted or updated.\n REVISIONS:\n Ver Date Author Description\n --------- ---------- --------------- ------------------------------------\n 1.0 27.6.2000 1. Created this trigger.\n PARAMETERS:\n INPUT:\n OUTPUT:\n RETURNED VALUE:\n CALLED BY:\n CALLS:\n EXAMPLE USE:\n ASSUMPTIONS:\n LIMITATIONS:\n ALGORITHM:\n NOTES:\n******************************************************************************/\n" }, { "answer_id": 176009, "author": "Paul Lefebvre", "author_id": 25615, "author_profile": "https://Stackoverflow.com/users/25615", "pm_score": 2, "selected": false, "text": "// Magic\nmenu.Visible = False\nmenu.Visible = True\n" }, { "answer_id": 176032, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "/** function header comments required to pass checkstyle */\n" }, { "answer_id": 176048, "author": "Steropes", "author_id": 21872, "author_profile": "https://Stackoverflow.com/users/21872", "pm_score": 2, "selected": false, "text": "/***************************************************************************/\n //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n" }, { "answer_id": 176050, "author": "Doron Yaacoby", "author_id": 3389, "author_profile": "https://Stackoverflow.com/users/3389", "pm_score": 2, "selected": false, "text": "//I know that this is very ugly, but I am tired and in a hurry. \n//You would do the same if you were me...\n//...\n//[A piece of nasty code here]\n" }, { "answer_id": 223242, "author": "dotnetcoder", "author_id": 29443, "author_profile": "https://Stackoverflow.com/users/29443", "pm_score": 0, "selected": false, "text": "/* this is a hack.\n ToDo: change this code */\n" }, { "answer_id": 223503, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 2, "selected": false, "text": " // do nothing\n // TODO: DAN to fix this. Not Wes. No sir. Not Wes.\n" }, { "answer_id": 223512, "author": "StubbornMule", "author_id": 13341, "author_profile": "https://Stackoverflow.com/users/13341", "pm_score": 0, "selected": false, "text": "//I am not sure why this works but it fixes the problem.\n" }, { "answer_id": 223589, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 0, "selected": false, "text": "// this is messed up, and no one actually knows how it works anymore...\n" }, { "answer_id": 247084, "author": "rshimoda", "author_id": 23297, "author_profile": "https://Stackoverflow.com/users/23297", "pm_score": 2, "selected": false, "text": "#region This is ugly but a mas has to do what a man has to do\nInitialization of a gigantic array (...)\n#endregion \n// Aren't you glad this has ended?\n" }, { "answer_id": 247198, "author": "GalacticCowboy", "author_id": 29638, "author_profile": "https://Stackoverflow.com/users/29638", "pm_score": 3, "selected": false, "text": "try\n{\n ...\n}\ncatch\n{\n // TODO: something catchy\n}\n // TODO: The following if block should be reduced to one return statememt:\n // return Regex.IsMatch(strTest, NAME_CHARS);\n if (!Regex.IsMatch(strTest, NAME_CHARS))\n return false;\n else\n return true;\n" }, { "answer_id": 247232, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 0, "selected": false, "text": "SwapArray(..); // Big endian ???\nwrite();\n" }, { "answer_id": 247451, "author": "Ace", "author_id": 18673, "author_profile": "https://Stackoverflow.com/users/18673", "pm_score": 2, "selected": false, "text": "cntrVal = \"\"+ toInteger(cntrVal) //<---MAYBE THIS IS THE WAY I'M GOING THROUGH CHANGES (comin' up comin' up) THIS IS THE WAY I WANNA LIVE\n" }, { "answer_id": 247491, "author": "Aardvark", "author_id": 3655, "author_profile": "https://Stackoverflow.com/users/3655", "pm_score": 1, "selected": false, "text": "//SFD Start\n...code...\n//SFD End\n" }, { "answer_id": 247500, "author": "endian", "author_id": 25462, "author_profile": "https://Stackoverflow.com/users/25462", "pm_score": 0, "selected": false, "text": "// This code should never be called\n" }, { "answer_id": 247625, "author": "Thomas DeGan", "author_id": 12470, "author_profile": "https://Stackoverflow.com/users/12470", "pm_score": 0, "selected": false, "text": "// Magic happens here...\n" }, { "answer_id": 247750, "author": "rlb.usa", "author_id": 449902, "author_profile": "https://Stackoverflow.com/users/449902", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n//why isn't this working!\n /*-style */" }, { "answer_id": 315540, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 3, "selected": false, "text": "<!--- Lasciate ogne speranza, voi ch'intrate --->\n" }, { "answer_id": 521961, "author": "JohnFx", "author_id": 30018, "author_profile": "https://Stackoverflow.com/users/30018", "pm_score": 1, "selected": false, "text": "a.writeline s 'write line\n" }, { "answer_id": 521978, "author": "Greg", "author_id": 12601, "author_profile": "https://Stackoverflow.com/users/12601", "pm_score": 1, "selected": false, "text": "//???\n" }, { "answer_id": 668071, "author": "Gavin Miller", "author_id": 33226, "author_profile": "https://Stackoverflow.com/users/33226", "pm_score": 0, "selected": false, "text": "/// <summary>\n/// The Page_Load runs when the page loads\n/// </summary>\nprivate void Page_Load(Object sender, EventArgs e) {}\n" }, { "answer_id": 668117, "author": "Antony Scott", "author_id": 62951, "author_profile": "https://Stackoverflow.com/users/62951", "pm_score": 1, "selected": false, "text": "if (someFlag)\n{\n // YES\n DoSomething();\n}\nelse\n{\n // NO\n DoSomethingElse();\n}\n" }, { "answer_id": 777151, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 2, "selected": false, "text": " #contentWrapper{\n position:absolute;\n top: 150px; /*80 = 30 + 50 where 50 is margin and 30 is the height of the header*/\n }\n" }, { "answer_id": 777215, "author": "Mike Cole", "author_id": 86191, "author_profile": "https://Stackoverflow.com/users/86191", "pm_score": 4, "selected": false, "text": "//TODO: Remove this comment.\n" }, { "answer_id": 777236, "author": "Mike Cole", "author_id": 86191, "author_profile": "https://Stackoverflow.com/users/86191", "pm_score": 0, "selected": false, "text": "//TODO: This needs to be reworked. THIS CRAP NEEDS TO STOP!!!\n" }, { "answer_id": 777289, "author": "jonny", "author_id": 72530, "author_profile": "https://Stackoverflow.com/users/72530", "pm_score": 2, "selected": false, "text": "/*========================================================================\n\nFUNCTION \n DtFld_SetMin\n\nDESCRIPTION\n This local function sets a nMin member of the Dtfld struct.\n\nDEPENDENCIES\n None\n\nARGUMENTS\n [in]me\n Pointer to the Dtfld struct.\n [in]val\n Value to set\n\nRETURN VALUE\n None.\n\nSIDE EFFECTS\n None\n\nNOTE\n None\n========================================================================*/\n/**\n @brief This local function sets a nMin member of the Dtfld struct..\n @param [in] me Pointer to the Dtfld struct.\n @param [in]val Value to set\n @retval None \n @note None\n @see None\n*/\n\nstatic __inline void DtFld_SetMin(DtFld *me, int val)\n{\n me->nMin = val;\n}\n" }, { "answer_id": 777328, "author": "Josef Sábl", "author_id": 53864, "author_profile": "https://Stackoverflow.com/users/53864", "pm_score": 2, "selected": false, "text": "//echo \"asdfada\";\n//echo $query.\"afadfadf\";\n" }, { "answer_id": 777358, "author": "kjv", "author_id": 1360, "author_profile": "https://Stackoverflow.com/users/1360", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Disables the web part. (Virtual method)\n/// </summary>\npublic virtual void EnableWebPart() { /* nothing - you have to override it */ }\n" }, { "answer_id": 777484, "author": "Pierre-Luc Simard", "author_id": 68554, "author_profile": "https://Stackoverflow.com/users/68554", "pm_score": 2, "selected": false, "text": "/* La passe du coyote qui tousse */\n /* The coughing coyote trick */\n" }, { "answer_id": 777512, "author": "Kapsh", "author_id": 45730, "author_profile": "https://Stackoverflow.com/users/45730", "pm_score": 0, "selected": false, "text": "{\n Long complicated code logic //Added this\n}\n" }, { "answer_id": 876238, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 1, "selected": false, "text": "// Return value does not matter\nreturn 0;\n" }, { "answer_id": 913327, "author": "vikingosegundo", "author_id": 106435, "author_profile": "https://Stackoverflow.com/users/106435", "pm_score": 1, "selected": false, "text": "# Let them send messages to the world\n#del self.irc_PRIVMSG # By deleting the method? Hello?\n" }, { "answer_id": 1288277, "author": "andersonbd1", "author_id": 125864, "author_profile": "https://Stackoverflow.com/users/125864", "pm_score": 1, "selected": false, "text": "/**\n * Implements the PaymentType interface.\n */\npublic class PaymentTypePo implements PaymentType\n" }, { "answer_id": 1544091, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 3, "selected": false, "text": "private\n //PRIVATE means PRIVATE so no comments for you\n function LoadIt(IntID: Integer): Integer;\n" }, { "answer_id": 1545805, "author": "snicker", "author_id": 160359, "author_profile": "https://Stackoverflow.com/users/160359", "pm_score": 3, "selected": false, "text": "//This causes a crash for some reason. I know the real reason but it doesn't fit on this line.\n" }, { "answer_id": 1556746, "author": "JohnFx", "author_id": 30018, "author_profile": "https://Stackoverflow.com/users/30018", "pm_score": 1, "selected": false, "text": "// other variables\n" }, { "answer_id": 1556786, "author": "Earlz", "author_id": 69742, "author_profile": "https://Stackoverflow.com/users/69742", "pm_score": 2, "selected": false, "text": "add ax,1 ;add 1 to the accumulator\n //the system can only handle 5 people right now. make sure where not over\nif(num_people>20){ \n" }, { "answer_id": 1557214, "author": "Makach", "author_id": 57731, "author_profile": "https://Stackoverflow.com/users/57731", "pm_score": 0, "selected": false, "text": "// 18042009: (Name here) made me do this\n" }, { "answer_id": 1557241, "author": "John Lechowicz", "author_id": 186384, "author_profile": "https://Stackoverflow.com/users/186384", "pm_score": 1, "selected": false, "text": "Dim huh as String 'Best name for a variable ever.\n" }, { "answer_id": 1662589, "author": "DisgruntledGoat", "author_id": 37947, "author_profile": "https://Stackoverflow.com/users/37947", "pm_score": 0, "selected": false, "text": "// it's a kind of magic (number)\n$descr_id = 2;\n$url_id = 34;\n" }, { "answer_id": 1760755, "author": "mezoid", "author_id": 39532, "author_profile": "https://Stackoverflow.com/users/39532", "pm_score": 1, "selected": false, "text": "// TODO: this is basically a copy of the code at line 743!!!\n" }, { "answer_id": 1767759, "author": "Martha", "author_id": 121333, "author_profile": "https://Stackoverflow.com/users/121333", "pm_score": 0, "selected": false, "text": "//we trick it, if forbidden, as if it had already existed\n" }, { "answer_id": 1767798, "author": "whybird", "author_id": 156118, "author_profile": "https://Stackoverflow.com/users/156118", "pm_score": 0, "selected": false, "text": "[some code]\n// [a commented out code line]\n// this line added 2004-10-24 by JD.\n// removed again 2004-11-05 by JD.\n// [another commented out code line]\n[some more code]\n" }, { "answer_id": 1767834, "author": "Secko", "author_id": 127269, "author_profile": "https://Stackoverflow.com/users/127269", "pm_score": 2, "selected": false, "text": "// HACK HACK HACK. REMOVE THIS ONCE MARLETT IS AROUND\n // this is a comment - don't delete\n" }, { "answer_id": 1767900, "author": "Elle H", "author_id": 23666, "author_profile": "https://Stackoverflow.com/users/23666", "pm_score": 1, "selected": false, "text": "/* http://youtube.com/watch?v=oHg5SJYRHA0 */\n" }, { "answer_id": 1767906, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 1, "selected": false, "text": "// Its stupid but it work\n" }, { "answer_id": 1767945, "author": "Daniel Rodriguez", "author_id": 131319, "author_profile": "https://Stackoverflow.com/users/131319", "pm_score": 0, "selected": false, "text": "...\"AI code\"...\nif(something)\n goto MyAwesomeLabel; //Who's gonna be the first to dump crap on me for this?\n...\"More Ai code\"...\n\nMyAwesomeLabel:\n //It wasn't that hard to get here, right?\n ...\"Even more AI code\"...\n" }, { "answer_id": 1889256, "author": "Dan J", "author_id": 112705, "author_profile": "https://Stackoverflow.com/users/112705", "pm_score": 1, "selected": false, "text": "/* Do the business */\n" }, { "answer_id": 2004112, "author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳", "author_id": 80243, "author_profile": "https://Stackoverflow.com/users/80243", "pm_score": 1, "selected": false, "text": "// Undocumented" }, { "answer_id": 2203103, "author": "Michael Todd", "author_id": 16623, "author_profile": "https://Stackoverflow.com/users/16623", "pm_score": 2, "selected": false, "text": "// yes, this is going to break in 2089, but, one, I'll be dead, and two, we really ought to be using\n// a different system by then\nif (yearPart >= 89)\n{\n // naughty bits removed....\n}\n" }, { "answer_id": 2390289, "author": "pestilence669", "author_id": 226917, "author_profile": "https://Stackoverflow.com/users/226917", "pm_score": 0, "selected": false, "text": "# Below is stub documentation for your module. You'd better edit it" }, { "answer_id": 3732919, "author": "EMP", "author_id": 20336, "author_profile": "https://Stackoverflow.com/users/20336", "pm_score": 2, "selected": false, "text": "// initialise the static variable to 0\ncount = 1;\n" }, { "answer_id": 3760435, "author": "dagofly", "author_id": 453875, "author_profile": "https://Stackoverflow.com/users/453875", "pm_score": 1, "selected": false, "text": "/*Added because someone asked me to add it*/\n" }, { "answer_id": 3811919, "author": "greuze", "author_id": 460306, "author_profile": "https://Stackoverflow.com/users/460306", "pm_score": 1, "selected": false, "text": "if (returnValue ==0)\n doStuff();\nelse\n System.out.println(\"Beware of you, the Dragons are coming!\");\n" }, { "answer_id": 3843271, "author": "MPelletier", "author_id": 210916, "author_profile": "https://Stackoverflow.com/users/210916", "pm_score": 2, "selected": false, "text": ";--- if LOGERR=1, errors are logged but debugging is difficult\n;--- if LOGERR=0, errors are not logged but debugging is easy\nLOGERR=1\n" }, { "answer_id": 3843352, "author": "Snekse", "author_id": 378151, "author_profile": "https://Stackoverflow.com/users/378151", "pm_score": 0, "selected": false, "text": "try\n{\n someSeeminglyTrivialMethod();\n}\ncatch (Exception e)\n{\n //Ignore. Should never happen.\n}\n catch (Exception e)\n{\n System.exit(0);\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ]
143,486
<p>I've recently read the Yahoo manifesto <a href="http://developer.yahoo.com/performance/rules.html#postload" rel="noreferrer">Best Practices for Speeding Up Your Web Site</a>. They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.</p> <p>But where exactly and when?</p> <p>Should we put it before closing <code>&lt;/html&gt;</code> or after ? And above all, when should we still put it in the <code>&lt;head&gt;</code> section?</p>
[ { "answer_id": 143496, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 2, "selected": false, "text": "</html>" }, { "answer_id": 143508, "author": "Laurie Young", "author_id": 7473, "author_profile": "https://Stackoverflow.com/users/7473", "pm_score": 3, "selected": false, "text": "</html> </body> onLoad" }, { "answer_id": 143527, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 7, "selected": true, "text": "</body></html>" }, { "answer_id": 143563, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 5, "selected": false, "text": "</body> <head> <head>" }, { "answer_id": 9035779, "author": "Luke W", "author_id": 314631, "author_profile": "https://Stackoverflow.com/users/314631", "pm_score": 4, "selected": false, "text": "</body> </body>" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
143,487
<p>I'm using netbeans on ubuntu, I would like to add some fonts to it. Could anyone tell me how this is done ?</p>
[ { "answer_id": 143496, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 2, "selected": false, "text": "</html>" }, { "answer_id": 143508, "author": "Laurie Young", "author_id": 7473, "author_profile": "https://Stackoverflow.com/users/7473", "pm_score": 3, "selected": false, "text": "</html> </body> onLoad" }, { "answer_id": 143527, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 7, "selected": true, "text": "</body></html>" }, { "answer_id": 143563, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 5, "selected": false, "text": "</body> <head> <head>" }, { "answer_id": 9035779, "author": "Luke W", "author_id": 314631, "author_profile": "https://Stackoverflow.com/users/314631", "pm_score": 4, "selected": false, "text": "</body> </body>" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
143,523
<p>Any recommended crypto libraries for Java. What I need is the ability to parse X.509 Certificates to extract the information contained in them.</p> <p>Thanks</p>
[ { "answer_id": 144128, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "java.security.cert.X509Certificate" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12344/" ]
143,530
<p>I'm having a problem with my compiler telling me there is an 'undefined reference to' a function I want to use in a library. Let me share some info on the problem:</p> <ul> <li>I'm cross compiling with gcc for C.</li> <li>I am calling a library function which is accessed through an included header which includes another header, which contains the prototype.</li> <li>I have included the headers directory using -I and i'm sure it's being found.</li> <li>I'm first creating the .o files then linking them in a separate command.</li> </ul> <p>So my thought is it might be the order in which I include the library files, but i'm not sure what is the correct way to order them. I tried with including the headers folder both before and after the .o file.</p> <p>Some suggests would be great, and maybe and explanation of how the linker does its thing.</p> <p>Thanks!</p> <hr> <p>Response to answers</p> <ul> <li>there is no .a library file, just .h and .c in the library, so -l isn't appropriate</li> <li>my understanding of a library file is that it is just a collection of header and source files, but maybe it's a collection of .o files created from the source?!</li> <li>there is no library object file being created, maybe there should be?? Yes seems I don't understand the difference between includes and libraries...i'll work on that :-)</li> </ul> <p>Thanks for all the responses! I learned a lot about libraries. I'd like to put all the responses as the accepted answer :-)</p>
[ { "answer_id": 143537, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 0, "selected": false, "text": "gcc -c mylib.c -o mylib.o\nar rcs libmylib.a mylib.o\n" }, { "answer_id": 143541, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 3, "selected": false, "text": "e_atan2.o:\n00000000 T atan2\n\ne_asinf.o:\n00000000 T asinf\n\ne_asin.o:\n00000000 T asin\n GNU assembler version 2.15 [FreeBSD] 2004-05-23 (i386-obrien-freebsd) \nusing BFD version 2.15 [FreeBSD] 2004-05-23\n/usr/bin/ld -V -dynamic-linker /libexec/ld-elf.so.1 /usr/lib/crt1.o \n/usr/lib/crti.o /usr/lib/crtbegin.o -L/usr/lib /var/tmp//ccIxJczl.o -lgcc -lc \n-lgcc /usr/lib/crtend.o /usr/lib/crtn.o\n" }, { "answer_id": 143558, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 2, "selected": false, "text": "libmylib.a myfunc() mylib.h myapp.c /* myapp.h\n** Here I will include and define my stuff\n*/\n...\n#include \"mylib.h\"\n...\n /* myapp.c\n** Here is my real code\n*/\n...\n#include \"myapp.h\"\n...\n/* Here I can use the function */\nmyfunc(3,\"XYZ\");\n myapp.o gcc -c -I../mylib/includes myapp.c\n gcc -o myapp -L../mylib/libs myapp.o -lmylib\n -L -l" }, { "answer_id": 143638, "author": "Jeff", "author_id": 15797, "author_profile": "https://Stackoverflow.com/users/15797", "pm_score": 1, "selected": false, "text": "LIBFLAGS =-lc -lpthread -lrt -lstdc++ -lShared -L../shared\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ]
143,552
<p>In MySQL, If I have a list of date ranges (range-start and range-end). e.g.</p> <pre><code>10/06/1983 to 14/06/1983 15/07/1983 to 16/07/1983 18/07/1983 to 18/07/1983 </code></pre> <p>And I want to check if another date range contains ANY of the ranges already in the list, how would I do that?</p> <p>e.g.</p> <pre><code>06/06/1983 to 18/06/1983 = IN LIST 10/06/1983 to 11/06/1983 = IN LIST 14/07/1983 to 14/07/1983 = NOT IN LIST </code></pre>
[ { "answer_id": 143568, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 10, "selected": true, "text": " |-------------------| compare to this one\n |---------| contained within\n |----------| contained within, equal start\n |-----------| contained within, equal end\n |-------------------| contained within, equal start+end\n |------------| not fully contained, overlaps start\n |---------------| not fully contained, overlaps end\n |-------------------------| overlaps start, bigger\n |-----------------------| overlaps end, bigger\n |------------------------------| overlaps entire period\n |-------------------| compare to this one\n |---| ends before\n |---| starts after\n starts after end\nends before start\n |-------------|\n |-------| equal end with start of comparison period\n |-----| equal start with end of comparison period\n SELECT *\nFROM periods\nWHERE NOT (range_start > @check_period_end\n OR range_end < @check_period_start)\n SELECT *\nFROM periods\nWHERE range_start <= @check_period_end\n AND range_end >= @check_period_start\n" }, { "answer_id": 143575, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 3, "selected": false, "text": "where ('1983-06-06' <= end) and ('1983-06-18' >= start)\n" }, { "answer_id": 5864708, "author": "jonavon", "author_id": 167540, "author_profile": "https://Stackoverflow.com/users/167540", "pm_score": 0, "selected": false, "text": "DELIMITER ;;\n\nCREATE FUNCTION overlap_interval(x INT,y INT,a INT,b INT)\nRETURNS INTEGER DETERMINISTIC\nBEGIN\nDECLARE\n overlap_amount INTEGER;\n IF (((x <= a) AND (a < y)) OR ((x < b) AND (b <= y)) OR (a < x AND y < b)) THEN\n IF (x < a) THEN\n IF (y < b) THEN\n SET overlap_amount = y - a;\n ELSE\n SET overlap_amount = b - a;\n END IF;\n ELSE\n IF (y < b) THEN\n SET overlap_amount = y - x;\n ELSE\n SET overlap_amount = b - x;\n END IF;\n END IF;\n ELSE\n SET overlap_amount = 0;\n END IF;\n RETURN overlap_amount;\nEND ;;\n\nDELIMITER ;\n" }, { "answer_id": 8557604, "author": "Rama Subba Reddy M", "author_id": 868917, "author_profile": "https://Stackoverflow.com/users/868917", "pm_score": 0, "selected": false, "text": " SELECT DISTINCT RelatedTo,CAST(NotificationContent as nvarchar(max)) as NotificationContent,\n ID,\n Url,\n NotificationPrefix,\n NotificationDate\n FROM NotificationMaster as nfm\n inner join NotificationSettingsSubscriptionLog as nfl on nfm.NotificationDate between nfl.LastSubscribedDate and isnull(nfl.LastUnSubscribedDate,GETDATE())\n where ID not in(SELECT NotificationID from removednotificationsmaster where Userid=@userid) and nfl.UserId = @userid and nfl.RelatedSettingColumn = RelatedTo\n" }, { "answer_id": 14312925, "author": "Paul Williamson", "author_id": 1976318, "author_profile": "https://Stackoverflow.com/users/1976318", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION overlap_date(s DATE, e DATE, a DATE, b DATE)\nRETURNS BOOLEAN DETERMINISTIC\nRETURN s BETWEEN a AND b or e BETWEEN a and b or a BETWEEN s and e;\n" }, { "answer_id": 27815104, "author": "RickyS", "author_id": 4427966, "author_profile": "https://Stackoverflow.com/users/4427966", "pm_score": 0, "selected": false, "text": "WITH date_range (calc_date) AS (\nSELECT DATEADD(DAY, DATEDIFF(DAY, 0, [ending date]) - DATEDIFF(DAY, [start date], [ending date]), 0)\nUNION ALL SELECT DATEADD(DAY, 1, calc_date)\nFROM date_range \nWHERE DATEADD(DAY, 1, calc_date) <= [ending date])\nSELECT P.[fieldstartdate], P.[fieldenddate]\nFROM date_range R JOIN [yourBaseTable] P on Convert(date, R.calc_date) BETWEEN convert(date, P.[fieldstartdate]) and convert(date, P.[fieldenddate]) \nGROUP BY P.[fieldstartdate], P.[fieldenddate];\n" }, { "answer_id": 33148731, "author": "Florian HENRY - Scopen", "author_id": 2418749, "author_profile": "https://Stackoverflow.com/users/2418749", "pm_score": 0, "selected": false, "text": "SELECT *\nFROM periods\nWHERE @check_period_start BETWEEN range_start AND range_end\n AND @check_period_end BETWEEN range_start AND range_end\n SELECT *\nFROM periods\nWHERE (@check_period_start NOT BETWEEN range_start AND range_end\n OR @check_period_end NOT BETWEEN range_start AND range_end)\n" }, { "answer_id": 44704468, "author": "Gio", "author_id": 8200935, "author_profile": "https://Stackoverflow.com/users/8200935", "pm_score": -1, "selected": false, "text": "SELECT * \nFROM tabla a \nWHERE ( @Fini <= a.dFechaFin AND @Ffin >= a.dFechaIni )\n AND ( (@Fini >= a.dFechaIni AND @Ffin <= a.dFechaFin) OR (@Fini >= a.dFechaIni AND @Ffin >= a.dFechaFin) OR (a.dFechaIni>=@Fini AND a.dFechaFin <=@Ffin) OR\n(a.dFechaIni>=@Fini AND a.dFechaFin >=@Ffin) )\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5777/" ]
143,554
<p>I have written a ruby script which opens up dlink admin page in firefox and does a ADSL connection or disconnection.</p> <p>I could run this script in the terminal without any problem. But if I put it as cron job, it doesn't fire up firefox.</p> <p>This is the entry I have in <em>crontab</em></p> <pre><code># connect to dataone 55 17 * * * ruby /home/raguanu/Dropbox/nettie.rb &gt;&gt; /tmp/cron_test </code></pre> <p>I see the following entries in /tmp/cron_test. So it looks like the script indeed ran.</p> <pre><code>PROFILE: i486-linux /usr/bin/firefox -jssh </code></pre> <p>But I couldn't figure out why I didn't see firefox opening up, for this automation to work. Here is <em>/home/raguanu/Dropbox/nettie.rb</em></p> <pre><code>#!/usr/bin/ruby -w require 'rubygems' require 'firewatir' require 'optiflag' module Options extend OptiFlagSet character_flag :d do long_form 'disconnect' description 'Mention this flag if you want to disconnect dataone' end flag :l do optional long_form 'admin_link' default 'http://192.168.1.1' description 'Dlink web administration link. Defaults to http://192.168.1.1' end flag :u do optional long_form 'user' default 'admin' description 'Dlink administrator user name. Defaults to "admin"' end flag :p do optional long_form 'password' default 'admin' description 'Dlink administrator password. Defaults to "admin"' end flag :c do optional long_form 'connection_name' default 'bsnl' description 'Dataone connection name. Defaults to "bsnl"' end extended_help_flag :h do long_form 'help' end and_process! end class DlinkAdmin include FireWatir def initialize(admin_link = "http://192.168.1.1", user = 'admin', pwd = 'admin') @admin_link, @user, @pwd = admin_link, user, pwd end def connect( connection_name = 'bsnl' ) goto_connection_page connection_name # disconnect prior to connection @browser.button(:value, 'Disconnect').click # connect @browser.button(:value, 'Connect').click # done! @browser.close end def disconnect( connection_name = 'bsnl' ) goto_connection_page connection_name # disconnect @browser.button(:value, 'Disconnect').click # done! @browser.close end private def goto_connection_page( connection_name = 'bsnl') @browser ||= Firefox.new @browser.goto(@admin_link) # login @browser.text_field(:name, 'uiViewUserName').set(@user) @browser.text_field(:name, 'uiViewPassword').set(@pwd) @browser.button(:value,'Log In').click # setup &gt; dataone @browser.image(:alt, 'Setup').click @browser.link(:text, connection_name).click end end admin = DlinkAdmin.new(Options.flags.l, Options.flags.u, Options.flags.p) unless Options.flags.d? admin.connect( Options.flags.c ) else admin.disconnect( Options.flags.c ) end </code></pre> <p>Any help is appreciated.</p>
[ { "answer_id": 143596, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 0, "selected": false, "text": "#min hour day month dow user command\n55 17 * * * ur_user_is_missing ruby /home/raguanu/Dropbox/nettie.rb >> /tmp/cron_test\n" }, { "answer_id": 143605, "author": "Roshan", "author_id": 15806, "author_profile": "https://Stackoverflow.com/users/15806", "pm_score": 3, "selected": true, "text": "Xvfb :1 -screen 0 1600x1200x32\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15139/" ]
143,566
<p>I've been thinking a lot lately about a music-oriented project I'd like to work on. Kind of like a game... kind of like a studio workstation (FL Studio, Reason).</p> <p>I guess the best way to describe it would be: like "Guitar Hero", but with no canned tracks. All original music--composed by you, on the fly--but the software would use its knowledge of music theory (as well as some supervised learning algorithms) to make sure that your input gets turned into something that sounds great.</p> <p>It sounds a little silly, explaining it like that, but there ya go. It's something I think would make an interesting side project.</p> <p>Anyhow, I'm looking for a Java library for generating the actual audio. Browsing around on sourceforge, there are countless software synths, and I have no idea which to choose.</p> <p>My top priority is that it should sound incredible... Really rich, layered, textured synths, with gobs of configurable parameters. Emulation of acoustic instruments is not important to me.</p> <p>My second priority is that it ought to be straightforward to use strictly as a library, with no GUI involved at all. (If there's a synth with really breathtaking output, but it's tightly-coupled with a GUI, then I might consider ripping the audio portion out of the application, but I'd rather start with a nicely contained library).</p> <p>I know I could send MIDI to a standalone synth, but I think it'd be cool to read the actual synth code and learn a little DSP while I'm at it.</p> <p>Any suggestions?</p> <p>Oh yeah, I'm on Windows, so posix-only stuff is a no go.</p> <p>Thanks!</p>
[ { "answer_id": 143634, "author": "benjismith", "author_id": 22979, "author_profile": "https://Stackoverflow.com/users/22979", "pm_score": 2, "selected": false, "text": "Synth s = new Synth();\nInstrument i = s.getInstrument(\"Robot Bass\");\ni.makeAwesome(true);\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22979/" ]
143,571
<p>I'm building my first ASP.NET MVC application and I am having some troubles with Partial Views.</p> <p>If I, as an example, want to put a "Footer" as a Partial I create an "MVC View User Control" in "/Views/Shared/Footer.ascx". (I leave it empty for now)</p> <p>What is the correct way for adding it to my Layout? </p> <p>I have tried:</p> <pre><code>&lt;%=Html.RenderPartial("Footer")%&gt; </code></pre> <p>and:</p> <pre><code>&lt;%=Html.RenderPartial("~/Views/Shared/Footer.ascx")%&gt; </code></pre> <p>For each one I get an exception: </p> <blockquote> <p>"CS1502: The best overloaded method match for 'System.IO.TextWriter.Write(char)' has some invalid arguments"</p> </blockquote> <p>What is the correct way to deal with partials in ASP.NET MVC?</p>
[ { "answer_id": 143594, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 4, "selected": false, "text": "<% Html.RenderPartial(\"~/Views/Shared/Footer.ascx\"); %>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
143,622
<p>This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?</p> <pre><code>try { // Do something } catch(IOException e) { throw new ApplicationException("Problem connecting to server"); } catch(Exception e) { // Will the ApplicationException be caught here? } </code></pre> <p>I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.</p>
[ { "answer_id": 143628, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 9, "selected": true, "text": "throw try" }, { "answer_id": 143671, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": false, "text": "public class Catch {\n public static void main(String[] args) {\n try {\n throw new java.io.IOException();\n } catch (java.io.IOException exc) {\n System.err.println(\"In catch IOException: \"+exc.getClass());\n throw new RuntimeException();\n } catch (Exception exc) {\n System.err.println(\"In catch Exception: \"+exc.getClass());\n } finally {\n System.err.println(\"In finally\");\n }\n }\n}\n" }, { "answer_id": 143674, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "try {\n doSomething();\n} catch (IOException) {\n try {\n doSomething();\n } catch (IOException e) {\n throw new ApplicationException(\"Failed twice at doSomething\" +\n e.toString());\n } \n} catch (Exception e) {\n}\n" }, { "answer_id": 17111311, "author": "Mastergeek", "author_id": 965571, "author_profile": "https://Stackoverflow.com/users/965571", "pm_score": 3, "selected": false, "text": "public void doStuff() throws MyException {\n try {\n //Stuff\n } catch(StuffException e) {\n throw new MyException();\n }\n}\n" }, { "answer_id": 20308711, "author": "Ted K", "author_id": 2324774, "author_profile": "https://Stackoverflow.com/users/2324774", "pm_score": -1, "selected": false, "text": "try {\n // Do something\n} catch(IOException ioE) {\n throw new ApplicationException(\"Problem connecting to server\");\n} catch(Exception e) {\n // Will the ApplicationException be caught here?\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/270/" ]
143,632
<p>Any recommended crypto libraries for Python. I know I've asked something similar in <a href="https://stackoverflow.com/questions/143523/">x509 certificate parsing libraries for Java</a>, but I should've split the question in two.</p> <p>What I need is the ability to parse X.509 Certificates to extract the information contained in them.</p> <p>Looking around, I've found two options:</p> <ul> <li>Python OpenSSL Wrappers (<a href="http://sourceforge.net/projects/pow" rel="nofollow noreferrer" title="Python OpenSSL Wrappers">http://sourceforge.net/projects/pow</a>)</li> <li><a href="https://github.com/pyca/pyopenssl" rel="nofollow noreferrer">pyOpenSSL</a></li> </ul> <p>Of the two, pyOpenSSL seems to be the most "maintained", but I'd like some feedback on anybody who might have experience with them?</p>
[ { "answer_id": 70135187, "author": "Saikat", "author_id": 1594823, "author_profile": "https://Stackoverflow.com/users/1594823", "pm_score": 0, "selected": false, "text": "keyczar tink" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12344/" ]
143,651
<p>I have written an application which has a modal form. How can I ensure that this form does not lose the focus even when an other application is started?</p>
[ { "answer_id": 143698, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 0, "selected": false, "text": "SetForegroundWindow(Me.Handle)\n Declare Unicode Function SetForegroundWindow Lib \"user32.dll\" (ByVal hWnd As IntPtr) As Boolean\n Declare Unicode Function SystemParametersInfo Lib \"user32.dll\" Alias \"SystemParametersInfoW\" (ByVal uiAction As Int32, ByVal uiParam As Int32, ByRef pvParam As Int32, ByVal fWinIni As Int32) As Int32\n Dim _timeout As Int32\n SystemParametersInfo(&H2000, 0, _timeout, 0)\n SystemParametersInfo(&H2001, 0, 0, 3)\n SetForegroundWindow(Me.Handle)\n SystemParametersInfo(&H2001, 0, _timeout, 2)\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
143,680
<p>It seems that most of the installers for Perl are centered around installing Perl modules, not applications. Things like ExtUtils::MakeMaker and Module::Build are very well suited for modules, but require some additional work for Web Apps.</p> <p>Ideally it would be nice to be able to do the following after checking out the source from the repository:</p> <ul> <li>Have missing dependencies detected</li> <li>Download and install dependencies from CPAN</li> <li>Run a command to "Build" the source into a final state (perform any source parsing or configuration necessary for the local environment).</li> <li>Run a command to install the built files into the appropriate locations. Not only the perl modules, but also things like template (.tt) files, and CGI scripts, JS and image files that should be web-accessible.</li> <li>Make sure proper permissions are set on installed files (and SELinux context if necessary).</li> </ul> <p>Right now we have a system based on <strong>Module::Build</strong> that does most of this. The work was done by done by my co-worker who was learning to use <strong>Module::Build</strong> at the time, and we'd like some advice on generalizing our solution, since it's fairly app-specific right now. In particular, our system requires us to install dependencies by hand (although it does detect them).</p> <p>Is there any particular system you've used that's been particularly successful? Do you have to write an installer based on <strong>Module::Build</strong> or <strong>ExtUtils::MakeMaker</strong> that's particular to your application, or is something more general available?</p> <p><strong>EDIT:</strong> To answer brian's questions below:</p> <ul> <li>We can log into the machines</li> <li>We do not have root access to the machines</li> <li>The machines are all (ostensibly) identical builds of RHEL5 with SELinux enabled</li> <li>Currently, the people installing the machines are only programmers from our group, and our source is not available to the general public. However, it's conceivable our source could eventually be installed on someone else's machines in our organization, to be installed by their programmers or systems people.</li> <li>We install by checking out from the repository, though we'd like to have the option of using a distributed archive (see above).</li> </ul>
[ { "answer_id": 144216, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 4, "selected": true, "text": "MakeMaker MakeMaker Module::Build Module::Build cpan $ cpan .\n Module::Build Module::Build Module::Build" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ]
143,712
<p>Is there a way of comparing two bitmasks in Transact-SQL to see if any of the bits match? I've got a User table with a bitmask for all the roles the user belongs to, and I'd like to select all the users that have <em>any</em> of the roles in the supplied bitmask. So using the data below, a roles bitmask of 6 (designer+programmer) should select Dave, Charlie and Susan, but not Nick.</p> <pre>User Table ---------- ID Username Roles 1 Dave 6 2 Charlie 2 3 Susan 4 4 Nick 1 Roles Table ----------- ID Role 1 Admin 2 Programmer 4 Designer</pre> <p>Any ideas? Thanks.</p>
[ { "answer_id": 143919, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "SELECT * FROM UserTable WHERE Roles & 2 = 2\n" }, { "answer_id": 3561763, "author": "ScottE", "author_id": 112194, "author_profile": "https://Stackoverflow.com/users/112194", "pm_score": 2, "selected": false, "text": "DECLARE @Mask int\nSET @Mask = 6\n\nDECLARE @Users TABLE\n(\nID int,\nUsername varchar(50),\nRoles int\n)\n\nINSERT INTO @Users (ID, Username, Roles) \nSELECT 1, 'Dave', 6\nUNION\nSELECT 2, 'Charlie', 2\nUNION\nSELECT 3, 'Susan', 4\nUNION\nSELECT 4, 'Nick', 1\n\nSELECT * FROM @Users WHERE Roles & @Mask > 0\n" }, { "answer_id": 9262624, "author": "Ben", "author_id": 1139212, "author_profile": "https://Stackoverflow.com/users/1139212", "pm_score": 3, "selected": false, "text": "SELECT * FROM UserTable WHERE Roles & 6 > 0\n" }, { "answer_id": 9263250, "author": "Jamiec", "author_id": 219661, "author_profile": "https://Stackoverflow.com/users/219661", "pm_score": 8, "selected": true, "text": "& SELECT * FROM UserTable WHERE Roles & 6 != 0\n 6 1 2 4\n------------------\nDave 0 1 1\nCharlie 0 1 0\nSusan 0 0 1 \nNick 1 0 0\n 1 2 4\n------------------\nTest 0 1 1\n 1 2 4\n------------------\nDave 0 1 1 \nTest 0 1 1\nResult 0 1 1 (6)\n\nCharlie 0 1 0\nTest 0 1 1\nResult 0 1 0 (2)\n\nSusan 0 0 1\nTest 0 1 1\nResult 0 0 1 (4)\n\nNick 1 0 0\nTest 0 1 1\nResult 0 0 0 (0) \n with test (id, username, roles)\nAS\n(\n SELECT 1,'Dave',6\n UNION SELECT 2,'Charlie',2\n UNION SELECT 3,'Susan',4\n UNION SELECT 4,'Nick',1\n)\nselect * from test where (roles & 6) != 0 // returns dave, charlie & susan\n select * from test where (roles & 2) != 0 // returns Dave & Charlie\n select * from test where (roles & 7) != 0 // returns dave, charlie, susan & nick\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
143,714
<p>In PHP, a string enclosed in "double quotes" will be parsed for variables to replace whereas a string enclosed in 'single quotes' will not. In Python, does this also apply?</p>
[ { "answer_id": 143719, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 8, "selected": true, "text": "' \" \\" }, { "answer_id": 143730, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 5, "selected": false, "text": "\"this doesn't require escaping the single quote\"\n'she said \"quoting is easy in python\"'\n" }, { "answer_id": 143732, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 0, "selected": false, "text": "String HtmlInJava = \"<body bgcolor=\\\"Pink\\\">\"\n html_in_python = '<body bgcolor=\"Pink\">'\n multiline_python_string = \"\"\"\nThis is a multi-line Python string which contains line breaks in the \nresulting string variable, so this string has a '\\n' after the word\n'resulting' and the first word 'word'.\"\"\"\n" }, { "answer_id": 143748, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 3, "selected": false, "text": "'a \"quoted\" word'\n\"another 'quoted' word\"\n name = 'John'\nlastname = 'Smith'\nprint 'My name is %(name)s %(lastname)s' % locals() # prints 'My name is John Smith'\n" }, { "answer_id": 143753, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 3, "selected": false, "text": "irb(main):001:0> puts \"string1\\nstring2\"\nstring1\nstring2\n=> nil\nirb(main):002:0> puts 'string1\\nstring2'\nstring1\\nstring2\n=> nil\n >>> print 'string1\\nstring2'\nstring1\nstring2\n>>> print r'string1\\nstring2'\nstring1\\nstring2\n" }, { "answer_id": 25527252, "author": "gseattle", "author_id": 962391, "author_profile": "https://Stackoverflow.com/users/962391", "pm_score": -1, "selected": false, "text": "import time\n\ntime_single = 0\ntime_double = 0\n\nfor i in range(10000000):\n # String Using Single Quotes\n time1 = time.time()\n str_single1 = 'Somewhere over the rainbow dreams come true'\n str_single2 = str_single1\n time2 = time.time()\n time_elapsed = time2 - time1\n time_single += time_elapsed\n\n # String Using Double Quotes \n time3 = time.time()\n str_double1 = \"Somewhere over the rainbow dreams come true\"\n str_double2 = str_double1\n time4 = time.time()\n time_elapsed = time4 - time3\n time_double += time_elapsed\n\nprint 'Time using single quotes: ' + str(time_single)\nprint 'Time using double quotes: ' + str(time_double)\n >python_quotes_test.py\nTime using single quotes: 13.9079978466\nTime using double quotes: 14.5360121727\n" }, { "answer_id": 34575964, "author": "Thorsten", "author_id": 5740232, "author_profile": "https://Stackoverflow.com/users/5740232", "pm_score": 3, "selected": false, "text": ">>> \"text\"\n'text'\n\n>>> 'text'\n'text'\n" }, { "answer_id": 36007665, "author": "kxr", "author_id": 1184933, "author_profile": "https://Stackoverflow.com/users/1184933", "pm_score": 3, "selected": false, "text": "gettext" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183/" ]
143,736
<p>I have a simple message box in a WPF application that is launched as below:</p> <pre><code>private void Button_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Howdy", "Howdy"); } </code></pre> <p>I can get <a href="http://www.codeplex.com/white" rel="nofollow noreferrer" title="white">white</a> to click my button and launch the message box. </p> <p>UISpy shows it as a child of my window I couldn't work out the method to access it.</p> <p>How do I get access to my MessageBox to verify its contents?</p>
[ { "answer_id": 143766, "author": "Brownie", "author_id": 6600, "author_profile": "https://Stackoverflow.com/users/6600", "pm_score": 3, "selected": true, "text": " var app = Application.Launch(@\"c:\\ApplicationPath.exe\");\n var window = app.GetWindow(\"Window1\");\n var helloButton = window.Get<Button>(\"Hello\");\n Assert.IsNotNull(helloButton);\n helloButton.Click();\n var messageBox = window.MessageBox(\"Howdy\");\n Assert.IsNotNull(messageBox);\n" }, { "answer_id": 11826654, "author": "Jeroen de Bekker", "author_id": 581255, "author_profile": "https://Stackoverflow.com/users/581255", "pm_score": 1, "selected": false, "text": "[TestFixture, WinFormCategory, WPFCategory]\npublic class MessageBoxTest : ControlsActionTest\n{\n [Test]\n public void CloseMessageBoxTest()\n {\n window.Get<Button>(\"buttonLaunchesMessageBox\").Click();\n Window messageBox = window.MessageBox(\"Close Me\");\n var label = window.Get<Label>(\"65535\");\n Assert.AreEqual(\"Close Me\", label.Text);\n messageBox.Close();\n }\n\n [Test]\n public void ClickButtonOnMessageBox()\n {\n window.Get<Button>(\"buttonLaunchesMessageBox\").Click();\n Window messageBox = window.MessageBox(\"Close Me\");\n messageBox.Get<Button>(SearchCriteria.ByText(\"OK\")).Click();\n }\n}\n" }, { "answer_id": 13670760, "author": "embarus", "author_id": 147572, "author_profile": "https://Stackoverflow.com/users/147572", "pm_score": 2, "selected": false, "text": " Window messageBox = window.MessageBox(\"\");\n var label = messageBox.Get<Label>(SearchCriteria.Indexed(0));\n Assert.AreEqual(\"Hello\",label.Text);\n" }, { "answer_id": 35219222, "author": "陸普世", "author_id": 2902212, "author_profile": "https://Stackoverflow.com/users/2902212", "pm_score": 1, "selected": false, "text": "[TestMethod]\npublic void TestMethod()\n{\n // arrange\n var app = Application.Launch(@\"c:\\ApplicationPath.exe\");\n var targetWindow = app.GetWindow(\"Window1\");\n Button button = targetWindow.Get<Button>(\"Button\");\n\n // act\n button.Click(); \n\n var actual = GetMessageBox(targetWindow, \"Application Error\", 1000L);\n\n // assert\n Assert.IsNotNull(actual); // I want to see the messagebox appears.\n // Assert.IsNull(actual); // I don't want to see the messagebox apears.\n}\n\nprivate void GetMessageBox(Window targetWindow, string title, long timeOutInMillisecond)\n{\n Window window = null ;\n\n Thread t = new Thread(delegate()\n {\n window = targetWindow.MessageBox(title);\n });\n t.Start();\n\n long l = CurrentTimeMillis();\n while (CurrentTimeMillis() - l <= timeOutInMillsecond) { }\n\n if (window == null)\n t.Abort();\n\n return window;\n}\n\npublic static class DateTimeUtil\n{\n private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n public static long currentTimeMillis()\n {\n return (long)((DateTime.UtcNow - Jan1st1970).TotalMilliseconds);\n }\n}\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6600/" ]
143,739
<p>How do you do your own fonts? I don't want a heavyweight algorithm (freetype, truetype, adobe, etc) and would be fine with pre-rendered bitmap fonts.</p> <p>I do want anti-aliasing, and would like proportional fonts if possible.</p> <p>I've heard I can use Gimp to do the rendering (with some post processing?)</p> <p>I'm developing for an embedded device with an LCD. It's got a 32 bit processor, but I don't want to run Linux (overkill - too much code/data space for too little functionality that I would use)</p> <p>C. C++ if necessary, but C is preferred. Algorithms and ideas/concepts are fine in any language...</p> <p>-Adam</p>
[ { "answer_id": 143810, "author": "SteinNorheim", "author_id": 19220, "author_profile": "https://Stackoverflow.com/users/19220", "pm_score": 3, "selected": true, "text": "LetterA db 01111100b\n db 11000110b\n db 11000110b\n db 11111110b\n db 11000110b\n db 11000110b\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/143739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]