qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
244,531
<p>I need to search a string and replace all occurrences of <code>%FirstName%</code> and <code>%PolicyAmount%</code> with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the <code>String.Replace()</code> method. I've seen web pages on the subject that suggest</p> <pre><code>Regex.Replace(strInput, strToken, strReplaceWith, RegexOptions.IgnoreCase); </code></pre> <p>However for some reason when I try and replace <code>%PolicyAmount%</code> with <code>$0</code>, the replacement never takes place. I assume that it has something to do with the dollar sign being a reserved character in regex. </p> <p>Is there another method I can use that doesn't involve sanitizing the input to deal with regex special characters?</p>
[ { "answer_id": 244539, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "Regex.Replace(strInput, strToken.Replace(\"$\", \"[$]\"), strReplaceWith, RegexOptions.IgnoreCase);\n" }, { "answer_id": 244585, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 8, "selected": true, "text": "string value = Regex.Replace(\"%PolicyAmount%\", \"%PolicyAmount%\", @\"$$0\", RegexOptions.IgnoreCase);\n" }, { "answer_id": 244933, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 8, "selected": false, "text": "string.Replace StringComparison public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)\n{\n StringBuilder sb = new StringBuilder();\n\n int previousIndex = 0;\n int index = str.IndexOf(oldValue, comparison);\n while (index != -1)\n {\n sb.Append(str.Substring(previousIndex, index - previousIndex));\n sb.Append(newValue);\n index += oldValue.Length;\n\n previousIndex = index;\n index = str.IndexOf(oldValue, index, comparison);\n }\n sb.Append(str.Substring(previousIndex));\n\n return sb.ToString();\n}\n" }, { "answer_id": 3551121, "author": "CleverPatrick", "author_id": 22399, "author_profile": "https://Stackoverflow.com/users/22399", "pm_score": 5, "selected": false, "text": "string res = Microsoft.VisualBasic.Strings.Replace(res, \n \"%PolicyAmount%\", \n \"$0\", \n Compare: Microsoft.VisualBasic.CompareMethod.Text);\n" }, { "answer_id": 4627100, "author": "Allanrbo", "author_id": 40645, "author_profile": "https://Stackoverflow.com/users/40645", "pm_score": 2, "selected": false, "text": "int n = myText.IndexOf(oldValue, System.StringComparison.InvariantCultureIgnoreCase);\nif (n >= 0)\n{\n myText = myText.Substring(0, n)\n + newValue\n + myText.Substring(n + oldValue.Length);\n}\n" }, { "answer_id": 6755752, "author": "rboarman", "author_id": 131818, "author_profile": "https://Stackoverflow.com/users/131818", "pm_score": 5, "selected": false, "text": "public static class StringExtensions\n{\n public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)\n {\n int startIndex = 0;\n while (true)\n {\n startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);\n if (startIndex == -1)\n break;\n\n originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);\n\n startIndex += newValue.Length;\n }\n\n return originalString;\n }\n\n}\n" }, { "answer_id": 12051066, "author": "Karl Glennon", "author_id": 23393, "author_profile": "https://Stackoverflow.com/users/23393", "pm_score": 4, "selected": false, "text": " /// <summary>\n /// A case insenstive replace function.\n /// </summary>\n /// <param name=\"originalString\">The string to examine.(HayStack)</param>\n /// <param name=\"oldValue\">The value to replace.(Needle)</param>\n /// <param name=\"newValue\">The new value to be inserted</param>\n /// <returns>A string</returns>\n public static string CaseInsenstiveReplace(string originalString, string oldValue, string newValue)\n {\n Regex regEx = new Regex(oldValue,\n RegexOptions.IgnoreCase | RegexOptions.Multiline);\n return regEx.Replace(originalString, newValue);\n }\n" }, { "answer_id": 24580455, "author": "ruffin", "author_id": 1028230, "author_profile": "https://Stackoverflow.com/users/1028230", "pm_score": 6, "selected": false, "text": "public static string ReplaceCaseInsensitiveFind(this string str, string findMe,\n string newValue)\n{\n return Regex.Replace(str,\n Regex.Escape(findMe),\n Regex.Replace(newValue, \"\\\\$[0-9]+\", @\"$$$0\"),\n RegexOptions.IgnoreCase);\n}\n \"œ\".ReplaceCaseInsensitiveFind(\"oe\", \"\") Escape newValue $ \"This is HIS fork, hIs spoon, hissssssss knife.\".ReplaceCaseInsensitiveFind(\"his\", @\"he$0r\") An unhandled exception of type 'System.ArgumentException' occurred in System.dll\n\nAdditional information: parsing \"The\\hisr\\ is\\ he\\HISr\\ fork,\\ he\\hIsr\\ spoon,\\ he\\hisrsssssss\\ knife\\.\" - Unrecognized escape sequence \\h.\n $10 $ Regex.Escape $0" }, { "answer_id": 25318933, "author": "Brandon", "author_id": 738665, "author_profile": "https://Stackoverflow.com/users/738665", "pm_score": 1, "selected": false, "text": " public static string ReplaceCaseInsensative( this string s, string oldValue, string newValue ) {\n var sb = new StringBuilder(s);\n int offset = oldValue.Length - newValue.Length;\n int matchNo = 0;\n foreach (Match match in Regex.Matches(s, Regex.Escape(oldValue), RegexOptions.IgnoreCase))\n {\n sb.Remove(match.Index - (offset * matchNo), match.Length).Insert(match.Index - (offset * matchNo), newValue);\n matchNo++;\n }\n return sb.ToString();\n }\n" }, { "answer_id": 25426773, "author": "JeroenV", "author_id": 3964020, "author_profile": "https://Stackoverflow.com/users/3964020", "pm_score": 3, "selected": false, "text": "public static string ReplaceCaseInsensitive(this string str, string oldValue, string newValue)\n{\n int prevPos = 0;\n string retval = str;\n // find the first occurence of oldValue\n int pos = retval.IndexOf(oldValue, StringComparison.InvariantCultureIgnoreCase);\n\n while (pos > -1)\n {\n // remove oldValue from the string\n retval = retval.Remove(pos, oldValue.Length);\n\n // insert newValue in it's place\n retval = retval.Insert(pos, newValue);\n\n // check if oldValue is found further down\n prevPos = pos + newValue.Length;\n pos = retval.IndexOf(oldValue, prevPos, StringComparison.InvariantCultureIgnoreCase);\n }\n\n return retval;\n}\n" }, { "answer_id": 39696868, "author": "Mark Cranness", "author_id": 365611, "author_profile": "https://Stackoverflow.com/users/365611", "pm_score": 2, "selected": false, "text": "public static string Replace(string str, string oldValue, string newValue, StringComparison comparison)\n{\n if (oldValue == null)\n throw new ArgumentNullException(\"oldValue\");\n if (oldValue.Length == 0)\n throw new ArgumentException(\"String cannot be of zero length.\", \"oldValue\");\n\n StringBuilder sb = null;\n\n int startIndex = 0;\n int foundIndex = str.IndexOf(oldValue, comparison);\n while (foundIndex != -1)\n {\n if (sb == null)\n sb = new StringBuilder(str.Length + (newValue != null ? Math.Max(0, 5 * (newValue.Length - oldValue.Length)) : 0));\n sb.Append(str, startIndex, foundIndex - startIndex);\n sb.Append(newValue);\n\n startIndex = foundIndex + oldValue.Length;\n foundIndex = str.IndexOf(oldValue, startIndex, comparison);\n }\n\n if (startIndex == 0)\n return str;\n sb.Append(str, startIndex, str.Length - startIndex);\n return sb.ToString();\n}\n" }, { "answer_id": 39792637, "author": "Chad Kuehn", "author_id": 1069995, "author_profile": "https://Stackoverflow.com/users/1069995", "pm_score": 3, "selected": false, "text": "Replace public static class StringExtensions\n{\n public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)\n {\n StringBuilder sb = new StringBuilder();\n\n int previousIndex = 0;\n int index = str.IndexOf(oldValue, comparison);\n while (index != -1)\n {\n sb.Append(str.Substring(previousIndex, index - previousIndex));\n sb.Append(newValue);\n index += oldValue.Length;\n\n previousIndex = index;\n index = str.IndexOf(oldValue, index, comparison);\n }\n sb.Append(str.Substring(previousIndex));\n return sb.ToString();\n }\n}\n" }, { "answer_id": 48337741, "author": "Fredrik Johansson", "author_id": 325874, "author_profile": "https://Stackoverflow.com/users/325874", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Text.RegularExpressions;\n\npublic static class MyExtensions {\n public static string ReplaceIgnoreCase(this string search, string find, string replace) {\n return Regex.Replace(search ?? \"\", Regex.Escape(find ?? \"\"), (replace ?? \"\").Replace(\"$\", \"$$\"), RegexOptions.IgnoreCase); \n }\n}\n var result = \"This is a test\".ReplaceIgnoreCase(\"IS\", \"was\");\n" }, { "answer_id": 51447661, "author": "Simon Hewitt", "author_id": 616187, "author_profile": "https://Stackoverflow.com/users/616187", "pm_score": 0, "selected": false, "text": "string.Replace [TestCase(\"œ\", \"oe\", \"\", StringComparison.InvariantCultureIgnoreCase, Result = \"\")]\n StringComparison.OrdinalIgnoreCase StringBuilder do{...}while while{...} public static string ReplaceCaseInsensitive(this string str, string oldValue, string newValue)\n {\n if (str == null) throw new ArgumentNullException(nameof(str));\n if (oldValue == null) throw new ArgumentNullException(nameof(oldValue));\n if (oldValue.Length == 0) throw new ArgumentException(\"String cannot be of zero length.\", nameof(oldValue));\n\n var position = str.IndexOf(oldValue, 0, StringComparison.OrdinalIgnoreCase);\n if (position == -1) return str;\n\n var sb = new StringBuilder(str.Length);\n\n var lastPosition = 0;\n\n do\n {\n sb.Append(str, lastPosition, position - lastPosition);\n\n sb.Append(newValue);\n\n } while ((position = str.IndexOf(oldValue, lastPosition = position + oldValue.Length, StringComparison.OrdinalIgnoreCase)) != -1);\n\n sb.Append(str, lastPosition, str.Length - lastPosition);\n\n return sb.ToString();\n }\n" }, { "answer_id": 63315139, "author": "Markus Hartmair", "author_id": 1220972, "author_profile": "https://Stackoverflow.com/users/1220972", "pm_score": 2, "selected": false, "text": "\"hello world\".Replace(\"World\", \"csharp\", StringComparison.CurrentCultureIgnoreCase); // \"hello csharp\"\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21155/" ]
244,569
<p>I'm sure this is a relatively simple question, and there must be a good sensible rails way of doing it, but I'm not sure what it is.</p> <p>Basically I'm adding books to a database, and I want to store the Author in a separate table. So I have a table called authors which is referenced by the table books.</p> <p>I want to create a rails form for adding a book, and I'd like it to be just a simple form for Author, Title, Publisher etc, and if it finds the author already in the authors table then it should just reference that record, and if it isn't in the authors table then it should add a new record and reference it.</p> <p>I'm sure there's an easy way of doing this in rails - but I can't seem to find it.</p> <p>Cheers,</p> <p>Robin</p>
[ { "answer_id": 244595, "author": "Micah", "author_id": 19964, "author_profile": "https://Stackoverflow.com/users/19964", "pm_score": 3, "selected": false, "text": "@author = Author.find_or_create_by_name(params[:author_name])\n@book = Book.new(params[:book])\n@book.author = @author\n@book.save\n" }, { "answer_id": 254284, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 1, "selected": false, "text": "@author = Author.find_or_create_by_name(params[:author_name])\n@book = Book.create params[:book].merge({:author_id => @author.id})\n class Book < ActiveRecord::Base\n ...\n def author_name=(author_name)\n self.author = Author.find_or_create_by_name author_name\n end\nend\n @book = Book.create params[:book]\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
244,588
<p>I was kind of scratching my head at this a week ago, and now with a little bit more Cocoa experience under my belt I feel like I have an inkling as to what might be going on. </p> <p>I'm making an application that is driven by a UINavigationController. In the AppDelegate, I create an instance of this class, using "page 1" as the Root View Controller.</p> <pre><code>UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:page1ViewController]; </code></pre> <p>Now here's where I'm having the problem. From "page 1" I'd like to use a modal view controller that slides over the interface and then disappears once the user has made an edit. I do that using code like this, inside of Page1ViewController:</p> <pre><code>[self presentModalViewController:myModalViewController animated:YES]; </code></pre> <p>When the Modal View Controller is gone, I want a value on "Page 1" to change based on what the user entered in the Modal View Controller. So, I wrote some code like this, which resides in the Modal View Controller: </p> <pre><code>[self.parentViewController dismissModalViewControllerAnimated:YES]; [self.parentViewController doSomethingPleaseWithSomeData:someData]; </code></pre> <p>The update to page 1 wasn't happening, and it took me a long time to realize that the "doSomethingPleaseWithSomeData" message was not being sent to Page1ViewController, but the Navigation Controller. </p> <p>Is this always to be expected when using Navigation Controllers? Did I perhaps configure something improperly? Is there an easy way to get at the View Controller that I want (in this case, Page1ViewController).</p>
[ { "answer_id": 244661, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 2, "selected": false, "text": "myModalViewController.logicalParent = self; //page1Controller\n[self presentModalViewController:myModalViewController animated:YES];\n" }, { "answer_id": 281270, "author": "Alex", "author_id": 35999, "author_profile": "https://Stackoverflow.com/users/35999", "pm_score": 5, "selected": true, "text": "@property (nonatomic, assign) id <MyModalViewDelegate> delegate;\n @protocol MyModalViewDelegate\n@optional\n - (void)myModalViewControllerDidFinish:(MyModalViewController *)aModalViewController;\n@end\n if ([self.delegate respondsToSelector:@selector(myModalViewControllerDidFinish:)])\n [self.delegate myModalViewControllerDidFinish:self];\n" }, { "answer_id": 4478207, "author": "zgobolos", "author_id": 546998, "author_profile": "https://Stackoverflow.com/users/546998", "pm_score": 1, "selected": false, "text": "- (void)presentModalViewController:(UIViewController *)c {\n [self.navigationHierarchy removeAllObjects];\n [self.navigationHierarchy addObjectsFromArray:[navigation viewControllers]];\n [navigation setViewControllers:[NSArray array] animated:YES];\n [navigation presentModalViewController:c animated:YES];\n}\n\n- (void)dismissModalViewController {\n [navigation dismissModalViewControllerAnimated:YES];\n [navigation setViewControllers:[NSArray arrayWithArray:self.navigationHierarchy] animated:YES];\n}\n NSMutableArray *navigationHierarchy;\nUINavigationController *navigation;\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543/" ]
244,591
<p>This is baffling me, maybe somebody can shine the light of education on my ignorance. This is in a C# windows app. I am accessing the contents of a listbox from a thread. When I try to access it like this<pre><code>prgAll.Maximum = lbFolders.SelectedItems.Count;</code></pre> I get the error. However, here is the part I don't get. If I comment out that line, the very next line<pre><code>foreach (string dir in lbFolders.SelectedItems)</code></pre> executes just fine.</p> <p>Edit: As usual, my communication skills are lacking. Let me clarify.</p> <p>I know that accessing GUI items from threads other than the ones they were created on causes problems. I know the right way to access them is via delegate.</p> <p>My question was mainly this: Why can I access and iterate through the SelectedItems object just fine, but when I try to get (not set) the Count property of it, it blows up.</p>
[ { "answer_id": 244604, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 4, "selected": true, "text": "prgAll.Maximum = lbFolders.SelectedItems.Count;\n" }, { "answer_id": 244613, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 2, "selected": false, "text": "void SetMax()\n{\n if (prgAll.InvokeRequired)\n {\n prgAll.BeginInvoke(new MethodInvoker(SetMax));\n return;\n }\n\n prgAll.Maximum = lbFolders.SelectedItems.Count;\n}\n" }, { "answer_id": 244614, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 4, "selected": false, "text": "lblStatus.Invoke((Action)(() => lblStatus.Text = counter.ToString()));\n lblTest.Invoke((MethodInvoker)(delegate() \n{ \n lblTest.Text = i.ToString(); \n}));\n" }, { "answer_id": 244657, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 1, "selected": false, "text": "private void RunMe()\n{\n if (!InvokeRequired)\n {\n myLabel.Text = \"You pushed the button!\";\n }\n else\n {\n Invoke(new ThreadStart(RunMe));\n }\n}\n" }, { "answer_id": 27435728, "author": "Gatherer", "author_id": 4041523, "author_profile": "https://Stackoverflow.com/users/4041523", "pm_score": 0, "selected": false, "text": "private delegate void xThreadCallBack();\nprivate void ThreadCallBack()\n{\n if (this.InvokeRequired)\n {\n this.BeginInvoke(new xThreadCallBack(ThreadCallBack));\n }\n else\n {\n //do what you want\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19038/" ]
244,601
<p>I have YAML data that looks sort of like this, but ~150k of it:</p> <pre><code>--- all: foo: 1025 bar: baz: 37628 quux: a: 179 b: 7 </code></pre> <p>...or the same thing in JSON:</p> <pre><code>{"all":{"bar":{"baz":"37628","quux":{"a":"179","b":"7"}},"foo":"1025"}} </code></pre> <p>I want to present this content in an expandable JavaScripty HTML tree view (examples: <a href="http://developer.yahoo.com/yui/examples/treeview/default_tree.html" rel="noreferrer">1</a>, <a href="http://www.mattkruse.com/javascript/mktree/" rel="noreferrer">2</a>) to make it easier to explore. How do I do this?</p> <p>I guess what I really want to figure out is how to take this YAML/JSON data, and automatically display it as a tree (with hash keys sorted alphabetically). So far, I've been tussling with <a href="http://developer.yahoo.com/yui/treeview/" rel="noreferrer">YUI's tree view</a>, but it doesn't accept straight JSON, and my feeble attempts to massage the data into something useful don't seem to be working.</p> <p>Thanks for any help.</p>
[ { "answer_id": 245117, "author": "user32225", "author_id": 32225, "author_profile": "https://Stackoverflow.com/users/32225", "pm_score": 1, "selected": false, "text": "{label:\"all\", children[\n {label:\"bar\", children:[\n {label:\"baz: 37628\"},\n {label:\"quux\", children[\n {label:\"a: 179\"},\n {label:\"b: 7\"}\n ]},\n {label:\"foo: 1025\"}\n ]}\n]}\n" }, { "answer_id": 247415, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 3, "selected": false, "text": "function renderJSON(obj) {\n 'use strict';\n var keys = [],\n retValue = \"\";\n for (var key in obj) {\n if (typeof obj[key] === 'object') {\n retValue += \"<div class='tree'>\" + key;\n retValue += renderJSON(obj[key]);\n retValue += \"</div>\";\n } else {\n retValue += \"<div class='tree'>\" + key + \" = \" + obj[key] + \"</div>\";\n }\n\n keys.push(key);\n }\n return retValue;\n}\n" }, { "answer_id": 247531, "author": "Anirvan", "author_id": 31100, "author_profile": "https://Stackoverflow.com/users/31100", "pm_score": 4, "selected": true, "text": "---\nall:\n foo: 1025\n bar:\n baz: 37628\n quux:\n a: 179\n b: 7\n --- $data =~ s/^---\\n//s;\n$data =~ s/^(\\s*)(\\S.*)$/$1- $2/gm;\n - all:\n - foo: 1025\n - bar:\n - baz: 37628\n - quux:\n - a: 179\n - b: 7\n use Text::Markdown qw( markdown );\nprint markdown($data);\n <ul>\n <li>all:\n <ul>\n <li>foo: 1025</li>\n <li>bar:</li>\n <li>baz: 37628</li>\n <li>quux:\n <ul>\n <li>a: 179</li>\n <li>b: 7</li>\n </ul>\n </li>\n </ul>\n </li>\n</ul>\n <html>\n<head>\n <!-- CSS + JS served via YUI hosting: developer.yahoo.com/yui/articles/hosting/ -->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/combo?2.6.0/build/treeview/assets/skins/sam/treeview.css\">\n <script type=\"text/javascript\" src=\"http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js&2.6.0/build/treeview/treeview-min.js\"></script>\n</head>\n<body>\n <div id=\"markup\" class=\"yui-skin-sam\">\n <!-- start Markdown-generated list -->\n <ul>\n <li>all:\n <ul>\n <li>foo: 1025</li>\n <li>bar:</li>\n <li>baz: 37628</li>\n <li>quux:\n <ul>\n <li>a: 179</li>\n <li>b: 7</li>\n </ul>\n </li>\n </ul>\n </li>\n </ul>\n <!-- end Markdown-generated list -->\n </div>\n <script type=\"text/javascript\">\n var treeInit = function() {\n var tree = new YAHOO.widget.TreeView(\"markup\");\n tree.render();\n };\n YAHOO.util.Event.onDOMReady(treeInit);\n </script>\n</body>\n</html>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31100/" ]
244,620
<p>I'm looking at the output from spring being loaded up by tomcat and there's something very strange...Everything is duplicated. What would cause this? Whatever it is, it's causing my application to run in odd ways.</p> <p><strong>Additional Info:</strong></p> <p>The application is a web app. All the spring information is loaded using the context loader(?) defined in the web.xml file. My configuration files are split amoung 6 (or so) files.</p> <p>Example debug output:</p> <blockquote> <p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [REQUIRES_SECURE_CHANNEL]</p> <p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [REQUIRES_SECURE_CHANNEL]</p> <p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [ROLE_READ, ROLE_UPDATE]</p> <p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [ROLE_READ, ROLE_UPDATE]</p> <p>[DEBUG,AbstractFallbackMethodDefinitionSource,main] Adding security method [CacheKey[com.service.impl.FooServiceImpl; public abstract java.lang.Boolean com.service.IFooService.saveOrUpdateFoo(com.model.Foo2,java.lang.String) throws org.springframework.dao.DataAccessException]] with attribute [[ROLE_UPDATE]]</p> <p>[DEBUG,AbstractFallbackMethodDefinitionSource,main] Adding security method [CacheKey[com.service.impl.FooServiceImpl; public abstract java.lang.Boolean com.service.IFooService.saveOrUpdateFoo(com.model.Foo2,java.lang.String) throws org.springframework.dao.DataAccessException]] with attribute [[ROLE_UPDATE]]</p> <p>[INFO,AbstractSecurityInterceptor,main] Validated configuration attributes</p> <p>[INFO,AbstractSecurityInterceptor,main] Validated configuration attributes</p> </blockquote>
[ { "answer_id": 2668390, "author": "khotyn", "author_id": 227994, "author_profile": "https://Stackoverflow.com/users/227994", "pm_score": 0, "selected": false, "text": "<category name=\"org.springframework\">\n <level value=\"INFO\"></level>\n <appender-ref ref=\"basicAppender\" />\n</category>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17337/" ]
244,631
<p>I've got several developers about to start working on the front end of a jquery-based web application. How can we structure the application so that multiple developers can work on the ui at the same time. The end result for the user will just be one web "page", but I don't all of the client development to occur in one file. There is already another team working on the back end.</p>
[ { "answer_id": 711564, "author": "eduncan911", "author_id": 56693, "author_profile": "https://Stackoverflow.com/users/56693", "pm_score": 0, "selected": false, "text": " /products/532\n /products/showproduct.jsp?productid=532\n/products/showproduct.java (code behind)\n /Controllers/ProductController.java <- ProductController.ViewProduct(int id)\n/Models/ViewModels/Product.java <- Product() class\n/Views/Product/Index.html <- very simple display of html.\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32177/" ]
244,639
<p>I have a medium size Java file. Everytime I make a change to one of my files, BuildTable.java, Git reports it as a massive change, even if is only a line or two. BuildTable.java is about 200 lines and the change in this commit only changed a single line.</p> <p>git-diff ouputs this:</p> <pre><code>--- a/src/BuildTable.java +++ b/src/BuildTable.java @@ -1 +1 @@ -import java.io.FileNotFoundException;^Mimport java.io.FileReader;^Mimport java.io.InputStreamReader;^Mimport java.io.PushbackReader;^Mimport java.util.ArrayList;^Mimport \ No newline at end of file +import java.io.FileNotFoundException;^Mimport java.io.FileReader;^Mimport java.io.InputStreamReader;^Mimport java.io.PushbackReader;^Mimport java.util.ArrayList;^Mimport \ No newline at end of file </code></pre> <p>After doing a git-commit -a</p> <pre><code>Created commit fe43985: better error notifications 3 files changed, 54 insertions(+), 50 deletions(-) rewrite src/BuildTable.java (78%) </code></pre> <p>Is Git seeing this file as binary or something? Is this a problem? If it is, how do I fix this?</p>
[ { "answer_id": 244782, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "core.autocrlf core.safecrlf git-config CR LF recode LF" }, { "answer_id": 251383, "author": "Paul Wicks", "author_id": 85, "author_profile": "https://Stackoverflow.com/users/85", "pm_score": 5, "selected": true, "text": ":%s/^M/\\r/g\n" }, { "answer_id": 1814909, "author": "Andrew Grimm", "author_id": 38765, "author_profile": "https://Stackoverflow.com/users/38765", "pm_score": 0, "selected": false, "text": "git diff -b\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
244,640
<p>I am having difficulty refreshing windows forms controls that are using a BindingSource object. We have a CAB/MVP/SCSF client that I (actually “we” since it is a team effort) are developing that will interact with WCF services running on a remote server. (This is our first attempt at this, so we are in a learning mode). One of the calls (from the Presenter) to the service returns a DataSet that contains 3 DataTables, named “Contract”, “Loan” and “Terms”. Each table contains just one row. When the service returns the dataset, we store it in the SmartPart/View in a class member variable, by calling a function in the view called BindData() and passing the dataset in to the view from the presenter class;</p> <pre><code>private System.Data.DataSet _ds = null; public void BindData(System.Data.DataSet ds) { string sErr = ""; try { _ds = ds; // save to private member variable // more code goes down here } } </code></pre> <p>We are trying to bind each of the three DataTables to an assortment of Windows Forms TextBoxes, MaskedEditBoxes, and Infragistics UltraComboEditor Dropdown comboboxes We created three BindingSource objects, one for each DataTable using the VS2008 IDE.</p> <pre><code>private System.Windows.Forms.BindingSource bindsrcContract; private System.Windows.Forms.BindingSource bindsrcLoan; private System.Windows.Forms.BindingSource bindsrcTerms; </code></pre> <p>We are binding the values like this</p> <pre><code>if (bindsrcContract.DataSource == null) { bindsrcContract.DataSource = _ds; bindsrcContract.DataMember = “contract”; txtContract.DataBindings.Add(new Binding("Text", bindsrcContract, "contract_id", true)); txtLateFeeAmt.DataBindings.Add(new Binding("Text", bindsrcContract, "fee_code", true)); txtPrePayPenalty.DataBindings.Add(new Binding("Text", bindsrcContract, "prepay_penalty", true)); txtLateFeeDays.DataBindings.Add(new Binding("Text", bindsrcContract, "late_days", true)); } if (bindsrcLoan.DataSource == null) { bindsrcLoan.DataSource = _ds; bindsrcLoan.DataMember = “loan”; mskRecvDate.DataBindings.Add(new Binding("Text", bindsrcLoan, "receive_date", true)); cmboDocsRcvd.DataBindings.Add(new Binding("Value", bindsrcLoan, "docs", true)); } </code></pre> <p>This works when we do the first read from the service and get a dataset back. The information is displayed on the form's controls, we can update it using the form, and then “save” it by passing the changed values back to the WCF service.</p> <p>Here is our problem. If we select a different loan key and make the same call to the service and get a new DataSet, again with 3 tables with one row each, the controls (textboxes, masked edit boxes, etc.) are not being updated with the new information. Note that the smartPart/View is not closed or anything, but remains loaded in between calls to the service. On the second call we are not rebinding the calls, but simply trying to get the data to refresh from the updated DataSet.</p> <p>We have tried everything we can think of, but clearly we are missing something. This is our first attempt at using the BindingSource control. We have tried</p> <pre><code>bindsrcContract.ResetBindings(false); </code></pre> <p>and </p> <pre><code>bindsrcContract.ResetBindings(true); </code></pre> <p>and </p> <pre><code>bindsrcContract.RaiseListChangedEvents = true; </code></pre> <p>and </p> <pre><code>for (int i = 0; i &lt; bindsrcContract.Count; i++) { bindsrcContract.ResetItem(i); } </code></pre> <p>As well as resetting the DataMember property again.</p> <pre><code>bindsrcContract.DataMember = ”Contract”; </code></pre> <p>We’ve looked at a lot of examples. Many examples make reference to the BindingNavigator but since the DataTables only have one row, we did not think we needed that. There are a lot of examples for grids, but we’re not using one here. Can anyone please point out where we are going wrong, or point us to resources that will provide some more information?</p> <p>We’re using VisualStudio 2008, C# and .Net 2.0, XP client, W2K3 server.</p> <p>Thanks in advance</p> <p>wes</p>
[ { "answer_id": 244983, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 0, "selected": false, "text": "bindsrcContract.DataSource = typeof(System.Data.DataSet);\nbindsrcContract.DataSource = _ds;\n" }, { "answer_id": 248300, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 0, "selected": false, "text": "bindsrcContract.DataSource = _ds;\n bindsrcContract.DataSource = typeof(System.Data.DataSet);\nbindsrcContract.DataSource = _ds;\n" }, { "answer_id": 4740912, "author": "Jimmy V", "author_id": 582131, "author_profile": "https://Stackoverflow.com/users/582131", "pm_score": 2, "selected": false, "text": "private void btnCancel_Click(object sender, EventArgs e)\n{\n this.MyTable.RejectChanges();\n this.txtMyBoundTextBox.DataBindings[0].ReadValue();\n this.EditState = EditStates.NotEditting;\n}\n" }, { "answer_id": 16346912, "author": "zeljko", "author_id": 2344678, "author_profile": "https://Stackoverflow.com/users/2344678", "pm_score": 0, "selected": false, "text": "bindingsource.EndEdit() // writting data to underlying source \nbindingSource.ResetBindings(false) // force controls to reread data from bindingSource\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
244,646
<p>I'm looking for the equivalent in Qt to <code>GetTickCount()</code></p> <p>Something that will allow me to measure the time it takes for a segment of code to run as in:</p> <pre><code>uint start = GetTickCount(); // do something.. uint timeItTook = GetTickCount() - start; </code></pre> <p>any suggestions?</p>
[ { "answer_id": 244676, "author": "Dusty Campbell", "author_id": 2174, "author_profile": "https://Stackoverflow.com/users/2174", "pm_score": 8, "selected": true, "text": "QTime QTime myTimer;\nmyTimer.start();\n// do something..\nint nMilliseconds = myTimer.elapsed();\n" }, { "answer_id": 4381741, "author": "sivabudh", "author_id": 65313, "author_profile": "https://Stackoverflow.com/users/65313", "pm_score": 7, "selected": false, "text": "QElapsedTimer #include <QDebug>\n#include <QElapsedTimer>\n...\n...\nQElapsedTimer timer;\ntimer.start();\nslowOperation(); // we want to measure the time of this slowOperation()\nqDebug() << timer.elapsed();\n" }, { "answer_id": 13003265, "author": "Lilian A. Moraru", "author_id": 1020714, "author_profile": "https://Stackoverflow.com/users/1020714", "pm_score": 5, "selected": false, "text": "sivabudh QElapsedTimer QElapsedTimer timer;\nqint64 nanoSec;\ntimer.start();\n//something happens here\nnanoSec = timer.nsecsElapsed();\n//printing the result(nanoSec)\n//something else happening here\ntimer.restart();\n//some other operation\nnanoSec = timer.nsecsElapsed();\n" }, { "answer_id": 22772205, "author": "Oliver Hoffmann", "author_id": 1633383, "author_profile": "https://Stackoverflow.com/users/1633383", "pm_score": 2, "selected": false, "text": "QElapsedTimer static qint64 time = 0;\nstatic int count = 0;\nQElapsedTimer et;\net.start();\ntime += et.nsecsElapsed();\nif (++count % 10000 == 0)\n qDebug() << \"timing:\" << (time / count) << \"ns/call\";\n timing: 90 ns/call \ntiming: 89 ns/call \n...\n" }, { "answer_id": 38651310, "author": "Damien", "author_id": 919155, "author_profile": "https://Stackoverflow.com/users/919155", "pm_score": 2, "selected": false, "text": "#include <QDebug>\n#include <QElapsedTimer>\n#define CONCAT_(x,y) x##y\n#define CONCAT(x,y) CONCAT_(x,y)\n\n#define CHECKTIME(x) \\\n QElapsedTimer CONCAT(sb_, __LINE__); \\\n CONCAT(sb_, __LINE__).start(); \\\n x \\\n qDebug() << __FUNCTION__ << \":\" << __LINE__ << \" Elapsed time: \" << CONCAT(sb_, __LINE__).elapsed() << \" ms.\";\n CHECKTIME(\n // any code\n for (int i=0; i<1000; i++)\n {\n timeConsumingFunc();\n }\n)\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
244,663
<p>Sign. My tsql kungfu sucks. I have a fee that is of type small money. When I exported as SQL from MS Access the column that represents the fee was stored as text, for example $3.28 was stored as "00000328". When I imported this into MS SQLServer I changed the data type to smallmoney, but it was stored as 328. How do I make all the values on that column to move the "." two digits over to the left. </p>
[ { "answer_id": 244745, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "update table\nset fee = fee / 100.0\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
244,665
<p>This is the css for setting the color for h1 text that is linked:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-left h1 a, a:visited { color: #055830; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="nav-left"&gt; &lt;h1&gt;&lt;a href="/index.php/housing/"&gt;Housing&lt;/a&gt;&lt;/h1&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>It does not look like it is working appropriately, any help is appreciated.</p>
[ { "answer_id": 244670, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 4, "selected": true, "text": ".nav-left h1 a:visited{\n color:#055830;\n}\n" }, { "answer_id": 244681, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": ".nav-left h1 a {\n color: #055830;\n}\n" }, { "answer_id": 244937, "author": "closetgeekshow", "author_id": 8691, "author_profile": "https://Stackoverflow.com/users/8691", "pm_score": 3, "selected": false, "text": ".nav-left h1 a:link, .nav-left h1 a:visited {\n color:#055830;\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
244,671
<p>I'm looking for an UPDATE statement where it will update a single duplicate row only and remain the rest (duplicate rows) intact as is, using ROWID or something else or other elements to utilize in Oracle SQL or PL/SQL?</p> <p>Here is an example duptest table to work with:</p> <pre><code>CREATE TABLE duptest (ID VARCHAR2(5), NONID VARCHAR2(5)); </code></pre> <ul> <li><p>run one <code>INSERT INTO duptest VALUES('1','a');</code> </p></li> <li><p>run four (4) times <code>INSERT INTO duptest VALUES('2','b');</code> </p></li> </ul> <p>Also, the first duplicate row has to be updated (not deleted), always, whereas the other three (3) have to be remained as is!</p> <p>Thanks a lot, Val.</p>
[ { "answer_id": 244757, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 4, "selected": false, "text": "update duptest \nset nonid = 'c'\nWHERE ROWID IN (SELECT MIN (ROWID)\n FROM duptest \n GROUP BY id, nonid)\n" }, { "answer_id": 244809, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "--third, update the one row\nUPDATE DUPTEST DT\nSET DT.NONID = 'c'\nWHERE (DT.ID,DT.ROWID) IN(\n --second, find the row id of the first dup\n SELECT \n DT.ID\n ,MIN(DT.ROWID) AS FIRST_ROW_ID\n FROM DUPTEST DT\n WHERE ID IN(\n --first, find the dups\n SELECT ID\n FROM DUPTEST\n GROUP BY ID\n HAVING COUNT(*) > 1\n )\n GROUP BY\n DT.ID\n )\n" }, { "answer_id": 244857, "author": "Aaron Smith", "author_id": 12969, "author_profile": "https://Stackoverflow.com/users/12969", "pm_score": 1, "selected": false, "text": "UPDATE DUPTEST SET NONID = 'C'\nWHERE ROWID in (\n Select ROWID from (\n SELECT ROWID, Row_Number() over (Partition By ID, NONID order by ID) rn\n ) WHERE rn = 1\n)\n" }, { "answer_id": 245969, "author": "Thorsten", "author_id": 25320, "author_profile": "https://Stackoverflow.com/users/25320", "pm_score": 0, "selected": false, "text": "select min (real_id) \nfrom duptest\ngroup by (id, nonid)\n update duptest\nset nonid = 'C'\nwhere real_id in (<select from above>)\n" }, { "answer_id": 277041, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "UPDATE duptest \nSET nonid = 'c' \nWHERE nonid = 'b' \n AND rowid = (SELECT min(rowid) \n FROM duptest \n WHERE nonid = 'b');\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
244,677
<p>Can it be known in general whether or not placing a case within a for loop will result in bad assembly. I'm interested mainly in Delphi, but this is an interesting programming question, both in terms of style and performance. </p> <p>Here are my codez!</p> <pre> case ResultList.CompareType of TextCompareType: begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin if (StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) and (Result FalseEval) then Result := TrueEval else Result := FalseEval; LastGoodIndex := I; end; end; end; NumericCompareType: begin //Same as above with a numeric comparison end; DateCompareType: begin //Same as above with a date comparison end; BooleanCompareType: begin //Same as above with a boolean comparison end; </pre> <p>alternatively I could write </p> <pre> begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin case ResultList.CompareType of TextCompareType: begin if (StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) and (Result FalseEval) then Result := TrueEval else Result := FalseEval; LastGoodIndex := I; end; NumericCompareType: begin //Same as above with a numeric comparison end; DateCompareType: begin //Same as above with a date comparison end; BooleanCompareType: begin //Same as above with a boolean comparison end; end; end; end; </pre> <p>I don't like the second way because I'm asking a question I know the answer to in a for loop and I don't like the first way because I'm repeating the code I use to figure out which of my objects contain valid information. </p> <p>Perhaps there is a design pattern someone could suggest that would circumvent this all together.</p>
[ { "answer_id": 244687, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": true, "text": "TComparer = class \nprotected\n function Compare(const AItem1, AItem2: TItem): Boolean; virtual; abstract;\npublic\n procedure DoCompare(ResultList: ...);\nend;\n\nTTextComparer = class (TComparer)\nprotected\n function Compare(const AItem1, AItem2: TItem): Boolean; override;\nend;\n\nprocedure TComparer.DoCompare(ResultList: ...);\nvar\n LastGoodIndex, I : Integer;\nbegin \n LastGoodIndex := -1;\n for I := 1 to ResultList.Count -1 do\n if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then\n LastGoodIndex := I\n else if not ResultList[I].Indeterminate then begin\n if Compare(ResultList[LastGoodIndex], ResultList[I]) then\n Result := TrueEval\n else \n Result := FalseEval;\n end;\nend;\n\nfunction TTextComparer.Compare(const AItem1, AItem2: TItem): Boolean; \nbegin\n Result := StrComp(ResultList[LastGoodIndex].ResultAsText,\n ResultList[I].ResultAsText) > 0) \nend;\n" }, { "answer_id": 244747, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 1, "selected": false, "text": "my %type = (\n TextCompareType => sub { $_[0] lt $_[1] },\n NumericCompareType => sub { $_[0] < $_[1] },\n DateCompareType => sub { ... },\n BooleanCompareType => sub { ... },\n );\n\nfor (my $i = 1; $i <= $#list; ++$i)\n{\n if ( $type{$ResultList{CompareType}}->($list[$i-1], $list[$i]) )\n {\n $result = 1; # ?\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
244,680
<p>Can someone explain what this means?</p> <pre><code>int (*data[2])[2]; </code></pre>
[ { "answer_id": 244692, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "double (*elephant)[20];\n int *(*crocodile)[15];\n int (*data[2])[5];\n int (*data[2])[5];\nint x1[5];\ndata[0] = &x1;\ndata[1] = &x1;\n\ndata[2] = &x1;//<--- out of bounds, crash data has no 3rd element\nint y1[10];\ndata[0] = &y1;//<--- compiling error, each element of data must point to an int[5] not an int[10]\n" }, { "answer_id": 245688, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 3, "selected": false, "text": "char *p;\n *p int (*data[2])[5];\n (*data[x])[y] data void **(*(*weird)[6])(char, int);\n weird typedef void **(*sillyFunction)(char, int);\n\nsillyFunction (*weird)[6];\n" }, { "answer_id": 22361953, "author": "AbstractDonut", "author_id": 3408627, "author_profile": "https://Stackoverflow.com/users/3408627", "pm_score": -1, "selected": false, "text": "int myArray[5];\nint * myArrayPtr = myArray;\n myArray int myArray myArrayPtr[1] = 3;\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32185/" ]
244,695
<p>The structures of my Git repositories look like this:</p> <pre><code>A-B-C-D-E-F # master branch in separate repo1 A-B-C-D-E-G-H # master branch in separate repo2 </code></pre> <p>A-H are simple commits. As you can see the repositories are related (repo2 is a fork of repo1). I'm trying to combine these two repositories in one.</p> <p>Afterwards the single repository should have the following structure:</p> <pre><code>A-B-C-D-E-F # master branch of previous repo1 \ \ G-H # master branch of previous repo2 </code></pre> <p>I've already spent a lot of time reading the Git User's Guide and so on. However, this (special) case of use doesn't seem to be documented anywhere.</p>
[ { "answer_id": 245240, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 7, "selected": true, "text": "git remote add <name> /path/to/other/repo/.git\ngit fetch <name>\ngit branch <name> <name>/master #optional\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
244,699
<p>Does <code>YUI</code> have selector methods like jQuery?</p> <p>e.g. get me all div's that are <code>children</code> of <code>&lt;table&gt;</code> that have links in them?</p>
[ { "answer_id": 244818, "author": "Anirvan", "author_id": 31100, "author_profile": "https://Stackoverflow.com/users/31100", "pm_score": 3, "selected": false, "text": "Y.all('.foo').set('title', 'Go!').removeClass('off');\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
244,715
<p>I'm debating the best way to propagate fairly complex permissions from the server to an AJAX application, and I'm not sure the best approach to take.</p> <p>Essentially, I want my permissions to be defined so I can request a whole set of permissions in one shot, and adjust the UI as appropriate (the UI changes can be as low level as disabling certain context menu items). Of course, I still need to enforce the permissions server side. </p> <p>So, I was wondering if anyone has any suggestions for the best way to</p> <ol> <li>maintain the permissions and use them in server code</li> <li>have easy access to the permissions in javascript</li> <li>not have to make a round-trip request to the server for each individual permission</li> </ol> <p>Thoughts?</p>
[ { "answer_id": 244948, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 3, "selected": true, "text": "0x00000001 //edit permission\n0x00000002 //create new thing permission\n0x00000004 //delete things permission\n0x00000008 //view hidden things permission\n .\n .\n .\n0x80000000 //total control of the server and everyone logged in\n 0x000007" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25330/" ]
244,720
<p>Because I need to display a <a href="http://codeflow.org/ubuntu.png" rel="nofollow noreferrer">huge number of labels</a> that <a href="http://www.youtube.com/watch?v=A_ah-SE-cNY" rel="nofollow noreferrer">move independently</a>, I need to render a label in <a href="http://pyglet.org" rel="nofollow noreferrer">pyglet</a> to a texture (otherwise updating the vertex list for each glyph is too slow).</p> <p>I have a solution to do this, but my problem is that the texture that contains the glyphs is black, but I'd like it to be red. See the example below:</p> <pre><code>from pyglet.gl import * def label2texture(label): vertex_list = label._vertex_lists[0].vertices[:] xpos = map(int, vertex_list[::8]) ypos = map(int, vertex_list[1::8]) glyphs = label._get_glyphs() xstart = xpos[0] xend = xpos[-1] + glyphs[-1].width width = xend - xstart ystart = min(ypos) yend = max(ystart+glyph.height for glyph in glyphs) height = yend - ystart texture = pyglet.image.Texture.create(width, height, pyglet.gl.GL_RGBA) for glyph, x, y in zip(glyphs, xpos, ypos): data = glyph.get_image_data() x = x - xstart y = height - glyph.height - y + ystart texture.blit_into(data, x, y, 0) return texture.get_transform(flip_y=True) window = pyglet.window.Window() label = pyglet.text.Label('Hello World!', font_size = 36) texture = label2texture(label) @window.event def on_draw(): hoff = (window.width / 2) - (texture.width / 2) voff = (window.height / 2) - (texture.height / 2) glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.0, 1.0, 0.0, 1.0) window.clear() glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture.id) glColor4f(1.0, 0.0, 0.0, 1.0) #I'd like the font to be red glBegin(GL_QUADS); glTexCoord2d(0.0,1.0); glVertex2d(hoff,voff); glTexCoord2d(1.0,1.0); glVertex2d(hoff+texture.width,voff); glTexCoord2d(1.0,0.0); glVertex2d(hoff+texture.width,voff+texture.height); glTexCoord2d(0.0,0.0); glVertex2d(hoff, voff+texture.height); glEnd(); pyglet.app.run() </code></pre> <p>Any idea how I could color this?</p>
[ { "answer_id": 246962, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "glTexEnv()" }, { "answer_id": 405855, "author": "Joseph Garvin", "author_id": 50385, "author_profile": "https://Stackoverflow.com/users/50385", "pm_score": 2, "selected": false, "text": "glEnable(GL_COLOR_MATERIAL) glColorMaterial" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19435/" ]
244,752
<p>I want to setup a CRON that runs a PHP script that in turn moves XML file (holding non-sensitive information) from one server to another. </p> <p>I have been given the proper username/password, and want to use SFTP protocol. The jobs will run daily. There is the potential that one server is Linux and the other is Windows. Both are on different networks. </p> <p>What is the best way to move that file?</p>
[ { "answer_id": 244771, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 3, "selected": false, "text": "<?php\n $output = shell_exec('scp file1.txt dvader@deathstar.com:somedir');\n echo \"<pre>$output</pre>\";\n?>\n" }, { "answer_id": 244917, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 3, "selected": false, "text": "// open some file for reading\n$file = 'somefile.txt';\n$fp = fopen($file, 'r');\n\n// set up basic connection\n$conn_id = ftp_connect($ftp_server);\n\n// login with username and password\n$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);\n\n// try to upload $file\nif (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {\n echo \"Successfully uploaded $file\\n\";\n} else {\n echo \"There was a problem while uploading $file\\n\";\n}\n\n// close the connection and the file handler\nftp_close($conn_id);\nfclose($fp);\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
244,755
<p>I am currently publishing code behind .aspx in SharePoint. I can automatically publish the .dll to the bin folder of the virtual directory, but I cannot figure out how to push the .aspx pages and images to the server without manually using SharePoint Designer.</p> <p>Where does the folder exist?</p> <p>Or do I need to create a SharePoint feature for this?</p>
[ { "answer_id": 244771, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 3, "selected": false, "text": "<?php\n $output = shell_exec('scp file1.txt dvader@deathstar.com:somedir');\n echo \"<pre>$output</pre>\";\n?>\n" }, { "answer_id": 244917, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 3, "selected": false, "text": "// open some file for reading\n$file = 'somefile.txt';\n$fp = fopen($file, 'r');\n\n// set up basic connection\n$conn_id = ftp_connect($ftp_server);\n\n// login with username and password\n$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);\n\n// try to upload $file\nif (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {\n echo \"Successfully uploaded $file\\n\";\n} else {\n echo \"There was a problem while uploading $file\\n\";\n}\n\n// close the connection and the file handler\nftp_close($conn_id);\nfclose($fp);\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3149/" ]
244,758
<p>So this might be really simple, but I haven't been able to find any examples to learn off of yet, so please bear with me. ;) </p> <p>Here's basically what I want to do:</p> <pre><code>&lt;div&gt;Lots of content! Lots of content! Lots of content! ...&lt;/div&gt; .... $("div").html("Itsy-bitsy bit of content!"); </code></pre> <p>I want to smoothly animate between the dimensions of the div with lots of content to the dimensions of the div with very little when the new content is injected.</p> <p>Thoughts?</p>
[ { "answer_id": 244847, "author": "lucas", "author_id": 31172, "author_profile": "https://Stackoverflow.com/users/31172", "pm_score": 3, "selected": false, "text": "$(\".testLink\").click(function(event) {\n event.preventDefault();\n $(\".testDiv\").hide(400,function(event) {\n $(this).html(\"Itsy-bitsy bit of content!\").show(400);\n });\n});\n" }, { "answer_id": 245011, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 5, "selected": false, "text": "$(\"div\").animate({width:\"200px\"},400);\n" }, { "answer_id": 245316, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 7, "selected": true, "text": "// Animates the dimensional changes resulting from altering element contents\n// Usage examples: \n// $(\"#myElement\").showHtml(\"new HTML contents\");\n// $(\"div\").showHtml(\"new HTML contents\", 400);\n// $(\".className\").showHtml(\"new HTML contents\", 400, \n// function() {/* on completion */});\n(function($)\n{\n $.fn.showHtml = function(html, speed, callback)\n {\n return this.each(function()\n {\n // The element to be modified\n var el = $(this);\n\n // Preserve the original values of width and height - they'll need \n // to be modified during the animation, but can be restored once\n // the animation has completed.\n var finish = {width: this.style.width, height: this.style.height};\n\n // The original width and height represented as pixel values.\n // These will only be the same as `finish` if this element had its\n // dimensions specified explicitly and in pixels. Of course, if that \n // was done then this entire routine is pointless, as the dimensions \n // won't change when the content is changed.\n var cur = {width: el.width()+'px', height: el.height()+'px'};\n\n // Modify the element's contents. Element will resize.\n el.html(html);\n\n // Capture the final dimensions of the element \n // (with initial style settings still in effect)\n var next = {width: el.width()+'px', height: el.height()+'px'};\n\n el .css(cur) // restore initial dimensions\n .animate(next, speed, function() // animate to final dimensions\n {\n el.css(finish); // restore initial style settings\n if ( $.isFunction(callback) ) callback();\n });\n });\n };\n\n\n})(jQuery);\n stop() showHtml() true $(selector).showHtml(\"new HTML contents\")\n .stop(true, true)\n .showHtml(\"even newer contents\");\n" }, { "answer_id": 475889, "author": "Daan", "author_id": 58565, "author_profile": "https://Stackoverflow.com/users/58565", "pm_score": 3, "selected": false, "text": "<div id=\"div-1\"><div id=\"div-2\">Some content here</div></div>\n // cache selectors for better performance\nvar container = $('#div-1'),\n wrapper = $('#div-2');\n\n// temporarily fix the outer div's width\ncontainer.css({width: wrapper.width()});\n// fade opacity of inner div - use opacity because we cannot get the width or height of an element with display set to none\nwrapper.fadeTo('slow', 0, function(){\n // change the div content\n container.html(\"<div id=\\\"2\\\" style=\\\"display: none;\\\">new content (with a new width)</div>\");\n // give the outer div the same width as the inner div with a smooth animation\n container.animate({width: wrapper.width()}, function(){\n // show the inner div\n wrapper.fadeTo('slow', 1);\n });\n});\n" }, { "answer_id": 5972286, "author": "A-P", "author_id": 749720, "author_profile": "https://Stackoverflow.com/users/749720", "pm_score": 1, "selected": false, "text": "$('div#to-transition').wrap( '<div id=\"tmp\"></div>' );\n$('div#tmp').css( { height: $('div#to-transition').outerHeight() + 'px' } );\n$('div#to-transition').fadeOut('fast', function() {\n $(this).html(new_html);\n $('div#tmp').animate( { height: $(this).outerHeight() + 'px' }, 'fast' );\n $(this).fadeIn('fast', function() {\n $(this).unwrap();\n });\n});\n" }, { "answer_id": 27139850, "author": "davidcondrey", "author_id": 1922144, "author_profile": "https://Stackoverflow.com/users/1922144", "pm_score": 0, "selected": false, "text": "dequeue var space = ($(window).width() - 100);\n$('.column').width(space/4);\n\n$(\".column\").click(function(){\n if (!$(this).hasClass('animated')) {\n $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {});\n }\n\n $(this).addClass('animated');\n $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {\n $(this).removeClass('animated').dequeue();\n\n });\n $(this).dequeue().stop().animate({\n width:(space/4)\n }, 1400,'linear',function(){\n $(this).html('AGAIN');\n });\n});\n" }, { "answer_id": 27534587, "author": "snotbubblelou", "author_id": 1123521, "author_profile": "https://Stackoverflow.com/users/1123521", "pm_score": 0, "selected": false, "text": "// Modify the element's contents. Element will resize.\nel.html(html);\n // Modify the element's contents. Element will resize.\nel.append(html);\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
244,772
<p>I'm creating a series of builders to clean up the syntax which creates domain classes for my mocks as part of improving our overall unit tests. My builders essentially populate a domain class (such as a <code>Schedule</code>) with some values determined by invoking the appropriate <code>WithXXX</code> and chaining them together.</p> <p>I've encountered some commonality amongst my builders and I want to abstract that away into a base class to increase code reuse. Unfortunately what I end up with looks like:</p> <pre><code>public abstract class BaseBuilder&lt;T,BLDR&gt; where BLDR : BaseBuilder&lt;T,BLDR&gt; where T : new() { public abstract T Build(); protected int Id { get; private set; } protected abstract BLDR This { get; } public BLDR WithId(int id) { Id = id; return This; } } </code></pre> <p>Take special note of the <code>protected abstract BLDR This { get; }</code>.</p> <p>A sample implementation of a domain class builder is:</p> <pre><code>public class ScheduleIntervalBuilder : BaseBuilder&lt;ScheduleInterval,ScheduleIntervalBuilder&gt; { private int _scheduleId; // ... // UG! here's the problem: protected override ScheduleIntervalBuilder This { get { return this; } } public override ScheduleInterval Build() { return new ScheduleInterval { Id = base.Id, ScheduleId = _scheduleId // ... }; } public ScheduleIntervalBuilder WithScheduleId(int scheduleId) { _scheduleId = scheduleId; return this; } // ... } </code></pre> <p>Because BLDR is not of type BaseBuilder I cannot use <code>return this</code> in the <code>WithId(int)</code> method of <code>BaseBuilder</code>.</p> <p>Is exposing the child type with the property <code>abstract BLDR This { get; }</code> my only option here, or am I missing some syntax trick?</p> <p>Update (since I can show why I'm doing this a bit more clearly):</p> <p>The end result is to have builders that build profiled domain classes that one would expect to retrieve from the database in a [programmer] readable format. There's nothing wrong with...</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new Schedule { ScheduleId = 1 // ... } ); </code></pre> <p>as that's pretty readable already. The alternative builder syntax is:</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new ScheduleBuilder() .WithId(1) // ... .Build() ); </code></pre> <p>the advantage I'm looking for out of using builders (and implementing all these <code>WithXXX</code> methods) is to abstract away complex property creation (automatically expand our database lookup values with the correct <code>Lookup.KnownValues</code> without hitting the database obviously) and having the builder provide commonly reusable test profiles for domain classes...</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new ScheduleBuilder() .AsOneDay() .Build() ); </code></pre>
[ { "answer_id": 9244978, "author": "dvdvorle", "author_id": 481635, "author_profile": "https://Stackoverflow.com/users/481635", "pm_score": 2, "selected": false, "text": "abstract BLDR This { get; } public abstract class BaseBuilder<T, BLDR> where BLDR : BaseBuilder<T, BLDR>\n where T : new()\n{\n public abstract T Build();\n\n protected int Id { get; private set; }\n\n public BLDR WithId(int id)\n {\n _id = id;\n return (BLDR)this;\n }\n}\n\npublic class ScheduleIntervalBuilder :\n BaseBuilder<ScheduleInterval,ScheduleIntervalBuilder>\n{\n private int _scheduleId;\n // ...\n\n public override ScheduleInterval Build()\n {\n return new ScheduleInterval\n {\n Id = base.Id,\n ScheduleId = _scheduleId\n // ...\n };\n }\n\n public ScheduleIntervalBuilder WithScheduleId(int scheduleId)\n {\n _scheduleId = scheduleId;\n return this;\n }\n\n // ...\n}\n protected BLDR This\n{\n get\n {\n return (BLDR)this;\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5645/" ]
244,777
<p>Can I use comments inside a <a href="https://en.wikipedia.org/wiki/JSON" rel="noreferrer">JSON</a> file? If so, how?</p>
[ { "answer_id": 244858, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 14, "selected": true, "text": "\"_comment\" {\n \"_comment\": \"comment text goes here...\",\n \"glossary\": {\n \"title\": \"example glossary\",\n \"GlossDiv\": {\n \"title\": \"S\",\n \"GlossList\": {\n \"GlossEntry\": {\n \"ID\": \"SGML\",\n \"SortAs\": \"SGML\",\n \"GlossTerm\": \"Standard Generalized Markup Language\",\n \"Acronym\": \"SGML\",\n \"Abbrev\": \"ISO 8879:1986\",\n \"GlossDef\": {\n \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n \"GlossSeeAlso\": [\"GML\", \"XML\"]\n },\n \"GlossSee\": \"markup\"\n }\n }\n }\n }\n}\n" }, { "answer_id": 3104376, "author": "Kyle Simpson", "author_id": 228852, "author_profile": "https://Stackoverflow.com/users/228852", "pm_score": 10, "selected": false, "text": "JSON.parse(JSON.minify(my_str));\n" }, { "answer_id": 3356227, "author": "raffel", "author_id": 404282, "author_profile": "https://Stackoverflow.com/users/404282", "pm_score": 6, "selected": false, "text": "{\n \"description\": \"A person\",\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"age\": {\n \"type\": \"integer\",\n \"maximum\": 125\n }\n }\n}\n" }, { "answer_id": 4183018, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 11, "selected": false, "text": "//… /*…*/ application/json" }, { "answer_id": 4729509, "author": "David", "author_id": 83852, "author_profile": "https://Stackoverflow.com/users/83852", "pm_score": 5, "selected": false, "text": "/* */ dojo.xhrGet()" }, { "answer_id": 6440396, "author": "peterk", "author_id": 576448, "author_profile": "https://Stackoverflow.com/users/576448", "pm_score": 5, "selected": false, "text": "\"#\": \"comment\"" }, { "answer_id": 7901053, "author": "schoetbi", "author_id": 108238, "author_profile": "https://Stackoverflow.com/users/108238", "pm_score": 7, "selected": false, "text": "// Configuration options\n{\n // Default encoding for text\n \"encoding\" : \"UTF-8\",\n\n // Plug-ins loaded at start-up\n \"plug-ins\" : [\n \"python\",\n \"c++\",\n \"ruby\"\n ],\n\n // Tab indent size\n \"indent\" : { \"length\" : 3, \"use_space\": true }\n}\n" }, { "answer_id": 11805048, "author": "AZ.", "author_id": 166286, "author_profile": "https://Stackoverflow.com/users/166286", "pm_score": 5, "selected": false, "text": "/* commment */" }, { "answer_id": 18018493, "author": "p3drosola", "author_id": 249161, "author_profile": "https://Stackoverflow.com/users/249161", "pm_score": 8, "selected": false, "text": "({a: 1, a: 2});\n// => Object {a: 2}\nObject.keys(JSON.parse('{\"a\": 1, \"a\": 2}')).length; \n// => 1\n {\n \"api_host\" : \"The hostname of your API server. You may also specify the port.\",\n \"api_host\" : \"hodorhodor.com\",\n\n \"retry_interval\" : \"The interval in seconds between retrying failed API calls\",\n \"retry_interval\" : 10,\n\n \"auth_token\" : \"The authentication token. It is available in your developer dashboard under 'Settings'\",\n \"auth_token\" : \"5ad0eb93697215bc0d48a7b69aa6fb8b\",\n\n \"favorite_numbers\": \"An array containing my all-time favorite numbers\",\n \"favorite_numbers\": [19, 13, 53]\n}\n {\n \"api_host\": \"hodorhodor.com\",\n \"retry_interval\": 10,\n \"auth_token\": \"5ad0eb93697215bc0d48a7b69aa6fb8b\",\n \"favorite_numbers\": [19,13,53]\n}\n" }, { "answer_id": 19234265, "author": "Sergey Orshanskiy", "author_id": 1243926, "author_profile": "https://Stackoverflow.com/users/1243926", "pm_score": 5, "selected": false, "text": "?(/* AAPL historical OHLC data from the Google Finance API */\n[\n/* May 2006 */\n[1147651200000,67.79],\n[1147737600000,64.98],\n...\n[1368057600000,456.77],\n[1368144000000,452.97]\n]);\n $.getJSON text/javascript application/json" }, { "answer_id": 19655633, "author": "Chris", "author_id": 959219, "author_profile": "https://Stackoverflow.com/users/959219", "pm_score": 4, "selected": false, "text": "{\n\n\"#############################\" : \"Part1\",\n\n\"data1\" : \"value1\",\n\"data2\" : \"value2\",\n\n\"#############################\" : \"Part2\",\n\n\"data4\" : \"value3\",\n\"data3\" : \"value4\"\n\n}\n" }, { "answer_id": 20267852, "author": "Steve Thomas", "author_id": 1869759, "author_profile": "https://Stackoverflow.com/users/1869759", "pm_score": 3, "selected": false, "text": "{\n \"note1\" : \"This demonstrates the provision of annotations within a JSON file\",\n \"field1\" : 12,\n \"field2\" : \"some text\",\n\n \"note2\" : \"Add more annotations as necessary\"\n}\n" }, { "answer_id": 20434146, "author": "Joshua Richardson", "author_id": 973402, "author_profile": "https://Stackoverflow.com/users/973402", "pm_score": 4, "selected": false, "text": "var comments = new RegExp(\"//.*\", 'mg');\ndata = JSON.parse(fs.readFileSync(sample_file, 'utf8').replace(comments, ''));\n data = require(fs.realpathSync(doctree_fp));\n" }, { "answer_id": 21409180, "author": "Aurimas", "author_id": 757328, "author_profile": "https://Stackoverflow.com/users/757328", "pm_score": 3, "selected": false, "text": "{\n \"param\" : \"This is the comment place\",\n \"param\" : \"This is value place\",\n}\n {\n \"param\" : \"This is value place\",\n}\n" }, { "answer_id": 21613658, "author": "Andrejs", "author_id": 1180621, "author_profile": "https://Stackoverflow.com/users/1180621", "pm_score": 6, "selected": false, "text": "ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_COMMENTS, true);\n {\n key: \"value\" // Comment\n}\n # mapper.configure(Feature.ALLOW_YAML_COMMENTS, true);\n" }, { "answer_id": 23275699, "author": "William Entriken", "author_id": 300224, "author_profile": "https://Stackoverflow.com/users/300224", "pm_score": 5, "selected": false, "text": "$jsonMin = json_encode(json_decode($json));\n $hex = unpack('H*', $comment);\n$commentBinary = base_convert($hex[1], 16, 2);\n $steg = str_replace('0', ' ', $commentBinary);\n$steg = str_replace('1', \"\\t\", $steg);\n $jsonWithComment = $steg . $jsonMin;\n" }, { "answer_id": 24545329, "author": "Даниил Пронин", "author_id": 766307, "author_profile": "https://Stackoverflow.com/users/766307", "pm_score": 3, "selected": false, "text": "{\n // Rainbows\n \"unicorn\": /* ❤ */ \"cake\"\n}\n" }, { "answer_id": 24618928, "author": "Maurício Giordano", "author_id": 1822704, "author_profile": "https://Stackoverflow.com/users/1822704", "pm_score": -1, "selected": false, "text": "/****\n * Hey\n */\n\n/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/\n // Hey\n\n/\\/\\/.*/\n jsonString = jsonString.replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/, \"\").replace(/\\/\\/.*/,\"\")\nvar object = JSON.parse(jsonString);\n" }, { "answer_id": 24839354, "author": "Nick", "author_id": 956278, "author_profile": "https://Stackoverflow.com/users/956278", "pm_score": 3, "selected": false, "text": "module.exports module.exports = {\n \"key\": \"value\",\n\n // And with comments!\n \"key2\": \"value2\"\n};\n require .js" }, { "answer_id": 27169861, "author": "Joy", "author_id": 978320, "author_profile": "https://Stackoverflow.com/users/978320", "pm_score": 4, "selected": false, "text": "strip-json-comments /*\n * Description \n*/\n{\n // rainbows\n \"unicorn\": /* ❤ */ \"cake\"\n}\n npm install --save strip-json-comments var strip_json_comments = require('strip-json-comments')\nvar json = '{/*rainbows*/\"unicorn\":\"cake\"}';\nJSON.parse(strip_json_comments(json));\n//=> {unicorn: 'cake'}\n" }, { "answer_id": 31512948, "author": "Manish Shrivastava", "author_id": 1133932, "author_profile": "https://Stackoverflow.com/users/1133932", "pm_score": 5, "selected": false, "text": "_comment" }, { "answer_id": 33583560, "author": "Mark", "author_id": 723090, "author_profile": "https://Stackoverflow.com/users/723090", "pm_score": 3, "selected": false, "text": "commentjson # // json_tricks # // json_tricks" }, { "answer_id": 34504798, "author": "vitaly-t", "author_id": 1102051, "author_profile": "https://Stackoverflow.com/users/1102051", "pm_score": 4, "selected": false, "text": "/*\n* multi-line comments\n**/\n{\n \"value\": 123 // one-line comment\n}\n var decomment = require('decomment');\nvar fs = require('fs');\n\nfs.readFile('input.js', 'utf8', function (err, data) {\n if (err) {\n console.log(err);\n } else {\n var text = decomment(data); // removing comments\n var json = JSON.parse(text); // parsing JSON\n console.log(json);\n }\n});\n { value: 123 }\n" }, { "answer_id": 35347457, "author": "MovGP0", "author_id": 601990, "author_profile": "https://Stackoverflow.com/users/601990", "pm_score": 2, "selected": false, "text": "{\n \"https://schema.org/comment\": \"this is a comment\"\n}\n" }, { "answer_id": 36213249, "author": "Meru-kun", "author_id": 5146783, "author_profile": "https://Stackoverflow.com/users/5146783", "pm_score": 2, "selected": false, "text": "function json_clean_decode($json, $assoc = true, $depth = 512, $options = 0) {\n // search and remove comments like /* */ and //\n $json = preg_replace(\"#(/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/)|([\\s\\t]//.*)|(^//.*)#\", '', $json);\n\n if(version_compare(phpversion(), '5.4.0', '>=')) {\n $json = json_decode($json, $assoc, $depth, $options);\n }\n elseif(version_compare(phpversion(), '5.3.0', '>=')) {\n $json = json_decode($json, $assoc, $depth);\n }\n else {\n $json = json_decode($json, $assoc);\n }\n\n return $json;\n }\n" }, { "answer_id": 39171793, "author": "WilliamK", "author_id": 3123980, "author_profile": "https://Stackoverflow.com/users/3123980", "pm_score": 5, "selected": false, "text": "header(\"My-Json-Comment: Yes, I know it's a workaround ;-) \");\n" }, { "answer_id": 41038255, "author": "xdeepakv", "author_id": 1594359, "author_profile": "https://Stackoverflow.com/users/1594359", "pm_score": 2, "selected": false, "text": "JSON.parse var oldParse = JSON.parse;\nJSON.parse = parse;\nfunction parse(json){\n json = json.replace(/\\/\\*.+\\*\\//, function(comment){\n console.log(\"comment:\", comment);\n return \"\";\n });\n return oldParse(json)\n}\n {\n \"test\": 1\n /* Hello, babe */\n}\n" }, { "answer_id": 43440043, "author": "Alexander Shostak", "author_id": 7875310, "author_profile": "https://Stackoverflow.com/users/7875310", "pm_score": 3, "selected": false, "text": "function json_decode_commented ($data, $objectsAsArrays = false, $maxDepth = 512, $opts = 0) {\n $data = preg_replace('~\n (\" (?:[^\"\\\\\\\\] | \\\\\\\\\\\\\\\\ | \\\\\\\\\")*+ \") | \\# [^\\v]*+ | // [^\\v]*+ | /\\* .*? \\*/\n ~xs', '$1', $data);\n\n return json_decode($data, $objectsAsArrays, $maxDepth, $opts);\n}\n" }, { "answer_id": 44700108, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 7, "selected": false, "text": "{\n \"//\": \"Some browsers will use this to enable push notifications.\",\n \"//\": \"It is the same for all projects, this is not your project's sender ID\",\n \"gcm_sender_id\": \"1234567890\"\n}\n" }, { "answer_id": 50930429, "author": "fyngyrz", "author_id": 599484, "author_profile": "https://Stackoverflow.com/users/599484", "pm_score": 5, "selected": false, "text": "// /* */ # {\n \"Notations\": [\n {\n \"anchorX\": 333,\n \"anchorY\": 265,\n \"areaMode\": \"Ellipse\",\n \"extentX\": 356,\n \"extentY\": 294,\n \"opacity\": 0.5,\n \"text\": \"Elliptical area on top\",\n \"textX\": 333,\n \"textY\": 265,\n \"title\": \"Notation 1\"\n },\n {\n \"anchorX\": 87,\n \"anchorY\": 385,\n \"areaMode\": \"Rectangle\",\n \"extentX\": 109,\n \"extentY\": 412,\n \"opacity\": 0.5,\n \"text\": \"Rect area\\non bottom\",\n \"textX\": 98,\n \"textY\": 385,\n \"title\": \"Notation 2\"\n },\n {\n \"anchorX\": 69,\n \"anchorY\": 104,\n \"areaMode\": \"Polygon\",\n \"extentX\": 102,\n \"extentY\": 136,\n \"opacity\": 0.5,\n \"pointList\": [\n {\n \"i\": 0,\n \"x\": 83,\n \"y\": 104\n },\n {\n \"i\": 1,\n \"x\": 69,\n \"y\": 136\n },\n {\n \"i\": 2,\n \"x\": 102,\n \"y\": 132\n },\n {\n \"i\": 3,\n \"x\": 83,\n \"y\": 104\n }\n ],\n \"text\": \"Simple polygon\",\n \"textX\": 85,\n \"textY\": 104,\n \"title\": \"Notation 3\"\n }\n ],\n \"imageXW\": 512,\n \"imageYW\": 512,\n \"imageName\": \"lena_std.ato\",\n \"tinyDocs\": {\n \"c01\": \"JSON image notation data:\",\n \"c02\": \"-------------------------\",\n \"c03\": \"\",\n \"c04\": \"This data contains image notations and related area\",\n \"c05\": \"selection information that provides a means for an\",\n \"c06\": \"image gallery to display notations with elliptical,\",\n \"c07\": \"rectangular, polygonal or freehand area indications\",\n \"c08\": \"over an image displayed to a gallery visitor.\",\n \"c09\": \"\",\n \"c10\": \"X and Y positions are all in image space. The image\",\n \"c11\": \"resolution is given as imageXW and imageYW, which\",\n \"c12\": \"you use to scale the notation areas to their proper\",\n \"c13\": \"locations and sizes for your display of the image,\",\n \"c14\": \"regardless of scale.\",\n \"c15\": \"\",\n \"c16\": \"For Ellipses, anchor is the center of the ellipse,\",\n \"c17\": \"and the extents are the X and Y radii respectively.\",\n \"c18\": \"\",\n \"c19\": \"For Rectangles, the anchor is the top left and the\",\n \"c20\": \"extents are the bottom right.\",\n \"c21\": \"\",\n \"c22\": \"For Freehand and Polygon area modes, the pointList\",\n \"c23\": \"contains a series of numbered XY points. If the area\",\n \"c24\": \"is closed, the last point will be the same as the\",\n \"c25\": \"first, so all you have to be concerned with is drawing\",\n \"c26\": \"lines between the points in the list. Anchor and extent\",\n \"c27\": \"are set to the top left and bottom right of the indicated\",\n \"c28\": \"region, and can be used as a simplistic rectangular\",\n \"c29\": \"detect for the mouse hover position over these types\",\n \"c30\": \"of areas.\",\n \"c31\": \"\",\n \"c32\": \"The textx and texty positions provide basic positioning\",\n \"c33\": \"information to help you locate the text information\",\n \"c34\": \"in a reasonable location associated with the area\",\n \"c35\": \"indication.\",\n \"c36\": \"\",\n \"c37\": \"Opacity is a value between 0 and 1, where .5 represents\",\n \"c38\": \"a 50% opaque backdrop and 1.0 represents a fully opaque\",\n \"c39\": \"backdrop. Recommendation is that regions be drawn\",\n \"c40\": \"only if the user hovers the pointer over the image,\",\n \"c41\": \"and that the text associated with the regions be drawn\",\n \"c42\": \"only if the user hovers the pointer over the indicated\",\n \"c43\": \"region.\"\n }\n}\n" }, { "answer_id": 51232322, "author": "bortunac", "author_id": 544803, "author_profile": "https://Stackoverflow.com/users/544803", "pm_score": 2, "selected": false, "text": " $rgx_arr = [\"/\\/\\/[^\\n]*/sim\", \"/\\/\\*.*?\\*\\//sim\", \"/[\\n\\r\\t]/sim\"];\n $valid_json_str = \\preg_replace($rgx_arr, '', file_get_contents(path . 'a_file.json'));\n valid_json_str = json_str.replace(/\\/\\/[^\\n]*/gim,'').replace(/\\/\\*.*?\\*\\//gim,'')\n" }, { "answer_id": 55238032, "author": "jlettvin", "author_id": 1363592, "author_profile": "https://Stackoverflow.com/users/1363592", "pm_score": 2, "selected": false, "text": "fetch(filename).then(function(response) {\n return response.text();\n}).then(function(commented) {\n return commented.\n replace(/\\/\\*[\\s\\S]*?\\*\\/|([^\\\\:]|^)\\/\\/.*$/gm, '$1').\n replace(/\\r/,\"\\n\").\n replace(/\\n[\\n]+/,\"\\n\");\n}).then(function(clean) {\n return JSON.parse(clean);\n}).then(function(json) {\n // Do what you want with the JSON object.\n});\n" }, { "answer_id": 55547317, "author": "Malekai", "author_id": 10415695, "author_profile": "https://Stackoverflow.com/users/10415695", "pm_score": 1, "selected": false, "text": "json.loads dict import json, re\n\ndef parse_json(data_string):\n result = []\n for line in data_string.split(\"\\n\"):\n line = line.strip()\n if len(line) < 1 or line[0:2] == \"//\":\n continue\n if line[-1] not in \"\\,\\\"\\'\":\n line = re.sub(\"\\/\\/.*?$\", \"\", line)\n result.append(line)\n return json.loads(\"\\n\".join(result))\n\nprint(parse_json(\"\"\"\n{\n // This is a comment\n \"name\": \"value\" // so is this\n // \"name\": \"value\"\n // the above line gets removed\n}\n\"\"\"))\n" }, { "answer_id": 56626450, "author": "Roy Prins", "author_id": 470917, "author_profile": "https://Stackoverflow.com/users/470917", "pm_score": 5, "selected": false, "text": "010212 010202 011000 011000 011010 001012 010122 010121 011021 010202 001012 011022 010212 011020 010202 010202\n hello base three" }, { "answer_id": 58731581, "author": "ifelse.codes", "author_id": 2950614, "author_profile": "https://Stackoverflow.com/users/2950614", "pm_score": 3, "selected": false, "text": "// or /* */" }, { "answer_id": 62338887, "author": "nevelis", "author_id": 333988, "author_profile": "https://Stackoverflow.com/users/333988", "pm_score": 1, "selected": false, "text": "{\n \"\": \"Location to post to\",\n \"postUrl\": \"https://example.com/upload/\",\n\n \"\": \"Username for basic auth\",\n \"username\": \"joebloggs\",\n\n \"\": \"Password for basic auth (note this is in clear, be sure to use HTTPS!\",\n \"password\": \"bloejoggs\"\n}\n" }, { "answer_id": 64202860, "author": "khashashin", "author_id": 7986808, "author_profile": "https://Stackoverflow.com/users/7986808", "pm_score": 0, "selected": false, "text": "\"part_of_speech\": {\n \"__comment\": [\n \"@param {String} type - the following types can be used: \",\n \"NOUN, VERB, ADVERB, ADJECTIVE, PRONOUN, PREPOSITION\",\n \"CONJUNCTION, INTERJECTION, NUMERAL, PARTICLE, PHRASE\",\n \"@param {String} type_free_form - is optional, can be empty string\",\n \"@param {String} description - is optional, can be empty string\",\n \"@param {String} source - is optional, can be empty string\"\n ],\n \"type\": \"NOUN\",\n \"type_free_form\": \"noun\",\n \"description\": \"\",\n \"source\": \"https://google.com\",\n \"noun_class\": {\n \"__comment\": [\n \"@param {String} noun_class - the following types can be used: \",\n \"1_class, 2_class, 3_class, 4_class, 5_class, 6_class\"\n ],\n \"noun_class\": \"4_class\"\n }\n}\n" }, { "answer_id": 64907232, "author": "Audrius Meškauskas", "author_id": 1439305, "author_profile": "https://Stackoverflow.com/users/1439305", "pm_score": 5, "selected": false, "text": "// A single line comment.\n\n/* A multi-\n line comment. */\n" }, { "answer_id": 66570490, "author": "Boppity Bop", "author_id": 347484, "author_profile": "https://Stackoverflow.com/users/347484", "pm_score": -1, "selected": false, "text": "{\n // this is a comment for those who is ok with being different\n \"regular-json\": \"stuff\"...\n}\n" }, { "answer_id": 68124843, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 3, "selected": false, "text": "$ jq -ncf <(echo $'[1, # one\\n2 ] # two') \n[1,2]\n $ ls -l JEOPARDY_QUESTIONS1.json\n-rw-r--r-- 2 xyzzy staff 55554625 May 12 2016 JEOPARDY_QUESTIONS1.json\n\n$ jq -nf JEOPARDY_QUESTIONS1.json | jq length\n216930\n" }, { "answer_id": 68782282, "author": "dilshan", "author_id": 13237885, "author_profile": "https://Stackoverflow.com/users/13237885", "pm_score": 3, "selected": false, "text": "(jsonc) mode firebase.json {\n \"hosting\": {\n \"headers\": [\n /*{\n \"source\": \"*.html\",\n \"headers\": [\n {\n \"key\": \"Content-Security-Policy\",\n \"value\": \"default-src 'self' ...\"\n }\n ]\n },*/\n ]\n }\n }\n {\n \"comment\" : \"This is a comment\",\n \"//\" : \"This also comment\",\n \"name\" : \"This is a real value\"\n }\n" }, { "answer_id": 70139980, "author": "Deleted", "author_id": 585968, "author_profile": "https://Stackoverflow.com/users/585968", "pm_score": 2, "selected": false, "text": "{\n \"Logging\": {\n \"LogLevel\": { // All providers, LogLevel applies to all the enabled providers.\n \"Default\": \"Error\", // Default logging, Error and higher.\n \"Microsoft\": \"Warning\" // All Microsoft* categories, Warning and higher.\n },\n \"Debug\": { // Debug provider.\n \"LogLevel\": {\n \"Default\": \"Information\", // Overrides preceding LogLevel:Default setting.\n \"Microsoft.Hosting\": \"Trace\" // Debug:Microsoft.Hosting category.\n }\n },\n \"EventSource\": { // EventSource provider\n \"LogLevel\": {\n \"Default\": \"Warning\" // All categories of EventSource provider.\n }\n }\n }\n}\n" }, { "answer_id": 70373317, "author": "Heewoon", "author_id": 17341715, "author_profile": "https://Stackoverflow.com/users/17341715", "pm_score": 3, "selected": false, "text": "jsonWithComments.jsonc\n {\n // This is a comment!\n \"something\": \"idk\"\n\n}\n" }, { "answer_id": 71157617, "author": "EKanadily", "author_id": 365867, "author_profile": "https://Stackoverflow.com/users/365867", "pm_score": 3, "selected": false, "text": "{\n \"// my own comment goes here\":\"\",\n \"key1\":\"value 1\",\n\n \"// another comment goes here\":\"\",\n \"key 2\": \"value 2 here\"\n}\n {\n \"// my own comment goes here\" : \"_comment\",\n \"key1\":\"value 1\",\n\n \"// another comment goes here\" : \"_comment\",\n \"key 2\": \"value 2 here\"\n} \n \n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4105/" ]
244,779
<p>I have the following <code>before_filter</code>:</p> <pre><code> def find_current_membership respond_to do |wants| wants.html { @current_membership = @group.memberships.for(@current_user) } wants.rss {} wants.js { @current_membership = @group.memberships.for(@current_user) } end end </code></pre> <p>I would like to share the code for the HTML and JS blocks. Is there a better way than just throwing the code into a method? I was hoping this would work:</p> <pre><code> def find_current_membership respond_to do |wants| wants.rss {} wants.all { @current_membership = @group.memberships.for(@current_user) } end end </code></pre> <p>But alas, it did not.</p>
[ { "answer_id": 244831, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": "before_filter :only => :find_current_membership do |c|\n load_current_membership if not request.format.rss?\nend\n" }, { "answer_id": 244893, "author": "Cameron Booth", "author_id": 14873, "author_profile": "https://Stackoverflow.com/users/14873", "pm_score": 3, "selected": true, "text": "find_current_membership before_filter class SomeController < ApplicationController\n before_filter :find_current_membership\n ...\n respond_to before_filter class SomeController < ApplicationController\n before_filter :find_current_membership\n\n def some_action\n # stuff, or maybe nothing\n end\n\n private\n def find_current_membership\n @current_membership = @group.memberships.for(@current_user) unless request.format.rss?\n end\n end\n" }, { "answer_id": 246551, "author": "allesklar", "author_id": 19893, "author_profile": "https://Stackoverflow.com/users/19893", "pm_score": 1, "selected": false, "text": "def find_current_membership\n @current_membership = @group.memberships.for(@current_user)\n respond_to do |wants|\n wants.html\n wants.rss {}\n wants.js\n end\nend\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14895/" ]
244,807
<p>I have a c# site which makes use of a lot of images with embedded english text. </p> <p>How can I use a standard resource file to swap out images depending on the language?</p> <p>I have a resx file in my App_GlobalResources directory, but I can't seem to get it plugged into an asp:image control for the imageurl correctly.</p> <p>Ideas?</p> <p><strong>UPDATE:</strong> </p> <p>For some further information, here is the image tag code:</p> <pre><code>&lt;asp:image runat="server" ID="img2" ImageUrl="&lt;%$Resources: Resource, cs_logo %&gt;" /&gt; </code></pre> <p>The result on the client side is:</p> <pre><code>&lt;img id="img2" src="System.Drawing.Bitmap" style="border-width:0px;" /&gt; </code></pre> <p>Note that the source is obviously not what I expected...</p>
[ { "answer_id": 244830, "author": "Oscar Cabrero", "author_id": 14440, "author_profile": "https://Stackoverflow.com/users/14440", "pm_score": 4, "selected": true, "text": "<asp:Image ImageUrl=\"<%$resources:Image1 %>\" />\n" }, { "answer_id": 245141, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n\n Dim FinalBitmap As Bitmap\n Dim strRenderSource As String\n Dim msStream As New MemoryStream()\n\n strRenderSource = Request.Params(\"ImageName\").ToString()\n\n ' Write your code here that gets the image from the app resources.\n FinalBitmap = New Bitmap(Me.Resources(strRenderSource))\n FinalBitmap.Save(msStream, ImageFormat.Png)\n\n Response.Clear()\n Response.ContentType = \"image/png\"\n\n msStream.WriteTo(Response.OutputStream)\n\n If Not IsNothing(FinalBitmap) Then FinalBitmap.Dispose()\n\nEnd Sub\n <asp:Image ImageUrl=\"http://localhost/GetImage.aspx?ImageName=Image1\" />\n" }, { "answer_id": 1847349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<img id=\"WelocmeICon\" runat=\"server\" alt=\"welcome icon\" \n src=\"<%$resources:NmcResource,WelcomeIcon %>\" />\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2424/" ]
244,808
<p>Simple question really - how do I use <code>text_field_with_auto_complete</code> inside a <code>form_for</code> block?</p> <p>I've tried doing <code>f.text_field_with_auto_complete</code> but that gives an error, and just using <code>text_field_with_auto_complete</code> by itself doesn't seem to do anything.</p> <p>Am I missing something here?</p>
[ { "answer_id": 245392, "author": "Ricardo Acras", "author_id": 19224, "author_profile": "https://Stackoverflow.com/users/19224", "pm_score": 1, "selected": false, "text": "<UL>\n <LI ID=\"1\">Item 1</LI>\n < LI ID=\"2\">Item 2< /LI>\n</UL>\n <%= text_field_with_auto_complete :model, :method, {}, :after_update_element => ‘getSelectionId’ % >\n function getSelectionId(text, li) {\n\nalert (li.id);\n\n}\n" }, { "answer_id": 248577, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 3, "selected": false, "text": "<%= f.text_field :name, :autocomplete => \"off\" %><div class=\"auto_complete\" id=\"customer_name_auto_complete\"></div>\n new Ajax.Autocompleter('customer_name', 'customer_name_auto_complete', '/customers/auto_complete_for_customer_name', {\n method:'get',\n paramName:'customer[name]',\n minChars: 3\n});\n div.auto_complete {\n width: 350px;\n background: #fff;\n}\n\ndiv.auto_complete ul {\n border:1px solid #888;\n margin:0;\n padding:0;\n width:100%;\n list-style-type:none;\n}\n\ndiv.auto_complete ul li {\n margin:0;\n padding:3px;\n}\n\ndiv.auto_complete ul li.selected {\n background-color: #ffb;\n}\n\ndiv.auto_complete ul strong.highlight {\n color: #800;\n margin:0;\n padding:0;\n}\n" }, { "answer_id": 405796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<% fields_for :model, @formobject.model do %>\n<p>\n<%= text_field_with_auto_complete :object, :field, :skip_style => true %>\n</p>\n<% end %>\n" }, { "answer_id": 430979, "author": "pat", "author_id": 53685, "author_profile": "https://Stackoverflow.com/users/53685", "pm_score": 3, "selected": true, "text": "text_field_with_auto_complete fields_for form_for" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
244,811
<p>For my web service component, I need to generate a relatively large XML (~500 lines) according to many factors. I am facing a few different choices here: 1. StringBuilder 2. XmlWriter class 3. C# object with serialization???</p> <p>Which one should I use. Is there any other ways that I am not aware of?</p>
[ { "answer_id": 244827, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": " public static IEnumerable<XElement> AsXElements(this object source)\n {\n foreach (PropertyInfo prop in source.GetType().GetProperties())\n {\n object value = prop.GetValue(source, null);\n yield return new XElement(prop.Name.Replace(\"_\", \"-\"), value);\n }\n }\n\n public static IEnumerable<XAttribute> AsXAttributes(this object source)\n {\n foreach (PropertyInfo prop in source.GetType().GetProperties())\n {\n object value = prop.GetValue(source, null);\n yield return new XAttribute(prop.Name.Replace(\"_\", \"-\"), value ?? \"\");\n }\n }\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088/" ]
244,812
<p>I have an existing database with the table Transactions in it. I have added a new table called TransactionSequence where each transaction will ultimately have only one record. We are using the sequence table to count transactions for a given account. I have mapped this as a one-to-one mapping where TransactionSequence has a primary key of TransactionId. </p> <p>The constraint is that there is an instead of trigger on the transaction table does not allow updates of cancelled or posted transactions. </p> <p>So, when the sequence is calculated and the transaction is saved, NHibernate tries to send an update on the transaction like 'UPDATE Transaction SET TransactionId = ? WHERE TransactionId = ?'. But this fails because of the trigger. How can I configure my mapping so that NHibernate will not try to update the Transaction table when a new TransactionSequence table is inserted?</p> <p>Transaction mapping:</p> <pre><code>&lt;class name="Transaction" table="Transaction" dynamic-update="true" select-before-update="true"&gt; &lt;id name="Id" column="ID"&gt; &lt;generator class="native" /&gt; &lt;/id&gt; &lt;property name="TransactionTypeId" access="field.camelcase-underscore" /&gt; &lt;property name="TransactionStatusId" column="DebitDebitStatus" access="field.camelcase-underscore" /&gt; &lt;one-to-one name="Sequence" class="TransactionSequence" fetch="join" lazy="false" constrained="false"&gt; &lt;/one-to-one&gt; &lt;/class&gt; </code></pre> <p>And the sequence mapping:</p> <pre><code>&lt;class name="TransactionSequence" table="TransactionSequence" dynamic-update="true"&gt; &lt;id name="TransactionId" column="TransactionID" type="Int32"&gt; &lt;generator class="foreign"&gt; &lt;param name="property"&gt;Transaction&lt;/param&gt; &lt;/generator&gt; &lt;/id&gt; &lt;version name="Version" column="Version" unsaved-value="-1" access="field.camelcase-underscore" /&gt; &lt;property name="SequenceNumber" not-null="true" /&gt; &lt;one-to-one name="Transaction" class="Transaction" constrained="true" foreign-key="fk_Transaction_Sequence" /&gt; &lt;/class&gt; </code></pre> <p>Any help would be greatly appreciated...</p>
[ { "answer_id": 244871, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 5, "selected": true, "text": "<one-to-one name=\"Sequence\" class=\"TransactionSequence\" property-ref=\"Transaction\"/>\n <many-to-one name=\"Transaction\" class=\"Transaction\" column=\"fk_Transaction_Sequence\" />\n" }, { "answer_id": 246688, "author": "SteveBering", "author_id": 32196, "author_profile": "https://Stackoverflow.com/users/32196", "pm_score": 2, "selected": false, "text": "<join table> <join table>" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32196/" ]
244,826
<p>I'm stuck with .Net 1.1 application (i.e. I can not use the generics goodies from 2.0 for now), and I was trying to optimize some parts of the code. As it deals a lot with runtime callable wrappers, which need to be released, I ended up to create a utility method which loops until all references are released. The signature of the method is:</p> <pre><code>void ReleaseObject(object comObject) </code></pre> <p>After releasing all comObjects, I call GC.Collect and GC.WaitForPendingFinalizers (don't ask - anybody dealing with Office interop knows).</p> <p>And ... as usual, I hit a corner case - if I do not assign the corresponding managed reference to null before the GC.Collect call, it does not cleanup properly.</p> <p>So, my code looks like:</p> <pre><code>ReleaseObject(myComObject); myComObject = null; GC.Collect() ... </code></pre> <p>As, there are a bunch of xxx=null, I decided to put this in the util method, but as there is a difference between passing by reference, and passing a reference parameter, obviously I had to change the method to:</p> <pre><code>void ReleaseObject(out object comObject) { //do release comObject = null; } </code></pre> <p>and edit the caller to:</p> <pre><code>MyComClass myComObject = xxxx; ReleaseObject(out myComObject); </code></pre> <p>This fails with a message: "Cannot convert from 'out MyComClass' to 'out object'"</p> <p>While I can think of why it can be a problem (i.e. the reverse cast from object to MyComClass is not implicit, and there is no guarantee what the method will do), I was wondering if there is a workaround, or I need to stay with my hundreds assignments of nulls.</p> <p>Note: I have a bunch of different COM objects types, thats why I need a "object" parameter, and not a type safe one.</p>
[ { "answer_id": 244880, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "Marshal.ReleaseComObject static void ReleaseObject(ref object comObject)\n{\n if(comObject != null)\n {\n //do release\n comObject = null;\n }\n}\n SomeType obj = new SomeType();\ntry {\n obj.SomeMethod(); // etc\n} finally {\n Marshal.ReleaseComObject(obj);\n}\n" }, { "answer_id": 244887, "author": "Leopold Cimrman", "author_id": 32008, "author_profile": "https://Stackoverflow.com/users/32008", "pm_score": 0, "selected": false, "text": "List garbagedObjects = new List();\ngarbagedObjects.Add(myComObject1);\ngarbagedObjects.Add(myComObject2);\n...\nforeach(object garbagedObject in garbagedObjects)\n{\n ReleaseObject(garbagedObject);\n garbagedObject = null;\n}\ngarbagedObjects = null;\nGC.Collect();\n...\n" }, { "answer_id": 245357, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 2, "selected": false, "text": "out void foo( out MyClass x)\n x x x ref void foo( ref MyClass x)\n // need a remove method for each type. \nvoid Remove( ref Com1 x ) { ...; x = null; }\nvoid Remove( ref Con2 x ) { ...; x = null; }\nvoid Remove( ref Com3 x ) { ...; x = null; }\n\n// a generics version using ref.\nvoid RemoveComRef<ComT>(ref ComT t) where ComT : class\n{\n System.Runtime.InteropServices.Marshal.ReleaseComObject(t);\n t = null; \n}\n\nCom1 c1 = new Com1();\nCom2 c2 = new Com2();\nRemove( ref c1 );\nRemoveComRef(ref c2); // the generics version again.\n class Remover\n{\n // .net 1.1 must cast if assigning\n public static object Remove(object x)\n {\n System.Runtime.InteropServices.Marshal.ReleaseComObject(x);\n return null;\n }\n\n // uses generics.\n public static ComT RemoveCom<ComT>(ComT t) where ComT : class\n {\n System.Runtime.InteropServices.Marshal.ReleaseComObject(t);\n return null;\n } \n}\n\nCom1 c1 = new Com1();\nCom2 c2 = new Com2();\nc1 = (Com1)Remover.Remove(c1); // no reliance on generics\nc2 = Remover.RemoveCom(c2); // relies on generics\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8220/" ]
244,875
<p>I have a custom webpart that is displaying dynamic list data, it needs to render an image from a Picture Library (or at least provide me the URL so I can encapsulate it with an tag), however, none of the fields in the Picture Library seem to contain the image URL? Is there a 'image utility' (SPImageUtility) or something I can use to pull this out? Or am I simply missing something?</p>
[ { "answer_id": 248978, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 2, "selected": false, "text": "SPListItem[\"EncodedAbsUrl\"]\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105/" ]
244,879
<p>We are re-platforming for a client, and they are concerned about SEO. Their current site supports SEO friendly URLs, and so does the new platform. So for those, we are just going to create the same URL mapping. However, they have a large number of other URLs that are not SEO friendly that they want to permanently redirect. These do not follow a similar pattern, so one regex in an .htaccess won't cut it. What is the best way to handle this on a LAMP stack? The application has a front controller too, so I need to make sure that works along with the hard redirects.</p>
[ { "answer_id": 246326, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 0, "selected": false, "text": "header(\"Location: /new.html\",TRUE,301);\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
244,881
<p>Can dynamic variables in C# 4.0 be members on a class or passed into or returned from methods? var from C# 3.0 couldn't but I haven't seen any mention anywhere of whether it is possible or not with dynamic.</p>
[ { "answer_id": 245015, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "var dynamic var dynamic dynamic dynamic dynamic" }, { "answer_id": 2508443, "author": "Mohsen Afshin", "author_id": 191148, "author_profile": "https://Stackoverflow.com/users/191148", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Dynamic;\nstatic class DyanmicDemo\n{\n public static void Main() {\n for(Int32 demo =0; demo < 2; demo++) {\n dynamic arg = (demo == 0) ? (dynamic) 5 : (dynamic) \"A\";\n dynamic result = Plus(arg);\n M(result);\n }\n }\n private static dynamic Plus(dynamic arg) { return arg + arg; }\n private static void M(Int32 n) { Console.WriteLine(\"M(Int32): \" + n); }\n private static void M(String s) { Console.WriteLine(\"M(String): \" + s); }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11829/" ]
244,882
<p>I want my website to have a checkbox that users can click so that they will not have to log in each time they visit my website. I know I will need to store a cookie on their computer to implement this, but what should be contained in that cookie? </p> <p>Also, are there common mistakes to watch out for to keep this cookie from presenting a security vulnerability, which could be avoided while still giving the 'remember me' functionality?</p>
[ { "answer_id": 572740, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "@splattne" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9323/" ]
244,884
<p>I'm really stumped on this one. I want to output a list and have the tag file take care of commas, singular versus plural, etc. but when I display the list it completely ignores whitespace so everythingrunstogetherlikethis. I tried using the HTML entities "thinsp", "ensp" and "emsp" (I can't use "nbsp", these have to be breaking), but they're all hideously wide on IE except thinsp which is way too skinny on everything else.</p> <p>Edit: won't work. The output from the tag has no spaces at all. Although any content in the JSP has normal spacing. Obviously I could just put everything in the JSP but this is code that goes on multiple JSPs, so tag files would make a lot of sense.</p>
[ { "answer_id": 245305, "author": "alex77", "author_id": 1555, "author_profile": "https://Stackoverflow.com/users/1555", "pm_score": 2, "selected": false, "text": "<pre>" }, { "answer_id": 2133587, "author": "gshegosh", "author_id": 258570, "author_profile": "https://Stackoverflow.com/users/258570", "pm_score": 1, "selected": false, "text": "&#32;" }, { "answer_id": 2134454, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 4, "selected": false, "text": "${bean.foo} ${bean.bar} ${bean.waa}\n foobarwaa\n c:out <c:out value=\"${bean.foo} ${bean.bar} ${bean.waa}\" />\n foo bar waa\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484/" ]
244,886
<p>Consider the following code:</p> <pre><code>Public Class Animal Public Overridable Function Speak() As String Return "Hello" End Function End Class Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function End Class Dim dog As New Dog Dim animal As Animal animal = CType(dog, Animal) // Want "Hello", getting "Ruff" animal.Speak() </code></pre> <p>How can I convert/ctype the instance of Dog to Animal and have Animal.Speak get called?</p>
[ { "answer_id": 244910, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": false, "text": "Public Class Dog \n Inherits Animal\n Public Overrides Function Speak() As String\n Return \"Ruff\"\n End Function\n Public Function SpeakAsAnimal() As String\n Return MyBase.Speak()\n End Function\nEnd Class\n" }, { "answer_id": 244915, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "Public Class Cat\n Inherits Animal\n\n Public Overrides Function Speak() As String\n Return \"Meow\"\n End Function\nEnd Class\n protected sub Something\n Dim oCat as New Cat\n Dim oDog as New Dog\n\n MakeSpeak(oCat)\n MakeSpeak(oDog)\nEnd sub\n\nprotected sub MakeSpeak(ani as animal)\n Console.WriteLine(ani.Speak())\nend sub \n" }, { "answer_id": 245039, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 1, "selected": false, "text": "MyBase.Speak()\n" }, { "answer_id": 321115, "author": "Matt Burke", "author_id": 29691, "author_profile": "https://Stackoverflow.com/users/29691", "pm_score": 0, "selected": false, "text": "Public Class Animal\n\nPublic Function Speak() As String\n Return \"Hello\"\nEnd Function\n\nEnd Class\n\nPublic Class Dog\n Inherits Animal\n\n Public New Function Speak() As String\n Return \"Ruff\"\n End Function\n\nEnd Class\n\nDim dog As New Dog\nDim animal As Animal\ndog.Speak() ' should be \"Ruff\"\nanimal = CType(dog, Animal)\nanimal.Speak() ' should be \"Hello\"\n" }, { "answer_id": 27599112, "author": "tfrascaroli", "author_id": 1420614, "author_profile": "https://Stackoverflow.com/users/1420614", "pm_score": 0, "selected": false, "text": "dog Public Class Animal\n\nPublic Overridable Function Speak(Optional ByVal speakNormal as Boolean = False) As String\n Return \"Hello\"\nEnd Function\n\nEnd Class\n\nPublic Class Dog\n Inherits Animal\n\n Public Overrides Function Speak(Optional ByVal speakNormal as Boolean = False) As String\n If speakNormal then\n return MyBase.Speak()\n Else\n Return \"Ruff\"\n End If\n End Function\n\nEnd Class\n Dim dog As New Dog\nDim animal As new Animal\nanimal.Speak() //\"Hello\"\ndog.Speak()//\"Ruff\"\ndog.Speak(true)//\"Hello\"\n getTheAnimalInTheDog Speak() Public Class Animal\n\nPublic Overridable Function Speak() As String\n Return \"Hello\"\nEnd Function\n\nPublic MustOverride Function GetTheAnimalInMe() As Animal\n\nEnd Class\n\nPublic Class Dog\n Inherits Animal\n\n Public Overrides Function Speak() As String\n Return \"Ruff\"\n End Function\n\n Public Overrides Function GetTheAnimalInMe() As Animal\n Dim a As New Animal\n //Load a with the necessary custom parameters (if any)\n Return a\n End Function\nEnd Class\n Dim dog As New Dog\nDim animal As new Animal\nanimal.Speak() //\"Hello\"\ndog.Speak()//\"Ruff\"\ndog.GetTheAnimalInMe().Speak()//\"Hello\"\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81/" ]
244,892
<p>I have a protected Excel worksheet, without a password. What I'd like to do is trap the event that a user unprotects the worksheet, so that I can generate a message (and nag 'em!). I can setup event checking for the application, for when new workbooks are opened, etc., but not for Unprotect.<br> Does anyone have an idea?</p>
[ { "answer_id": 245036, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "Sub UnprotectTrap()\nIf ActiveSheet.ProtectContents = True Then\n MsgBox \"Tut,tut!\"\n ActiveSheet.Unprotect\nElse\n ActiveSheet.Protect\n\nEnd If\nEnd Sub\n" }, { "answer_id": 245139, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)\n If Sheets(\"MyProtectedSheet\").ProtectContents = False Then\n MsgBox \"The sheet 'MyProtectedSheet' should not be left unprotected. I will protect it before saving\", vbInformation\n Sheets(\"MyProtectedSheet\").Protect\n End If\nEnd Sub\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
244,896
<p>Is it possible via code to programmatically (from .NET for example via SQL query) to ask an Access database if it is corrupt or have tables with corrupt rows in it?</p> <p>//Andy</p>
[ { "answer_id": 244911, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "Sub CheckForErr(tablename)\nDim rs As dao.Recordset\nDim db As Database\n\nSet db = CurrentDb\n\nSet rs = db.OpenRecordset(tname)\n\nWith rs\n Do While Not .EOF\n For Each fld In rs.Fields\n If IsError(rs(fld.Name)) Then\n Debug.Print \"Error\"\n End If\n Next\n .MoveNext\n Loop\nEnd With\n\nrs.Close\nSet rs = Nothing\n\nEnd Sub\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
244,903
<p>Is there a significance to the word "salt" for a password salt?</p>
[ { "answer_id": 245134, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": false, "text": "(salt away) informal put by (money) secretly. \n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26604/" ]
244,913
<p>I need to match a string like "one. two. three. four. five. six. seven. eight. nine. ten. eleven" into groups of four sentences. I need a regular expression to break the string into a group after every fourth period. Something like: </p> <pre><code> string regex = @"(.*.\s){4}"; System.Text.RegularExpressions.Regex exp = new System.Text.RegularExpressions.Regex(regex); string result = exp.Replace(toTest, ".\n"); </code></pre> <p>doesn't work because it will replace the text before the periods, not just the periods themselves. How can I count just the periods and replace them with a period and new line character?</p>
[ { "answer_id": 244955, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 1, "selected": false, "text": "private string AppendNewLineToMatch(Match match) {\n return match.Value + Environment.NewLine;\n}\n string result = exp.Replace(toTest, AppendNewLineToMatch);\n string regex = @\"([^.]*[.]\\s*){4}\";\n" }, { "answer_id": 244964, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 2, "selected": false, "text": ". .*. .+ [^.]\\*[.] . ." }, { "answer_id": 244969, "author": "Ben", "author_id": 26633, "author_profile": "https://Stackoverflow.com/users/26633", "pm_score": 0, "selected": false, "text": "@\"(?:([^\\.]+?).\\s)(?:([^\\.]+?).\\s)(?:([^\\.]+?).\\s)(?:([^\\.]+?).\\s)\" \"$1 $2 $3 $4.\\n\" one two three four.\nfive six seven eight.\nnine. ten. eleven\n @\"(?:([^.]+?).\\s){4}\"" }, { "answer_id": 244980, "author": "Matthew Brubaker", "author_id": 21311, "author_profile": "https://Stackoverflow.com/users/21311", "pm_score": -1, "selected": false, "text": "String s = \"one. two. three. four. five. six. seven. eight. nine. ten. eleven\"\nString[] splitString = s.split(\".\")\nList li = new ArrayList(splitString.length/2)\nfor(int i=0;i<splitString.length;i+=4) {\n st = splitString[i]+\".\"\n st += splitString[i+1]+\".\"\n st += splitString[i+2]+\".\"\n st += splitString[i+3]+\".\"\n li.add(st)\n}\n" }, { "answer_id": 245606, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "string regex = @\"([^.]*[.]){4}\\s*\";\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4555/" ]
244,918
<p>I'm writing an application and I'm trying to tie simple AJAX functionality in. It works well in Mozilla Firefox, but there's an interesting bug in Internet Explorer: Each of the links can only be clicked once. The browser must be completely restarted, simply reloading the page won't work. I've written a <a href="http://static.stillinbeta.com/page/" rel="noreferrer">very simple example application</a> that demonstrates this.</p> <p>Javascript reproduced below:</p> <pre><code>var xmlHttp = new XMLHttpRequest(); /* item: the object clicked on type: the type of action to perform (one of 'image','text' or 'blurb' */ function select(item,type) { //Deselect the previously selected 'selected' object if(document.getElementById('selected')!=null) { document.getElementById('selected').id = ''; } //reselect the new selcted object item.id = 'selected'; //get the appropriate page if(type=='image') xmlHttp.open("GET","image.php"); else if (type=='text') xmlHttp.open("GET","textbox.php"); else if(type=='blurb') xmlHttp.open("GET","blurb.php"); xmlHttp.send(null); xmlHttp.onreadystatechange = catchResponse; return false; } function catchResponse() { if(xmlHttp.readyState == 4) { document.getElementById("page").innerHTML=xmlHttp.responseText; } return false; } </code></pre> <p>Any help would be appreciated.</p>
[ { "answer_id": 244923, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 3, "selected": false, "text": "Pragma: no-cache\nCache-Control: no-cache\nExpires: Fri, 30 Oct 1998 14:19:41 GMT\n" }, { "answer_id": 244931, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 5, "selected": true, "text": " xmlHttp.open(\"GET\",\"blurb.php?\"+Math.random();\n" }, { "answer_id": 245339, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 2, "selected": false, "text": "open var xmlHttp = new XMLHttpRequest();\n" }, { "answer_id": 744933, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 1, "selected": false, "text": "Expires: -1 Cache-Control: no-cache Pragma: no-cache" }, { "answer_id": 13214083, "author": "Alfredo Carrillo", "author_id": 332819, "author_profile": "https://Stackoverflow.com/users/332819", "pm_score": 0, "selected": false, "text": "dojo.date.stamp \"...&amp;ts=\" + dojo.date.stamp.toISOString(new Date())\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23335/" ]
244,926
<p>I'm using a the TreeView control and it scrolls automatically to left-align TreeViewItem when one of them is clicked. I've gone looking at my Styles and ControlTemplates, but I haven't found anything. Is there a default ControlTemplate that causes this? I want to disable it.</p>
[ { "answer_id": 246610, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": " using (Stream sw = File.Open(@\"C:\\TreeViewDefaults.xaml\", FileMode.Truncate, FileAccess.Write))\n {\n Style ts = Application.Current.FindResource(typeof(TreeView)) as Style;\n if (ts != null)\n XamlWriter.Save(ts, sw);\n }\n <Style TargetType=\"TreeView\" \n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:s=\"clr-namespace:System;assembly=mscorlib\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Style.Triggers>\n <Trigger Property=\"VirtualizingStackPanel.IsVirtualizing\">\n <Setter Property=\"ItemsControl.ItemsPanel\">\n <Setter.Value>\n <ItemsPanelTemplate><VirtualizingStackPanel IsItemsHost=\"True\" /></ItemsPanelTemplate>\n </Setter.Value>\n </Setter>\n <Trigger.Value>\n <s:Boolean>True</s:Boolean>\n </Trigger.Value>\n </Trigger>\n </Style.Triggers>\n <Style.Resources>\n <ResourceDictionary />\n </Style.Resources>\n <Setter Property=\"Panel.Background\">\n <Setter.Value><DynamicResource ResourceKey=\"{x:Static SystemColors.WindowBrushKey}\" /></Setter.Value>\n </Setter>\n <Setter Property=\"Border.BorderBrush\">\n <Setter.Value><SolidColorBrush>#FF828790</SolidColorBrush></Setter.Value>\n </Setter>\n <Setter Property=\"Border.BorderThickness\">\n <Setter.Value><Thickness>1,1,1,1</Thickness></Setter.Value>\n </Setter>\n <Setter Property=\"Control.Padding\">\n <Setter.Value><Thickness>1,1,1,1</Thickness></Setter.Value>\n </Setter>\n <Setter Property=\"TextElement.Foreground\">\n <Setter.Value><DynamicResource ResourceKey=\"{x:Static SystemColors.ControlTextBrushKey}\" /></Setter.Value>\n </Setter>\n <Setter Property=\"ScrollViewer.HorizontalScrollBarVisibility\">\n <Setter.Value><x:Static Member=\"ScrollBarVisibility.Auto\" /></Setter.Value>\n </Setter>\n <Setter Property=\"ScrollViewer.VerticalScrollBarVisibility\">\n <Setter.Value><x:Static Member=\"ScrollBarVisibility.Auto\" /></Setter.Value>\n </Setter>\n <Setter Property=\"Control.VerticalContentAlignment\">\n <Setter.Value><x:Static Member=\"VerticalAlignment.Center\" /></Setter.Value>\n </Setter>\n <Setter Property=\"Control.Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"TreeView\">\n <Border BorderThickness=\"{TemplateBinding Border.BorderThickness}\" \n BorderBrush=\"{TemplateBinding Border.BorderBrush}\" \n Name=\"Bd\" SnapsToDevicePixels=\"True\">\n <ScrollViewer CanContentScroll=\"False\" \n HorizontalScrollBarVisibility=\"{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}\" \n VerticalScrollBarVisibility=\"{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}\" \n Background=\"{TemplateBinding Panel.Background}\" \n Padding=\"{TemplateBinding Control.Padding}\" \n Name=\"_tv_scrollviewer_\" \n SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\" \n Focusable=\"False\">\n <ItemsPresenter />\n </ScrollViewer>\n </Border>\n <ControlTemplate.Triggers>\n <Trigger Property=\"UIElement.IsEnabled\">\n <Setter Property=\"Panel.Background\" TargetName=\"Bd\">\n <Setter.Value>\n <DynamicResource ResourceKey=\"{x:Static SystemColors.ControlBrushKey}\" />\n </Setter.Value>\n </Setter>\n <Trigger.Value>\n <s:Boolean>False</s:Boolean>\n </Trigger.Value>\n </Trigger>\n <Trigger Property=\"VirtualizingStackPanel.IsVirtualizing\">\n <Setter Property=\"ScrollViewer.CanContentScroll\" TargetName=\"_tv_scrollviewer_\">\n <Setter.Value><s:Boolean>True</s:Boolean></Setter.Value>\n </Setter>\n <Trigger.Value>\n <s:Boolean>True</s:Boolean>\n </Trigger.Value>\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n" }, { "answer_id": 260409, "author": "brian sharon", "author_id": 16935, "author_profile": "https://Stackoverflow.com/users/16935", "pm_score": 4, "selected": true, "text": "public class NoScrollTreeView : TreeView\n{\n public class NoScrollTreeViewItem : TreeViewItem\n {\n public NoScrollTreeViewItem() : base()\n {\n this.RequestBringIntoView += delegate (object sender, RequestBringIntoViewEventArgs e) {\n e.Handled = true;\n };\n }\n\n protected override DependencyObject GetContainerForItemOverride()\n {\n return new NoScrollTreeViewItem();\n }\n }\n protected override DependencyObject GetContainerForItemOverride()\n {\n return new NoScrollTreeViewItem();\n }\n}\n" }, { "answer_id": 976339, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "yourtreeview.SelectedItem = yourtreeviewitem\n <Style x:Key=\"{x:Type TreeView}\" TargetType=\"TreeView\">\n <Setter Property=\"OverridesDefaultStyle\" Value=\"True\" />\n <Setter Property=\"SnapsToDevicePixels\" Value=\"True\" />\n <Setter Property=\"ScrollViewer.HorizontalScrollBarVisibility\" Value=\"Auto\"/>\n <Setter Property=\"ScrollViewer.VerticalScrollBarVisibility\" Value=\"Auto\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"TreeView\">\n <Border Name=\"Border\" BorderThickness=\"0\" Padding=\"0\" Margin=\"1\">\n <ScrollViewer Focusable=\"False\" CanContentScroll=\"False\" Padding=\"0\">\n <Components:AutoScrollPreventer Margin=\"0\">\n <ItemsPresenter/>\n </Components:AutoScrollPreventer>\n </ScrollViewer>\n </Border>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n using System;\nusing System.Windows;\nusing System.Windows.Controls;\n\nnamespace LiveContext.Designer.GUI.Components {\n public class AutoScrollPreventer : StackPanel\n {\n public AutoScrollPreventer() {\n\n this.RequestBringIntoView += delegate(object sender, RequestBringIntoViewEventArgs e)\n {\n // stop this event from bubbling so that a scrollviewer doesn't try to BringIntoView..\n e.Handled = true;\n };\n\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
244,934
<p>I'd like to create a table which has an integer primary key limited between 000 and 999. Is there any way to enforce this 3 digit limit within the sql?</p> <p>I'm using sqlite3. Thanks.</p>
[ { "answer_id": 244982, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "CHECK CREATE TABLE mytable (\n mytable_id INT PRIMARY KEY CHECK (mytable_id BETWEEN 0 and 999)\n);\n INSERT UPDATE CREATE TRIGGER mytable_pk_enforcement\nBEFORE INSERT ON mytable\nFOR EACH ROW \n WHEN mytable_id NOT BETWEEN 0 AND 999\nBEGIN\n RAISE(ABORT, 'primary key out of range');\nEND\n AFTER INSERT BEFORE UPDATE CHECK" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20883/" ]
244,935
<p>How can I inject the value of an appSettings entry (from app.config or web.config) into a service using the Windsor container? If I wanted to inject the value of a Windsor property into a service, I would do something like this:</p> <pre><code>&lt;properties&gt; &lt;importantIntegerProperty&gt;666&lt;/importantIntegerProperty&gt; &lt;/properties&gt; &lt;component id="myComponent" service="MyApp.IService, MyApp" type="MyApp.Service, MyApp" &gt; &lt;parameters&gt; &lt;importantInteger&gt;#{importantIntegerProperty}&lt;/importantInteger&gt; &lt;/parameters&gt; &lt;/component&gt; </code></pre> <p>However, what I'd really like to do is take the value represented by <code>#{importantIntegerProperty}</code> from an app settings variable which might be defined like this:</p> <pre><code>&lt;appSettings&gt; &lt;add key="importantInteger" value="666"/&gt; &lt;/appSettings&gt; </code></pre> <p><strong>EDIT:</strong> To clarify; I realise that this is not natively possible with Windsor and the <a href="http://davidhayden.com/blog/dave/archive/2007/10/04/DependencyInjectionParametersPropertiesCastleWindsor.aspx" rel="nofollow noreferrer">David Hayden article</a> that <a href="https://stackoverflow.com/users/31385/sliderhouserules">sliderhouserules</a> refers to is actually about his own (David Hayden's) IoC container, not Windsor.</p> <p>I'm surely not the first person to have this problem so what I'd like to know is how have other people solved this issue?</p>
[ { "answer_id": 2659265, "author": "Damian Powell", "author_id": 30321, "author_profile": "https://Stackoverflow.com/users/30321", "pm_score": 4, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <appSettings>\n <add key=\"theAnswer\" value=\"42\"/>\n </appSettings>\n</configuration>\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<castle>\n <components>\n <component\n id=\"answerProvider\"\n service=\"Acme.IAnswerProvider, Acme\"\n type=\"Acme.AnswerProvider, Acme\"\n >\n <parameters>\n <theAnswer>#{AppSetting.theAnswer}</theAnswer>\n </parameters>\n </component>\n </components>\n</castle>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30321/" ]
244,941
<p>What is the best way to go about monitoring a folder to see when an image file has been added to it? Files are added approximately once a minute and the naming goes like this... image0001.jpg, image0002.jpg, image0003.jpg etc. I need to know when a file has been written to the folder so that my app can access and use it.</p>
[ { "answer_id": 14915777, "author": "Tanvir", "author_id": 2246679, "author_profile": "https://Stackoverflow.com/users/2246679", "pm_score": 1, "selected": false, "text": "List<string> files = new List<string>();\nstring path = @\"C:\\test\\\"; // whatever the path is\n\npublic List<string> GetNewFiles(string path)\n {\n // store all the filenames (only .jpg files) in a list\n List<string> currentFiles = System.IO.Directory.GetFiles(path, \"*.jpg\");\n\n if ( currentFiles.Count() > files.Count() )\n {\n count = newFiles.Length - files.Length;\n List<string> newFiles = new List<string>();\n\n foreach ( string file in currentFiles )\n {\n if ( !files.Contains(file) )\n {\n newFiles.Add(file);\n }\n }\n }\n files = currentFiles;\n return newFiles;\n }\n public void MonitorFolder()\n{\n while (true)\n {\n List<string> newFiles = GetNewFiles(path);\n System.Threading.Thread.Sleep(5000); // 5000 milliseconds\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
244,952
<p>I am creating a small web page using PHP that will be accessed as an IFRAME from a couple of sites. I'm wanting to restrict access to this site to work ONLY within the "approved" sites, and not other sites or accessed directly. Does anyone have any suggestions? Is this even possible? The PHP site will be Apache, and the sites iframing the content will probably be .NET.</p> <p>Just to clarify, any site can view the page, as long as it's iframe'd within an approved site. I want to block people from accessing it directly. I'm thinking cookies might be a solution, but I'm not sure.</p>
[ { "answer_id": 244956, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 1, "selected": false, "text": "if (top.location != location) {\n top.location.href = document.location.href ;\n}\n" }, { "answer_id": 245003, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "$_SERVER['HTTP_REFERER'] if (strpos('http://example.com', $_SERVER['HTTP_REFERER']) !== false) {\n // allowed\n}\n in_array()" }, { "answer_id": 245008, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": " <iframe src=\"http://yourdomain/frame.php?key=p21n9u234p8yfb8yfy234m3lunflb8hv\" />\n" }, { "answer_id": 245017, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\"><!--\nmyiframe_client = \"12345\";\nmyiframe_width = 728;\nmyiframe_height = 90;\n//-->\n</script>\n<script type=\"text/javascript\"\nsrc=\"http://www.example.com/scripts/show_iframe.js\">\n</script>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31319/" ]
244,953
<p>I have a class with a nullable int? datatype set to serialize as an xml element. Is there any way to set it up so the xml serializer will not serialize the element if the value is null? </p> <p>I've tried to add the [System.Xml.Serialization.XmlElement(IsNullable=false)] attribute, but I get a runtime serialization exception saying there was a an error reflecting the type, because "IsNullable may not be set to 'false' for a Nullable type. Consider using 'System.Int32' type or removing the IsNullable property from the XmlElement attribute."</p> <pre><code>[Serializable] [System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")] public class Score { private int? iID_m; ... /// &lt;summary&gt; /// /// &lt;/summary&gt; public int? ID { get { return iID_m; } set { iID_m = value; } } ... } </code></pre> <p>The above class will serialize to:</p> <pre><code>&lt;Score xmlns="http://mycomp.com/test/score/v1"&gt; &lt;ID xsi:nil="true" /&gt; &lt;/Score&gt; </code></pre> <p>But for IDs that are null I don't want the ID element at all, primarily because when I use OPENXML in MSSQL, it returns a 0 instead of null for an element that looks like </p>
[ { "answer_id": 245028, "author": "Jeremy", "author_id": 9266, "author_profile": "https://Stackoverflow.com/users/9266", "pm_score": 4, "selected": false, "text": " /// <summary>\n /// Score db record\n /// </summary> \n [System.Xml.Serialization.XmlIgnore()]\n public int? ID \n { \n get \n { \n return iID_m; \n } \n set \n { \n iID_m = value; \n } \n }\n\n /// <summary>\n /// Score db record\n /// </summary> \n [System.Xml.Serialization.XmlElement(\"ID\",IsNullable = false)]\n public object IDValue\n {\n get\n {\n return ID;\n }\n set\n {\n if (value == null)\n {\n ID = null;\n }\n else if (value is int || value is int?)\n {\n ID = (int)value;\n }\n else\n {\n ID = int.Parse(value.ToString());\n }\n }\n }\n" }, { "answer_id": 246359, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "ShouldSerialize{Foo}() public bool ShouldSerializeID() {return ID.HasValue;}\n {Foo}Specified" }, { "answer_id": 279588, "author": "scobi", "author_id": 14582, "author_profile": "https://Stackoverflow.com/users/14582", "pm_score": 3, "selected": false, "text": "public class Nullable<T>\n{\n public Nullable(T value)\n {\n _value = value;\n _hasValue = true;\n }\n\n public Nullable()\n {\n _hasValue = false;\n }\n\n [XmlText]\n public T Value\n {\n get\n {\n if (!HasValue)\n throw new InvalidOperationException();\n return _value;\n }\n set\n {\n _value = value;\n _hasValue = true;\n }\n }\n\n [XmlIgnore]\n public bool HasValue\n { get { return _hasValue; } }\n\n public T GetValueOrDefault()\n { return _value; }\n public T GetValueOrDefault(T i_defaultValue)\n { return HasValue ? _value : i_defaultValue; }\n\n public static explicit operator T(Nullable<T> i_value)\n { return i_value.Value; }\n public static implicit operator Nullable<T>(T i_value)\n { return new Nullable<T>(i_value); }\n\n public override bool Equals(object i_other)\n {\n if (!HasValue)\n return (i_other == null);\n if (i_other == null)\n return false;\n return _value.Equals(i_other);\n }\n\n public override int GetHashCode()\n {\n if (!HasValue)\n return 0;\n return _value.GetHashCode();\n }\n\n public override string ToString()\n {\n if (!HasValue)\n return \"\";\n return _value.ToString();\n }\n\n bool _hasValue;\n T _value;\n}\n" }, { "answer_id": 610630, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 5, "selected": false, "text": "[XmlIgnore]\npublic double? SomeValue { get; set; }\n\n[XmlAttribute(\"SomeValue\")] // or [XmlElement(\"SomeValue\")]\n[EditorBrowsable(EditorBrowsableState.Never)]\npublic double XmlSomeValue { get { return SomeValue.Value; } set { SomeValue= value; } } \n[EditorBrowsable(EditorBrowsableState.Never)]\npublic bool XmlSomeValueSpecified { get { return SomeValue.HasValue; } }\n" }, { "answer_id": 3989153, "author": "James Close", "author_id": 470183, "author_profile": "https://Stackoverflow.com/users/470183", "pm_score": 1, "selected": false, "text": " '----------------------------------------------------------------------------\n ' GetSchema\n '----------------------------------------------------------------------------\n Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema\n Return Nothing\n End Function\n\n '----------------------------------------------------------------------------\n ' ReadXml\n '----------------------------------------------------------------------------\n Public Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements System.Xml.Serialization.IXmlSerializable.ReadXml\n If (Not reader.IsEmptyElement) Then\n If (reader.Read AndAlso reader.NodeType = System.Xml.XmlNodeType.Text) Then\n Me._value = reader.ReadContentAs(GetType(T), Nothing)\n End If\n End If\n End Sub\n\n '----------------------------------------------------------------------------\n ' WriteXml\n '----------------------------------------------------------------------------\n Public Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements System.Xml.Serialization.IXmlSerializable.WriteXml\n If (_hasValue) Then\n writer.WriteValue(Me.Value)\n End If\n End Sub\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
244,959
<p>Suppose I have the following two strings containing regular expressions. How do I coalesce them? More specifically, I want to have the two expressions as alternatives.</p> <pre><code>$a = '# /[a-z] #i'; $b = '/ Moo /x'; $c = preg_magic_coalesce('|', $a, $b); // Desired result should be equivalent to: // '/ \/[a-zA-Z] |Moo/' </code></pre> <p>Of course, doing this as string operations isn't practical because it would involve parsing the expressions, constructing syntax trees, coalescing the trees and then outputting another regular expression equivalent to the tree. I'm completely happy without this last step. Unfortunately, PHP doesn't have a RegExp class (or does it?).</p> <p>Is there <em>any</em> way to achieve this? Incidentally, does any other language offer a way? Isn't this a pretty normal scenario? Guess not. :-(</p> <p><strong>Alternatively</strong>, is there a way to check <strong>efficiently</strong> if either of the two expressions matches, and which one matches earlier (and if they match at the same position, which match is longer)? This is what I'm doing at the moment. Unfortunately, I do this on long strings, very often, for more than two patterns. The result is <em>slow</em> (and yes, this is definitely the bottleneck).</p> <h2>EDIT:</h2> <p>I should have been more specific – sorry. <code>$a</code> and <code>$b</code> are <em>variables</em>, their content is outside of my control! Otherwise, I would just coalesce them manually. Therefore, I can't make any assumptions about the delimiters or regex modifiers used. Notice, for example, that my first expression uses the <code>i</code> modifier (ignore casing) while the second uses <code>x</code> (extended syntax). Therefore, I can't just concatenate the two because the second expression does <em>not</em> ignore casing and the first doesn't use the extended syntax (and any whitespace therein is significant!</p>
[ { "answer_id": 244991, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 0, "selected": false, "text": "function preg_magic_coalasce($split, $re1, $re2) {\n $re1 = rtrim($re1, \"\\/#is\");\n $re2 = ltrim($re2, \"\\/#\");\n return $re1.$split.$re2;\n}\n" }, { "answer_id": 245097, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": "$a = '# /[a-z] #i';\n$b = '/ Moo /x';\n\n$a_matched = preg_match($a, $text, $a_matches);\n$b_matched = preg_match($b, $text, $b_matches);\n\nif ($a_matched && $b_matched) {\n $a_pos = strpos($text, $a_matches[1]);\n $b_pos = strpos($text, $b_matches[1]);\n\n if ($a_pos == $b_pos) {\n if (strlen($a_matches[1]) == strlen($b_matches[1])) {\n // $a and $b matched the exact same string\n } else if (strlen($a_matches[1]) > strlen($b_matches[1])) {\n // $a and $b started matching at the same spot but $a is longer\n } else {\n // $a and $b started matching at the same spot but $b is longer\n }\n } else if ($a_pos < $b_pos) {\n // $a matched first\n } else {\n // $b matched first\n }\n} else if ($a_matched) {\n // $a matched, $b didn't\n} else if ($b_matched) {\n // $b matched, $a didn't\n} else {\n // neither one matched\n}\n" }, { "answer_id": 245326, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "/^(.)(.*)\\1([imsxeADSUXJu]*)$/\n \"(?$flags1:$regexp1)|(?$flags2:$regexp2)\"\n /(.)x\\1/ /(.)y\\1/ /(.)x\\1|(.)y\\2/" }, { "answer_id": 245661, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": true, "text": ". // Pass as many expressions as you'd like\nfunction preg_magic_coalesce() {\n $active_modifiers = array();\n\n $expression = '/(?:';\n $sub_expressions = array();\n foreach(func_get_args() as $arg) {\n // Determine modifiers from sub-expression\n if(preg_match('/^(.)(.*)\\1([eimsuxADJSUX]+)$/', $arg, $matches)) {\n $modifiers = preg_split('//', $matches[3]);\n if($modifiers[0] == '') {\n array_shift($modifiers);\n }\n if($modifiers[(count($modifiers) - 1)] == '') {\n array_pop($modifiers);\n }\n\n $cancel_modifiers = $active_modifiers;\n foreach($cancel_modifiers as $key => $modifier) {\n if(in_array($modifier, $modifiers)) {\n unset($cancel_modifiers[$key]);\n }\n }\n $active_modifiers = $modifiers;\n } elseif(preg_match('/(.)(.*)\\1$/', $arg)) {\n $cancel_modifiers = $active_modifiers;\n $active_modifiers = array();\n }\n\n // If expression has modifiers, include them in sub-expression\n $sub_modifier = '(?';\n $sub_modifier .= implode('', $active_modifiers);\n\n // Cancel modifiers from preceding sub-expression\n if(count($cancel_modifiers) > 0) {\n $sub_modifier .= '-' . implode('-', $cancel_modifiers);\n }\n\n $sub_modifier .= ')';\n\n $sub_expression = preg_replace('/^(.)(.*)\\1[eimsuxADJSUX]*$/', $sub_modifier . '$2', $arg);\n\n // Properly escape slashes\n $sub_expression = preg_replace('/(?<!\\\\\\)\\//', '\\\\\\/', $sub_expression);\n\n $sub_expressions[] = $sub_expression;\n }\n\n // Join expressions\n $expression .= implode('|', $sub_expressions);\n\n $expression .= ')/';\n return $expression;\n}\n function preg_magic_coalesce($expressions = array(), $global_modifier = '') {\n if(!preg_match('/^((?:-?[eimsuxADJSUX])+)$/', $global_modifier)) {\n $global_modifier = '';\n }\n\n $expression = '/(?:';\n $sub_expressions = array();\n foreach($expressions as $sub_expression) {\n $active_modifiers = array();\n // Determine modifiers from sub-expression\n if(preg_match('/^(.)(.*)\\1((?:-?[eimsuxADJSUX])+)$/', $sub_expression, $matches)) {\n $active_modifiers = preg_split('/(-?[eimsuxADJSUX])/',\n $matches[3], -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);\n }\n\n // If expression has modifiers, include them in sub-expression\n if(count($active_modifiers) > 0) {\n $replacement = '(?';\n $replacement .= implode('', $active_modifiers);\n $replacement .= ':$2)';\n } else {\n $replacement = '$2';\n }\n\n $sub_expression = preg_replace('/^(.)(.*)\\1(?:(?:-?[eimsuxADJSUX])*)$/',\n $replacement, $sub_expression);\n\n // Properly escape slashes if another delimiter was used\n $sub_expression = preg_replace('/(?<!\\\\\\)\\//', '\\\\\\/', $sub_expression);\n\n $sub_expressions[] = $sub_expression;\n }\n\n // Join expressions\n $expression .= implode('|', $sub_expressions);\n\n $expression .= ')/' . $global_modifier;\n return $expression;\n}\n (?modifiers:sub-expression) (?modifiers)sub-expression|(?cancel-modifiers)sub-expression /u 'u'" }, { "answer_id": 248361, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "preg_split create_function /**\n * Merges several regular expressions into one, using the indicated 'glue'.\n *\n * This function takes care of individual modifiers so it's safe to use\n * <em>different</em> modifiers on the individual expressions. The order of\n * sub-matches is preserved as well. Numbered back-references are adapted to\n * the new overall sub-match count. This means that it's safe to use numbered\n * back-refences in the individual expressions!\n * If {@link $names} is given, the individual expressions are captured in\n * named sub-matches using the contents of that array as names.\n * Matching pair-delimiters (e.g. <code>\"{…}\"</code>) are currently\n * <strong>not</strong> supported.\n *\n * The function assumes that all regular expressions are well-formed.\n * Behaviour is undefined if they aren't.\n *\n * This function was created after a {@link https://stackoverflow.com/questions/244959/\n * StackOverflow discussion}. Much of it was written or thought of by\n * “porneL” and “eyelidlessness”. Many thanks to both of them.\n *\n * @param string $glue A string to insert between the individual expressions.\n * This should usually be either the empty string, indicating\n * concatenation, or the pipe (<code>|</code>), indicating alternation.\n * Notice that this string might have to be escaped since it is treated\n * like a normal character in a regular expression (i.e. <code>/</code>)\n * will end the expression and result in an invalid output.\n * @param array $expressions The expressions to merge. The expressions may\n * have arbitrary different delimiters and modifiers.\n * @param array $names Optional. This is either an empty array or an array of\n * strings of the same length as {@link $expressions}. In that case,\n * the strings of this array are used to create named sub-matches for the\n * expressions.\n * @return string An string representing a regular expression equivalent to the\n * merged expressions. Returns <code>FALSE</code> if an error occurred.\n */\nfunction preg_merge($glue, array $expressions, array $names = array()) {\n // … then, a miracle occurs.\n\n // Sanity check …\n\n $use_names = ($names !== null and count($names) !== 0);\n\n if (\n $use_names and count($names) !== count($expressions) or\n !is_string($glue)\n )\n return false;\n\n $result = array();\n // For keeping track of the names for sub-matches.\n $names_count = 0;\n // For keeping track of *all* captures to re-adjust backreferences.\n $capture_count = 0;\n\n foreach ($expressions as $expression) {\n if ($use_names)\n $name = str_replace(' ', '_', $names[$names_count++]);\n\n // Get delimiters and modifiers:\n\n $stripped = preg_strip($expression);\n\n if ($stripped === false)\n return false;\n\n list($sub_expr, $modifiers) = $stripped;\n\n // Re-adjust backreferences:\n\n // We assume that the expression is correct and therefore don't check\n // for matching parentheses.\n\n $number_of_captures = preg_match_all('/\\([^?]|\\(\\?[^:]/', $sub_expr, $_);\n\n if ($number_of_captures === false)\n return false;\n\n if ($number_of_captures > 0) {\n // NB: This looks NP-hard. Consider replacing.\n $backref_expr = '/\n ( # Only match when not escaped:\n [^\\\\\\\\] # guarantee an even number of backslashes\n (\\\\\\\\*?)\\\\2 # (twice n, preceded by something else).\n )\n \\\\\\\\ (\\d) # Backslash followed by a digit.\n /x';\n $sub_expr = preg_replace_callback(\n $backref_expr,\n create_function(\n '$m',\n 'return $m[1] . \"\\\\\\\\\" . ((int)$m[3] + ' . $capture_count . ');'\n ),\n $sub_expr\n );\n $capture_count += $number_of_captures;\n }\n\n // Last, construct the new sub-match:\n\n $modifiers = implode('', $modifiers);\n $sub_modifiers = \"(?$modifiers)\";\n if ($sub_modifiers === '(?)')\n $sub_modifiers = '';\n\n $sub_name = $use_names ? \"?<$name>\" : '?:';\n $new_expr = \"($sub_name$sub_modifiers$sub_expr)\";\n $result[] = $new_expr;\n }\n\n return '/' . implode($glue, $result) . '/';\n}\n\n/**\n * Strips a regular expression string off its delimiters and modifiers.\n * Additionally, normalize the delimiters (i.e. reformat the pattern so that\n * it could have used '/' as delimiter).\n *\n * @param string $expression The regular expression string to strip.\n * @return array An array whose first entry is the expression itself, the\n * second an array of delimiters. If the argument is not a valid regular\n * expression, returns <code>FALSE</code>.\n *\n */\nfunction preg_strip($expression) {\n if (preg_match('/^(.)(.*)\\\\1([imsxeADSUXJu]*)$/s', $expression, $matches) !== 1)\n return false;\n\n $delim = $matches[1];\n $sub_expr = $matches[2];\n if ($delim !== '/') {\n // Replace occurrences by the escaped delimiter by its unescaped\n // version and escape new delimiter.\n $sub_expr = str_replace(\"\\\\$delim\", $delim, $sub_expr);\n $sub_expr = str_replace('/', '\\\\/', $sub_expr);\n }\n $modifiers = $matches[3] === '' ? array() : str_split(trim($matches[3]));\n\n return array($sub_expr, $modifiers);\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968/" ]
245,012
<p>By default Windows (XP) shows the <strong>underlined hotkeys</strong> only, when ALT is pressed. This can be changed in display-properties in the subdialog "Effects" so, that the hotkeys are <strong>always underlined</strong></p> <p>How can it be changed programmatically? Which API-call or registry-setting can be used to change this setting?</p>
[ { "answer_id": 452379, "author": "Christof Schardt", "author_id": 26820, "author_profile": "https://Stackoverflow.com/users/26820", "pm_score": 3, "selected": true, "text": "BOOL b\nSystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &b, 0);\nif (!b) {\n b = TRUE;\n SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, &b, 0);\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26820/" ]
245,019
<p>Has anybody else had trouble with getting the .Net Framework source code? Google doesn't have anything to say about this error message, and neither does the CodePlex issue tracker.</p> <p>Here is the command I'm using to get the source code for the modules that make up mscorlib.dll. Am I doing something obviously wrong?</p> <p>NetMassDownloader.exe -o source -f "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll"</p>
[ { "answer_id": 452379, "author": "Christof Schardt", "author_id": 26820, "author_profile": "https://Stackoverflow.com/users/26820", "pm_score": 3, "selected": true, "text": "BOOL b\nSystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &b, 0);\nif (!b) {\n b = TRUE;\n SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, &b, 0);\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31205/" ]
245,027
<p>...I want to Show the 'delete' button when user is an admin, and show the 'add item' button when user is a contributor:</p> <pre><code>&lt;!-- More code above --&gt; &lt;asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /&gt; &lt;asp:TemplateField ShowHeader="False"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton CSSClass="TableRightLink" ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Visible=&lt;%# User.IsInRole(@"DOMAIN\CMDB_ADMIN") %&gt; Text="Delete" OnClientClick="return confirm('Are you certain you want to delete this item?');"&gt;&lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;SelectedRowStyle VerticalAlign="Top" /&gt; &lt;HeaderStyle ForeColor="White" CssClass="TableHeader" BackColor="SteelBlue" /&gt; &lt;/asp:GridView&gt; &lt;asp:table width="100%" runat="server" CSSclass="PromptTable" Visible=&lt;%# User.IsInRole(@"DOMAIN\CMDB_CONTRIBUTE") %&gt; &gt; &lt;asp:tablerow&gt;&lt;asp:tablecell HorizontalAlign=Center&gt; &lt;asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="AddConfigItem.aspx" ForeColor="LightCyan"&gt;Add Item&lt;/asp:HyperLink&gt; &lt;/asp:tablecell&gt;&lt;/asp:tablerow&gt;&lt;/asp:table&gt; </code></pre> <p>The Delete button 'visible' attribute works fine. But, the "add item' hyperlink doesn't. It always shows. View-source tells me that %# User.IsInRole(@"DOMAIN\CMDB_CONTRIBUTE") %> isn't evaluating to anything. Any idea why this is?</p>
[ { "answer_id": 245032, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "Visible='<%= User.IsInRole(@\"DOMAIN\\CMDB_CONTRIBUTE\") %>'\n" }, { "answer_id": 245268, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "promptTable.Visible = User.IsInRole(@\"DOMAIN\\CMDB_CONTRIBUTE\");\n <%# %> <%= %>" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13959/" ]
245,045
<p>I'm looking for a way to add a close button to a .NET ToolTip object similar to the one the NotifyIcon has. I'm using the tooltip as a message balloon called programatically with the Show() method. That works fine but there is no onclick event or easy way to close the tooltip. You have to call the Hide() method somewhere else in your code and I would rather have the tooltip be able to close itself. I know there are several balloon tooltips around the net that use manage and unmanaged code to perform this with the windows API, but I would rather stay in my comfy .NET world. I have a thrid party application that calls my .NET application and it has crashes when trying to display unmanaged tooltips.</p>
[ { "answer_id": 245128, "author": "avgbody", "author_id": 8737, "author_profile": "https://Stackoverflow.com/users/8737", "pm_score": 3, "selected": true, "text": " 1 class MyToolTip : ToolTip\n 2 {\n 3 public MyToolTip()\n 4 {\n 5 this.OwnerDraw = true;\n 6 this.Draw += new DrawToolTipEventHandler(OnDraw);\n 7 \n 8 }\n 9 \n 10 public MyToolTip(System.ComponentModel.IContainer Cont)\n 11 {\n 12 this.OwnerDraw = true;\n 13 this.Draw += new DrawToolTipEventHandler(OnDraw);\n 14 }\n 15 \n 16 private void OnDraw(object sender, DrawToolTipEventArgs e)\n 17 {\n ...Code Stuff...\n 24 }\n 25 }\n" }, { "answer_id": 4972205, "author": "MMsoft", "author_id": 613432, "author_profile": "https://Stackoverflow.com/users/613432", "pm_score": 2, "selected": false, "text": " protected override CreateParams CreateParams\n {\n get\n {\n CreateParams cp = base.CreateParams;\n cp.Style = 0x80 | 0x40; //TTS_BALLOON & TTS_CLOSE\n\n return cp;\n }\n }\n" }, { "answer_id": 13805404, "author": "Joel Rein", "author_id": 20961, "author_profile": "https://Stackoverflow.com/users/20961", "pm_score": 2, "selected": false, "text": "private const int TTS_BALLOON = 0x80;\nprivate const int TTS_CLOSE = 0x40;\nprotected override CreateParams CreateParams\n{\n get\n {\n var cp = base.CreateParams;\n cp.Style = TTS_BALLOON | TTS_CLOSE;\n return cp;\n }\n}\n <dependency>\n <dependentAssembly>\n <assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.Windows.Common-Controls\"\n version=\"6.0.0.0\"\n processorArchitecture=\"*\"\n publicKeyToken=\"6595b64144ccf1df\"\n language=\"*\"\n />\n </dependentAssembly>\n</dependency> \n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13556/" ]
245,055
<p>So what I have right now is something like this:</p> <pre><code>PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public); </code></pre> <p>where <code>obj</code> is some object.</p> <p>The problem is some of the properties I want aren't in <code>obj.GetType()</code> they're in one of the base classes further up. If I stop the debugger and look at obj, the I have to dig through a few "base" entries to see the properties I want to get at. Is there some binding flag I can set to have it return those or do I have to recursively dig through the <code>Type.BaseType</code> hierarchy and do <code>GetProperties</code> on all of them?</p>
[ { "answer_id": 245105, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 3, "selected": false, "text": "Type.BaseType System.Object Type type = obj.GetType();\nPropertyInfo[] info = type.GetProperties(BindingFlags.Public);\nPropertyInfo[] baseProps = type.BaseType.GetProperties(BindingFlags.Public);\n" }, { "answer_id": 245119, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 6, "selected": true, "text": "PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);\n GetProperties() GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static ) BindingFlags.FlattenHierarchy" }, { "answer_id": 245131, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 4, "selected": false, "text": "BindingFlags class B\n {\n public int MyProperty { get; set; }\n }\n\n class C : B\n {\n public string MyProperty2 { get; set; }\n }\n\n static void Main(string[] args)\n {\n PropertyInfo[] info = new C().GetType().GetProperties();\n foreach (var pi in info)\n {\n Console.WriteLine(pi.Name);\n }\n }\n" }, { "answer_id": 245140, "author": "Nicolas Cadilhac", "author_id": 29244, "author_profile": "https://Stackoverflow.com/users/29244", "pm_score": 2, "selected": false, "text": "TypeDescriptor.GetProperties(obj);\n" }, { "answer_id": 245160, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "ComponentModel DataView DataRowView foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))\n {\n Console.WriteLine(\"{0}={1}\", prop.Name, prop.GetValue(obj));\n }\n Delegate.CreateDelegate TypeDescriptor TypeDescriptionProvider" }, { "answer_id": 72461513, "author": "Luc Bloom", "author_id": 1783320, "author_profile": "https://Stackoverflow.com/users/1783320", "pm_score": 0, "selected": false, "text": "public static IEnumerable<PropertyInfo> GetProperties(Type type, bool forGetter)\n{\n // Loop over public and protected members\n foreach (var item in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))\n {\n yield return item;\n }\n\n // Get first base type\n type = type.BaseType;\n\n // Find their \"private\" memebers\n while (type != null && type != typeof(object))\n {\n // Loop over non-public members\n foreach (var item in type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))\n {\n // Make sure it's private!\n // To prevent doubleing up on protected members\n var methodInfo = forGetter ? item.GetGetMethod(true) : item.GetSetMethod(true);\n if (methodInfo != null && methodInfo.IsPrivate)\n {\n yield return item;\n }\n }\n\n // Get next base type.\n type = type.BaseType;\n }\n}\n public static IEnumerable<FieldInfo> GetFields(Type type)\n{\n // Loop over public and protected members\n foreach (var item in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))\n {\n yield return item;\n }\n\n // Get first base type\n type = type.BaseType;\n\n // Find their \"private\" memebers\n while (type != null && type != typeof(object))\n {\n // Loop over non-public members\n foreach (var item in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic))\n {\n // Make sure it's private!\n // To prevent doubleing up on protected members\n if (item.IsPrivate)\n {\n yield return item;\n }\n }\n\n // Get next base type.\n type = type.BaseType;\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
245,058
<p>Lately I've been using XPathDocument and XNavigator to parse an XML file for a given XPath and attribute. It's been working very well, when I know in advance what the XPath is. </p> <p>Sometimes though, the XPath will be one of several possible XPath values, and I'd like to be able to test whether or not a given XPath exists. </p> <p>In case I'm getting the nomenclature wrong, here's what I'm calling an XPath - given this XML blob:</p> <pre><code>&lt;foo&gt; &lt;bar baz="This is the value of the attribute named baz"&gt; &lt;/foo&gt; </code></pre> <p>I might be looking for what I'm calling an XPath of "//foo/bar" and then reading the attribute "baz" to get the value. </p> <p>Example of the code that I use to do this: </p> <pre><code>XPathDocument document = new XPathDocument(filename); XPathNavigator navigator = document.CreateNavigator(); XPathNavigator node = navigator.SelectSingleNode("//foo/bar"); if(node.HasAttributes) { Console.WriteLine(node.GetAttribute("baz", string.Empty)); } </code></pre> <p>Now, if the call to navigator.SelectSingleNode fails, it will return a NullReferenceException or an XPathException. I can catch both of those and refactor the above into a test to see whether or not a given XPath returns an exception, but I was wondering whether there was a better way? </p> <p>I didn't see anything obvious in the Intellisense. XPathNavigator has .HasAttributes and .HasChildren but short of iterating through the path one node at a time, I don't see anything nicer to use. </p>
[ { "answer_id": 245077, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "SelectSingleNode NullReferenceException SelectSingleNode XPathException" }, { "answer_id": 245085, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "XDocument doc = XDocument.Load(\"foo.xml\");\n\nvar att = from a in doc.Descendants(\"bar\")\n select a.Attribute(\"baz\")\n\nforeach (var item in att) {\n if (item != null) { ... }\n}\n" }, { "answer_id": 245091, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "node == null node.HasAttributes NullReferenceException //foo/bar" }, { "answer_id": 245112, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "var node = XDocument.Load(filename)\n .Descendants(\"bar\")\n .SingleOrDefault(e=>e.Attribute(\"baz\") != null);\n\nif (node != null) Console.WriteLine(node.Attribute(\"baz\").Value);\n" }, { "answer_id": 245123, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": " var baz = navigator.SelectSingleNode(\"//foo/bar/@baz\");\n if (baz != null) Console.WriteLine(baz);\n" }, { "answer_id": 245136, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " var doc = XDocument.Load(fileName);\n\n var results = from r in doc.XPathSelectElements(\"/foo/bar[count(@baz) > 0]\")\n select r.Attribute(\"baz\");\n\n foreach (String s in results)\n Console.WriteLine(s);\n" }, { "answer_id": 40181030, "author": "Ron", "author_id": 1903747, "author_profile": "https://Stackoverflow.com/users/1903747", "pm_score": 1, "selected": false, "text": "if (Convert.ToBoolean(navigator.Evaluate(@\"boolean(//foo/bar)\"))) {...}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5948/" ]
245,062
<p>What's the difference between JavaScript and Java?</p>
[ { "answer_id": 245069, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 8, "selected": false, "text": "this" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
245,082
<p>I'm making a shell script to find bigrams, which works, sort of.</p> <pre><code>#tokenise words tr -sc 'a-zA-z0-9.' '\012' &lt; $1 &gt; out1 #create 2nd list offset by 1 word tail -n+2 out1 &gt; out2 #paste list together paste out1 out2 #clean up rm out1 out2 </code></pre> <p>The only problem is that it pairs words from the end and start of the previous sentence.</p> <p>eg for the two sentences 'hello world.' and 'foo bar.' i'll get a line with ' world. foo'. Would it be possible to filter these out with grep or something?</p> <p>I know i can find all bigrams containing a full stop with grep [.] but that also finds the legitimate bigrams.</p>
[ { "answer_id": 245069, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 8, "selected": false, "text": "this" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
245,094
<p>I have a simple Google App Engine app, that I wrote using ordinary strings. I realize I want to make it handle unicode. Are there any gotchas with this? I'm thinking of all the strings that I currently already have in the live database. (From real users who I don't want to upset.)</p>
[ { "answer_id": 1515542, "author": "Robert", "author_id": 92584, "author_profile": "https://Stackoverflow.com/users/92584", "pm_score": 1, "selected": false, "text": "instance.xml = db.Text(xml_string, encoding=\"utf_8\") response = urllib.urlopen(url)\nxml = minidom.parse(response)\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8482/" ]
245,111
<p>Is it possible in .NET to ascertain whether my application is closing due to Windows being given a shutdown command (as opposed to any old application closing) in order to either write out some temporary cache files or even block the shutdown long enough to prompt for user input?</p> <p>Whilst my current scope involves a Winform app and a windows service, I am interested in understanding this in a generic way if possible</p>
[ { "answer_id": 245135, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "WM_QUERYENDSESSION" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
245,121
<p>I'm looking for a code library that converts ANSI escape sequences into HTML color, via plain tags or CSS. For example, something that would convert this:</p> <pre>ESC[00mESC[01;34mbinESC[00m ESC[01;34mcodeESC[00m ESC[01;31mdropbox-lnx.x86-0.6.404.tar.gzESC[00m ESC[00mfooESC[00m</pre> <p>Into this:</p> <pre><code>&lt;span style="color:blue"&gt;bin&lt;/span&gt; &lt;span style="color:blue"&gt;code&lt;/span&gt; &lt;span style="color:red"&gt;dropbox-lnx.x86-0.6.404.tar.gz&lt;/span&gt; foo </code></pre> <p>Converting breaks into &lt;br/&gt; isn't necessary, it's just the escape codes that I don't know. I could hack it together myself, but I'd probably miss something important like underlines or mess up how background colors work. I'd rather just sit on top of someone else's code.</p> <p>Does such a tool (command line linux) or library (perl, python, or ruby preferably) exist?</p>
[ { "answer_id": 2975843, "author": "Alexander Matthes", "author_id": 358638, "author_profile": "https://Stackoverflow.com/users/358638", "pm_score": 7, "selected": false, "text": "aha ls --color=always | aha > ls-output.htm\n ls --color=always | aha --black > ls-output.htm\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084/" ]
245,124
<p>I need to set the onload attribute for a newly popped-up window. The following code works for Firefox:</p> <pre><code>&lt;a onclick="printwindow=window.open('www.google.com');printwindow.document.body.onload=self.print();return false;" href='www.google.com'&gt; </code></pre> <p>However, when I try this in IE, I get an error - "printwindow.document.body null or not defined'</p> <p>The goal is to pop open a new window, and call up the print dialog for that window once it's been opened. </p> <p>Any clues on how to make this work? It is important not to use javascript elsewhere on the target page, as I do not have control over it. All functionality must be contained in the link I posted above.</p>
[ { "answer_id": 245214, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "printwindow.onload\n printwindow.onload=function(){self.print();}\n <a href=\"www.google.com\" onclick=\"var printwindow=window.open(this.href,'printwindow');printwindow.onload=function(){self.print();};return false;\" >try it</a>\n" }, { "answer_id": 245256, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 1, "selected": false, "text": "printwindow=window.open('/mypage.html');\nprintwindow.onload = function() {\n printwindow.focus();\n printwindow.print();\n}\n" }, { "answer_id": 247915, "author": "SocialCensus", "author_id": 26001, "author_profile": "https://Stackoverflow.com/users/26001", "pm_score": -1, "selected": false, "text": "<a onclick=\"self.printwindow=window.open('print.html');setTimeout('self.printwindow.print()',3000);return false;\" href='print.html'>\n" }, { "answer_id": 5493229, "author": "ace", "author_id": 439699, "author_profile": "https://Stackoverflow.com/users/439699", "pm_score": 2, "selected": false, "text": "printwindow = window.open('print.html');\nvar body;\nfunction ieLoaded(){\n body = printwindow.document.getElementsByTagName(\"body\");\n if(body[0]==null){\n // Page isn't ready yet!\n setTimeout(ieLoaded, 10);\n }else{\n // Here you can inject javascript if you like\n var n = printwindow.document.createElement(\"script\");\n n.src = \"injectableScript.js\";\n body.appendChild(n);\n\n // Or you can just call your script as originally planned\n printwindow.print();\n }\n}\nieLoaded();\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26001/" ]
245,149
<p>svn:externals can be great for sucking in central libraries or IP into a project, so that they can be kept in one location accessible for all.</p> <p>But if I'm asking people to external tags of common IP (so it doesn't change on them) it opens the possibility of them inadvertently committing changes to the tag. </p> <p>How can I make svn:externals read-only? It's acceptable if there is some extra argument or some way of making the external that we can add to the procedure for everyone to follow.</p>
[ { "answer_id": 4823387, "author": "icasimpan", "author_id": 579516, "author_profile": "https://Stackoverflow.com/users/579516", "pm_score": 1, "selected": false, "text": "[external_repo]\n@maintainer = rw\n@others = r\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26568/" ]
245,168
<p>How do I properly convert two columns from SQL (2008) using Linq into a <code>Dictionary</code> (for caching)?</p> <p>I currently loop through the <code>IQueryable</code> b/c I can't get the <code>ToDictionary</code> method to work. Any ideas? This works:</p> <pre><code>var query = from p in db.Table select p; Dictionary&lt;string, string&gt; dic = new Dictionary&lt;string, string&gt;(); foreach (var p in query) { dic.Add(sub.Key, sub.Value); } </code></pre> <p>What I'd really like to do is something like this, which doesn't seem to work:</p> <pre><code>var dic = (from p in db.Table select new {p.Key, p.Value }) .ToDictionary&lt;string, string&gt;(p =&gt; p.Key); </code></pre> <p>But I get this error:</p> <blockquote> <p>Cannot convert from 'System.Linq.IQueryable&lt;AnonymousType#1&gt;' to 'System.Collections.Generic.IEnumerable'</p> </blockquote>
[ { "answer_id": 245174, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 8, "selected": true, "text": "var dictionary = db\n .Table\n .Select(p => new { p.Key, p.Value })\n .AsEnumerable()\n .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)\n;\n" }, { "answer_id": 245187, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "var dic = (from p in db.Table\n select new {p.Key, p.Value })\n .ToDictionary(p => p.Key, p=> p.Value);\n" }, { "answer_id": 245216, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 3, "selected": false, "text": "var dic = db\n .Table\n .Select(p => new { p.Key, p.Value })\n .AsEnumerable()\n .ToDictionary(k=> k.Key, v => v.Value);\n" }, { "answer_id": 2088742, "author": "TWiStErRob", "author_id": 253468, "author_profile": "https://Stackoverflow.com/users/253468", "pm_score": 2, "selected": false, "text": "IDictionary<string, string> dic = db.Table.ToDictionary(row => row.Key, row => row.Value);" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ]
245,178
<p>I read some properties from an xml file, amongst which is a string that refers to an llblgen object for example 'article'. For now I have set up a rather long </p> <pre><code>Select Case myString Case "article" return New ArticleEntity() </code></pre> <p>Etc. which is getting rather ugly as it gets longer and longer ;). Is there a better way to do this ?</p> <p>(the above is vb.net, but c# examples are fine as well)</p>
[ { "answer_id": 245181, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "return Activator.CreateInstance(Type.GetType(\"Some.Type.String\"));\n Some.Type.String" }, { "answer_id": 245191, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": " Object obj = Activator.CreateInstance(\"AssemblyName\", \"TypeName\");\n List<object> list = new List<object>();\n\n\nforeach(string typename in GetFromXMLFile())\n{\n list.Add(Activator.CreateInstance(\"AssemblyName\", typename);\n}\n" }, { "answer_id": 245195, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "Activator.CreateInstance public static IMyTrait MakeMyTrait(Type t) {\n return Activator.CreateInstance<IMyTrait>(t);\n}\n" }, { "answer_id": 245287, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 3, "selected": true, "text": "Dictionary<string, Func<Animal>> _map = new Dictionary\n{\n (\"cat\", () => new Cat()),\n (\"dog\", () => new Dog())\n ...\n}\n return _map[myString]();\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31489/" ]
245,180
<p>I am writing a stored procedure where I have an input parameter called <em>my_size</em> that is an <em>INTEGER</em>. I want to be able to use it in a <code>LIMIT</code> clause in a <code>SELECT</code> statement. Apparently this is not supported, is there a way to work around this?</p> <pre><code># I want something like: SELECT * FROM some_table LIMIT my_size; # Instead of hardcoding a permanent limit: SELECT * FROM some_table LIMIT 100; </code></pre>
[ { "answer_id": 7051824, "author": "user888112", "author_id": 888112, "author_profile": "https://Stackoverflow.com/users/888112", "pm_score": 4, "selected": false, "text": "Declare rowCount int;\nSet rowCount = 100;\nSet SQL_SELECT_LIMIT = rowCount;\nSelect blah blah\nSet SQL_SELECT_LIMIT = Default;\n" }, { "answer_id": 10025538, "author": "Pradeep Sanjaya", "author_id": 529218, "author_profile": "https://Stackoverflow.com/users/529218", "pm_score": 4, "selected": false, "text": "DELIMITER $\nCREATE PROCEDURE get_users(page_from INT, page_size INT)\nBEGIN\n SET @_page_from = page_from;\n SET @_page_size = page_size;\n PREPARE stmt FROM \"select u.user_id, u.firstname, u.lastname from users u limit ?, ?;\";\n EXECUTE stmt USING @_page_from, @_page_size;\n DEALLOCATE PREPARE stmt;\nEND$\n\nDELIMITER ;\n call get_users(1, 10);\ncall get_users(11, 10);\n" }, { "answer_id": 14856587, "author": "Алексей Пузенко", "author_id": 1098030, "author_profile": "https://Stackoverflow.com/users/1098030", "pm_score": 2, "selected": false, "text": "CREATE PROCEDURE `some_func`(startIndex INT, countNum INT)\nREADS SQL DATA\n COMMENT 'example'\nBEGIN\n SET @asd = CONCAT('SELECT `id` FROM `table` LIMIT ',startIndex,',',countNum);\n PREPARE zxc FROM @asd;\n EXECUTE zxc;\nEND;\n" }, { "answer_id": 17059426, "author": "ENargit", "author_id": 676623, "author_profile": "https://Stackoverflow.com/users/676623", "pm_score": 5, "selected": false, "text": "SET @limit = 10;\nSELECT * FROM (\n SELECT instances.*, \n @rownum := @rownum + 1 AS rank\n FROM instances, \n (SELECT @rownum := 0) r\n) d WHERE rank < @limit;\n" }, { "answer_id": 30612069, "author": "rekaszeru", "author_id": 506879, "author_profile": "https://Stackoverflow.com/users/506879", "pm_score": 1, "selected": false, "text": "LIMIT OFFSET" }, { "answer_id": 60102915, "author": "juan_carlos_yl", "author_id": 10102494, "author_profile": "https://Stackoverflow.com/users/10102494", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE SOME_PROCEDURE_NAME(IN _length INT, IN _start INT)\nBEGIN\n SET _start = (SELECT COALESCE(_start, 0));\n SET _length = (SELECT COALESCE(_length, 999999)); -- USING ~0 GIVES OUT OF RANGE ERROR\n SET @row_num_personalized_variable = 0;\n\n SELECT\n *,\n @row_num_personalized_variable AS records_total \n FROM(\n SELECT\n *,\n (@row_num_personalized_variable := @row_num_personalized_variable + 1) AS row_num\n FROM some_table\n ) tb\n WHERE row_num > _start AND row_num <= (_start + _length);\nEND;\n" }, { "answer_id": 72050341, "author": "marisxanis", "author_id": 1249945, "author_profile": "https://Stackoverflow.com/users/1249945", "pm_score": 0, "selected": false, "text": "DECLARE rowsNr INT DEFAULT 0; \nSET rowsNr = 15; \nSELECT * FROM Table WHERE ... LIMIT rowsNr;\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24694/" ]
245,183
<p>How do you go about verifying the type of an uploaded file reliably without using the extension? I'm guessing that you have to examine the header / read some of the bytes, but I really have no idea how to go about it. Im using c# and asp.net.</p> <p>Thanks for any advice.</p> <hr> <p>ok, so from the above links I now know that I am looking for 'ff d8 ff e0' to positively identify a .jpg file for example.</p> <p>In my code I can read the first twenty bytes no problem:</p> <pre><code> FileStream fs = File.Open(filePath, FileMode.Open); Byte[] b = new byte[20]; fs.Read(b, 0, 20); </code></pre> <p>so (and please excuse my total inexperience here) but how do I check whether the byte array contains 'ff d8 ff e0'?</p>
[ { "answer_id": 245201, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "file tar file" }, { "answer_id": 245479, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 3, "selected": true, "text": "byte[] jpg = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 };\nbool match = true;\nfor (int i = 0; i < jpg.Length; i++)\n{\n if (jpg[i] != b[i])\n {\n match = false;\n break;\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
245,192
<p>When are objects or something else said to be &quot;first-class&quot; in a given programming language, and why? In what way do they differ from languages where they are not?</p> <p>When one says &quot;everything is an object&quot; (like in Python), do they indeed mean that &quot;everything is first-class&quot;?</p>
[ { "answer_id": 245208, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 9, "selected": true, "text": "// f: function that takes a number and returns a number\n// deltaX: small positive number\n// returns a function that is an approximate derivative of f\nfunction makeDerivative( f, deltaX )\n{\n var deriv = function(x)\n { \n return ( f(x + deltaX) - f(x) )/ deltaX;\n }\n return deriv;\n}\nvar cos = makeDerivative( Math.sin, 0.000001);\n// cos(0) ~> 1\n// cos(pi/2) ~> 0\n" }, { "answer_id": 245209, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "void f(int n) { return n * 2; }\n\nvoid g(Action<int> a, int n) { return a(n); }\n\n// Now call g and pass f:\n\ng(f, 10); // = 20\n Action<>" }, { "answer_id": 245295, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": "2 >>> dir(2)\n['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']\n 2 type 'int' >>> type(2)\n<class 'int'>\n int type 'type' >>> type(type(2))\n<class 'type'>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770/" ]
245,236
<p>Is there a pure-Java equivalent to &lt;jsp:forward page="..." /&gt; that I can use within a &lt;% ... %> block?</p> <p>For example, I currently have a JSP page something like this:</p> <pre><code>&lt;% String errorMessage = SomeClass.getInstance().doSomething(); if (errorMessage != null) { session.setAttribute("error", errorMessage); %&gt; &lt;jsp:forward page="error.jsp" /&gt; &lt;% } else { String url = response.encodeRedirectURL("index.jsp"); response.sendRedirect(url); } %&gt; </code></pre> <p>Having to break the &lt;% ... %> block to use the jsp:forward is ugly and makes it harder to read due to indentation, among other things.</p> <p>So, can I do the forward in the Java code without use the JSP tag?</p> <p>Something like this would be ideal:</p> <pre><code>&lt;% String errorMessage = SomeClass.getInstance().doSomething(); if (errorMessage != null) { session.setAttribute("error", errorMessage); someObject.forward("error.jsp"); } else { String url = response.encodeRedirectURL("index.jsp"); response.sendRedirect(url); } %&gt; </code></pre>
[ { "answer_id": 245257, "author": "Adam", "author_id": 8604, "author_profile": "https://Stackoverflow.com/users/8604", "pm_score": 6, "selected": true, "text": "someObject pageContext.forward(\"<some relative jsp>\");\n" }, { "answer_id": 245515, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 3, "selected": false, "text": "<%\n // Consider moving to a servlet or controller/action class\n String errorMessage = SomeClass.getInstance().doSomething();\n pageContext.setAttribute(\"errorMessage\", errorMessage);\n%>\n<c:choose>\n <c:when test=\"${not empty errorMessage}\">\n <c:set var=\"error\" scope=\"session\" value=\"${errorMessage}\" />\n <jsp:forward page=\"error.jsp\" />\n </c:when>\n <c:otherwise>\n <c:redirect url=\"index.jsp\" />\n </c:otherwise>\n</c:choose>\n" }, { "answer_id": 246488, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<%@page errorPage=\"Error.jsp\" %>\n\n<%\n String errorMessage = SomeClass.getInstance().doSomething();\n if (errorMessage != null) {\n throw new Exception(errorMessage); // Better throw the exception from doSomething()\n }\n pageContext.forward(\"index.jsp\");\n%>\n\n\nError.jsp\n.........\n<%@ page isErrorPage='true' %>\n<%\nout.print(\"Error!!!\"); \nout.print(exception.getMessage());\n%>\n <error-page>\n <exception-type>java.lang.Exception</exception-type>\n <location>/WEB-INF/jsp/Error.jsp</location>\n</error-page>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
245,237
<p>which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?</p>
[ { "answer_id": 245660, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 5, "selected": true, "text": ".wsgi" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
245,241
<p>I'd like to check ancestry using two jQuery objects. They don't have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called <code>get()</code>). jQuery's <code>is()</code> only works with expressions, so this code would be ideal but will not work:</p> <pre><code>var someDiv = $('#div'); $('a').click(function() { if ($(this).parents().is(someDiv)) { alert('boo'); } } </code></pre> <p>Just want to see if one element is a child of another and I'd like to avoid stepping back into DOM land if possible.</p>
[ { "answer_id": 245266, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 5, "selected": true, "text": "var someDiv = $('#div');\n\n$('a').click(function() {\n if ($(this).parents().index(someDiv) >= 0) {\n alert('boo');\n }\n}\n" }, { "answer_id": 245291, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 1, "selected": false, "text": "$('a').click(function() {\n if ($(this).parents(\"#div\").length) {\n alert('boo');\n }\n});\n" }, { "answer_id": 245310, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 0, "selected": false, "text": "$('a').click(function() {\n $(this).parents().filter(function() {\n return this == someDiv[0];\n }).each(function() {\n alert('foo');\n })\n}\n if ($.inArray( someDiv, $(this).parents() ) ) {\n alert('boo');\n}\n" }, { "answer_id": 245321, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 0, "selected": false, "text": "$( '#div a' ).click( function() { ... } );\n" }, { "answer_id": 245640, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 3, "selected": false, "text": "(this).parents().index(someDiv) >= 0" }, { "answer_id": 246069, "author": "Pier Luigi", "author_id": 27789, "author_profile": "https://Stackoverflow.com/users/27789", "pm_score": 0, "selected": false, "text": "var someDiv = $('#div');\n\n$('a').click(function() {\n if ($.inArray($(this).parents().get(), someDiv.get(0)) {\n alert('boo');\n }\n}\n" }, { "answer_id": 3615358, "author": "Jonas Fischer", "author_id": 436633, "author_profile": "https://Stackoverflow.com/users/436633", "pm_score": 0, "selected": false, "text": "var $element = $('a');\nwhile ($element && !$element.is('someDiv')) {\n var $element = $element.parent();\n};\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32229/" ]
245,251
<p>Is there an <strong>efficient</strong> way to create a file with a given size in Java?</p> <p>In C it can be done with <a href="http://linux.die.net/man/2/ftruncate" rel="noreferrer">ftruncate</a> (see <a href="https://stackoverflow.com/questions/139261/how-to-create-a-file-with-a-given-size-in-linux#245239">that answer</a>). </p> <p>Most people would just write <strong>n</strong> dummy bytes into the file, but there must be a faster way. I'm thinking of <a href="http://linux.die.net/man/2/ftruncate" rel="noreferrer">ftruncate</a> and also of <a href="http://en.wikipedia.org/wiki/Sparse_file" rel="noreferrer">Sparse files</a>…</p>
[ { "answer_id": 245278, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 8, "selected": true, "text": "import java.io.*;\n\nclass Test {\n public static void main(String args[]) throws Exception {\n RandomAccessFile f = new RandomAccessFile(\"t\", \"rw\");\n f.setLength(1024 * 1024 * 1024);\n }\n}\n 6070 open(\"t\", O_RDWR|O_CREAT, 0666) = 4\n6070 fstat(4, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0\n6070 lseek(4, 0, SEEK_CUR) = 0\n6070 ftruncate(4, 1073741824) = 0\n /2: open64(\"t\", O_RDWR|O_CREAT, 0666) = 14\n/2: fstat64(14, 0xFE4FF810) = 0\n/2: llseek(14, 0, SEEK_CUR) = 0\n/2: fcntl(14, F_FREESP64, 0xFE4FF998) = 0\n" }, { "answer_id": 58261085, "author": "mandev", "author_id": 12173657, "author_profile": "https://Stackoverflow.com/users/12173657", "pm_score": 3, "selected": false, "text": "final ByteBuffer buf = ByteBuffer.allocate(4).putInt(2);\nbuf.rewind();\n\nfinal OpenOption[] options = { StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW , StandardOpenOption.SPARSE };\nfinal Path hugeFile = Paths.get(\"hugefile.txt\");\n\ntry (final SeekableByteChannel channel = Files.newByteChannel(hugeFile, options);) {\n channel.position(HUGE_FILE_SIZE);\n channel.write(buf);\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ]
245,292
<p>I've been running into this problem with Flex for nearly a year, and each time I work up a quick hack solution that works for the time being. I'd like to see if anyone has a better idea.</p> <p>Here are the conditions of a problem:</p> <pre><code>|------Container ------------| | explicitHeight: 400 (or whatever) | | | |-------- VBox -------| | | | percentHeight: 100 | | | | | | | | |-Repeater------| | | | | | Potentially | | | | | | a lot of stuff. | | |--|--|---------------|---|---| </code></pre> <p>The problem is that, contrary to what I would like to happen, the VBox will ALWAYS expand to accommodate the content inside it, instead of sticking to the explicit height of its parent and creating a scroll bar.</p> <p>My solution has been to hard code in a reference to the parent (or however far up the display list we need to go to find an explicitly set value as opposed to a percentage).</p> <p>I've even considered using this in a utility class:</p> <pre><code>public static function getFirstExplicitHeightInDisplayList(comp:UIComponent):Number{ if (!isNaN(comp.explicitHeight)) return comp.explicitHeight; if (comp.parent is UIComponent) return getFirstExplicitHeightInDisplayList(UIComponent(comp.parent)); else return 0; } </code></pre> <p>Please tell me there's a better way.</p>
[ { "answer_id": 267370, "author": "Glenn", "author_id": 11814, "author_profile": "https://Stackoverflow.com/users/11814", "pm_score": 1, "selected": false, "text": "clipContent = true;\nverticalScrollPolicy = \"off\"\n percentHeight = 100 scrollRect = new Rectangle(x, y, w, h);\n" }, { "answer_id": 14834046, "author": "user1919265", "author_id": 1919265, "author_profile": "https://Stackoverflow.com/users/1919265", "pm_score": 0, "selected": false, "text": "minHeight = 0;\nminWidth = 0;\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23965/" ]
245,304
<p>I feel like I should know this, but I haven't been able to figure it out...</p> <p>I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.</p>
[ { "answer_id": 245314, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "traceback extract_stack" }, { "answer_id": 245333, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 4, "selected": false, "text": "from functools import wraps\ndef pass_func_name(func):\n \"Name of decorated function will be passed as keyword arg _func_name\"\n @wraps(func)\n def _pass_name(*args, **kwds):\n kwds['_func_name'] = func.func_name\n return func(*args, **kwds)\n return _pass_name\n @pass_func_name\ndef sum(a, b, _func_name):\n print \"running function %s\" % _func_name\n return a + b\n\nprint sum(2, 4)\n" }, { "answer_id": 245346, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 6, "selected": false, "text": "inspect import inspect\ndef somefunc(a,b,c):\n print \"My name is: %s\" % inspect.stack()[0][3]\n def funcname():\n return inspect.stack()[1][3]\n\ndef somefunc(a,b,c):\n print \"My name is: %s\" % funcname()\n" }, { "answer_id": 245561, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 3, "selected": false, "text": "# file \"foo.py\" \nimport sys\nimport os\n\ndef LINE( back = 0 ):\n return sys._getframe( back + 1 ).f_lineno\ndef FILE( back = 0 ):\n return sys._getframe( back + 1 ).f_code.co_filename\ndef FUNC( back = 0):\n return sys._getframe( back + 1 ).f_code.co_name\ndef WHERE( back = 0 ):\n frame = sys._getframe( back + 1 )\n return \"%s/%s %s()\" % ( os.path.basename( frame.f_code.co_filename ), \n frame.f_lineno, frame.f_code.co_name )\n\ndef testit():\n print \"Here in %s, file %s, line %s\" % ( FUNC(), FILE(), LINE() )\n print \"WHERE says '%s'\" % WHERE()\n\ntestit()\n $ python foo.py\nHere in testit, file foo.py, line 17\nWHERE says 'foo.py/18 testit()'\n" }, { "answer_id": 245581, "author": "spiv", "author_id": 22701, "author_profile": "https://Stackoverflow.com/users/22701", "pm_score": 6, "selected": true, "text": "inspect self.id()" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
245,308
<p>This one has me scratching my head.</p> <p>I'm running Subversion 1.3.1 (r19032) on Ubuntu. All was well until recently when I tried to run svnadmin verify prior to a dump. This is the error message:</p> <blockquote> <p>svnadmin: Invalid diff stream: insn 0 cannot be decoded</p> </blockquote> <p>I have looked around for an explanation and fix but can't seem to find one. Subversion experts, I need your help.</p>
[ { "answer_id": 245330, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "svnadmin" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32124/" ]
245,317
<p>Has anyone else had any problems using google's Domain Tracking API, I am specifically talking about the _link() method.</p> <p><a href="http://code.google.com/apis/analytics/docs/gaJS/gaJSApiDomainDirectory.html#_gat.GA_Tracker_._link" rel="nofollow noreferrer">The documentation is here</a></p> <p>The example provided shows that the _link() method should be used in the onclick event like this:</p> <pre><code>&lt;a href="http://www.newsite.com" onclick="pageTracker._link('http://www.newsite.com');return false;"&gt;Go to our sister site&lt;/a&gt; </code></pre> <p>However, this essentially just makes the link...do nothing (most probably because of the 'return false').</p> <p>My understanding is that the pageTracker._link() method is 'supposed' to add additional parameters to the url and do it's own document.location style redirect.</p> <p>Any ideas / catches / previous posts??</p>
[ { "answer_id": 245330, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "svnadmin" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25767/" ]
245,318
<p>After reading many of the replies to <a href="https://stackoverflow.com/questions/244302/what-do-you-think-of-the-new-c-40-dynamic-keyword">this thread</a>, I see that many of those who dislike it cite the potential for abuse of the new keyword. My question is, what sort of abuse? How could this be abused so badly as to make people vehemently dislike it? Is it just about purism? Or is there a real pitfall that I'm just not seeing?</p>
[ { "answer_id": 245537, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 3, "selected": false, "text": "public dynamic Foo(dynamic other) {\n dynamic clone = other.Clone();\n clone.AssignData(this.Data);\n return clone ;\n}\n public T Foo<T>(T other) where T: ICloneable, IAssignData{\n T clone = (T)other.Clone();\n clone.AssignData(this.Data);\n return clone;\n}\n" }, { "answer_id": 245573, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "dynamic dynamic dynamic var dynamic IDynamicObject" }, { "answer_id": 245626, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 4, "selected": false, "text": "On Error Resume Next dynamic" }, { "answer_id": 245633, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n var foo = new Foo(); \n Console.WriteLine(foo.Invoke(\"Hello\",\"Jonathan\"));\n } \n}\n\nstatic class DynamicDispatchHelper\n{\n static public object Invoke(this object ot, string methodName, params object[] args)\n {\n var t = ot.GetType();\n var m = t.GetMethod(methodName);\n return m.Invoke(ot, args);\n }\n}\n\nclass Foo\n{\n public string Hello(string name)\n {\n return (\"Hello World, \" + name);\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16942/" ]
245,334
<p>Ok, this is very weird. I'm trying to do a database migration, and all of a sudden, I'm getting these errors:</p> <pre> [C:\source\fe]: rake db:migrate --trace (in C:/source/fe) ** Invoke db:migrate (first_time) ** Invoke setup (first_time) ** Invoke gems:install (first_time) ** Invoke gems:set_gem_status (first_time) ** Execute gems:set_gem_status ** Execute gems:install rake aborted! can`'t activate rake (> 0.0.0), already activated rake-0.8.3] c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:139:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:155:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:154:in `each' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:154:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:49:in `gem' C:/source/fe/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:36:in `add_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `add_gem_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `each' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `add_gem_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:97:in `send' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:97:in `run' C:/source/fe/config/gems.rb:45:in `init_dependencies' C:/source/fe/lib/tasks/overridegems.rake:15 c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `call' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `execute' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `execute' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:578:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:588:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:577:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:588:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:577:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:564:in `invoke' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2019:in `invoke_task' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1991:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1970:in `run' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31 c:/ruby/bin/rake:19:in `load' c:/ruby/bin/rake:19 [C:\source\fe]: </pre> <p>Any suggestions? I've tried uninstalling and reinstalling rake, as well as updating rails.</p> <p>FYI, I'm using Gem 1.1.1.</p> <p>I've also tried gem update rails, gem update rake and just about anything else.</p>
[ { "answer_id": 245340, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": -1, "selected": false, "text": "rake aborted!\ncan`'t activate rake\n" }, { "answer_id": 296492, "author": "aronchick", "author_id": 4322, "author_profile": "https://Stackoverflow.com/users/4322", "pm_score": 3, "selected": true, "text": "gem uninstall rake\ngem install rake -v ('= 1.5.1')\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4322/" ]
245,337
<p>I'm using tortoise svn in Windows.</p> <p>How can I branch in SVN and have it branch my svn:external folders as well?</p>
[ { "answer_id": 248367, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 6, "selected": true, "text": "svn:externals svn:externals svn:externals" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
245,338
<p>I've been working on a SharePoint project and I have gone the route of loading User Controls through a custom web part.</p> <p>I have several web controls where I need to dynamically generate hyperlinks (in a loop from a database) that will call certain functions of the User Control when clicked.</p> <p>When I'm building my own ASP.NET sites, I just add parameters to the hyperlink and check on the page load to see if I need to run any other code when a hyperlink is click.</p> <p>I'm starting to realize that this probably won't be very reliable inside the SharePoint environment because I don't control the way web page URLs are formed.</p> <p>I would prefer to have it post back when the hyperlink is clicked and pass some values, but I'm not sure the best way to approach this.</p> <p>Could someone point me in the right direction?</p> <p>Thanks.</p>
[ { "answer_id": 248367, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 6, "selected": true, "text": "svn:externals svn:externals svn:externals" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
245,342
<p>Does anybody know how to call the <code>import data</code> built-in dialog excel from a macro (vba)?</p> <p>I've tried <code>Application.Dialogs.Item(...).Show</code> but I can´t find the right dialog. Please help.</p> <p>Thanks in advance.</p>
[ { "answer_id": 245378, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "'Allow user to select text file\nsf = Application _\n .GetOpenFilename(\"Text Files (*.txt), *.txt\")\nIf sf <> False Then\n 'Open text file\n Workbooks.OpenText sf\nEnd If\n" }, { "answer_id": 245385, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 3, "selected": true, "text": "Application.Dialogs(xlDialogImportTextFile).Show\n Set button = Application.CommandBars.FindControl(ID:=6262)\n Execute" }, { "answer_id": 246054, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "SendKeys \"%ddd\"\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24927/" ]
245,345
<p>I have a series of text that contains mixed numbers (ie: a whole part and a fractional part). The problem is that the text is full of human-coded sloppiness:</p> <ol> <li>The whole part may or may not exist (ex: "10")</li> <li>The fractional part may or may not exist (ex: "1/3")</li> <li>The two parts may be separated by spaces and/or a hyphens (ex: "10 1/3", "10-1/3", "10 - 1/3").</li> <li>The fraction itself may or may not have spaces between the number and the slash (ex: "1 /3", "1/ 3", "1 / 3").</li> <li>There may be other text after the fraction that needs to be ignored</li> </ol> <p>I need a regex that can parse these elements so that I can create a proper number out of this mess.</p>
[ { "answer_id": 245351, "author": "Craig Walker", "author_id": 3488, "author_profile": "https://Stackoverflow.com/users/3488", "pm_score": 5, "selected": true, "text": "(\\d++(?! */))? *-? *(?:(\\d+) */ *(\\d+))?.*$\n Match the regular expression below and capture its match into backreference number 1 «(\\d++(?! */))?»\n Between zero and one times, as many times as possible, giving back as needed (greedy) «?»\n Match a single digit 0..9 «\\d++»\n Between one and unlimited times, as many times as possible, without giving back (possessive) «++»\n Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?! */)»\n Match the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\n Match the character “/” literally «/»\nMatch the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch the character “-” literally «-?»\n Between zero and one times, as many times as possible, giving back as needed (greedy) «?»\nMatch the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch the regular expression below «(?:(\\d+) */ *(\\d+))?»\n Between zero and one times, as many times as possible, giving back as needed (greedy) «?»\n Match the regular expression below and capture its match into backreference number 2 «(\\d+)»\n Match a single digit 0..9 «\\d+»\n Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»\n Match the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\n Match the character “/” literally «/»\n Match the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\n Match the regular expression below and capture its match into backreference number 3 «(\\d+)»\n Match a single digit 0..9 «\\d+»\n Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»\nMatch any single character that is not a line break character «.*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nAssert position at the end of the string (or before the line break at the end of the string, if any) «$»\n" }, { "answer_id": 245399, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "sub parse_mixed {\n my($mixed) = @_;\n\n if($mixed =~ /^ *(\\d+)[- ]+(\\d+) *\\/ *(\\d)+(\\D.*)?$/) {\n return $1+$2/$3;\n } elsif($mixed =~ /^ *(\\d+) *\\/ *(\\d+)(\\D.*)?$/) {\n return $1/$2;\n } elsif($mixed =~ /^ *(\\d+)(\\D.*)?$/) {\n return $1;\n }\n}\n\nprint parse_mixed(\"10\"), \"\\n\";\nprint parse_mixed(\"1/3\"), \"\\n\";\nprint parse_mixed(\"1 / 3\"), \"\\n\";\nprint parse_mixed(\"10 1/3\"), \"\\n\";\nprint parse_mixed(\"10-1/3\"), \"\\n\";\nprint parse_mixed(\"10 - 1/3\"), \"\\n\";\n" }, { "answer_id": 249236, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "Perl 5.10 %+ $+{whole};\n$+{numerator};\n$+{denominator};\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
245,349
<p>I'd like to show an image in an iPhone app, but the image I'm using is too big. I'd like to scale it to fit the iPhone screen, I can't find any class to handle it.</p>
[ { "answer_id": 245364, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 5, "selected": true, "text": "UIImageView* view = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @\"your_image.png\"]];\nview.frame = CGRectMake(0, 0, width, height);\n CGRect frame = [[UIScreen mainScreen] bounds];\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32096/" ]
245,352
<p>I have the following intentionally trivial function:</p> <pre><code>void ReplaceSome(ref string text) { StringBuilder sb = new StringBuilder(text); sb[5] = 'a'; text = sb.ToString(); } </code></pre> <p>It appears to be inefficient to convert this to a StringBuilder to index into and replace some of the characters only to copy it back to the ref'd param. Is it possible to index directly into the text param as an L-Value?</p> <p>Or how else can I improve this?</p>
[ { "answer_id": 245371, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": -1, "selected": false, "text": " string test = \"hello world\";\n Console.WriteLine(test);\n\n test = test.Remove(5, 1);\n test = test.Insert(5, \"z\");\n\n Console.WriteLine(test);\n string test = \"hello world\".Remove(5, 1).Insert(5, \"z\");\n" }, { "answer_id": 245379, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": -1, "selected": false, "text": "text = text.Substring(0, 4) + \"a\" + text.Substring(5);\n" }, { "answer_id": 245449, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 2, "selected": false, "text": "StringBuilder sb = new StringBuilder(text);\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
245,354
<p>I'm fairly new to Castle Windsor and am looking into the in's and out's of the logging facility. It seems fairly impressive but the only thing i can't work out is where Windsor sets the Logger property on my classes. As in the following code will set Logger to the nullLogger if the class hasn't been setup yet but when Resolve is finished running the Logger property is set. </p> <pre><code>private ILogger logger; public ILogger Logger { get { if (logger == null) logger = NullLogger.Instance; return logger; } set { logger = value; } } </code></pre> <p>So what I am wondering is how and where windsor sets my Logger property. </p> <p>Cheers Anthony</p>
[ { "answer_id": 245478, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 4, "selected": false, "text": "<facilities> <?xml version=\"1.0\"?>\n<configuration>\n <configSections>\n <section name=\"castle\" type=\"Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor\"/>\n </configSections>\n<Configuration>\n\n<castle>\n\n <facilities>\n <facility id=\"loggingfacility\" \n type=\"Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging\" \n loggingApi=\"log4net\" \n configFile=\"logging.config\" />\n </facilities>\n\n</castle>\n</configuration>\n" }, { "answer_id": 1572119, "author": "UpTheCreek", "author_id": 324381, "author_profile": "https://Stackoverflow.com/users/324381", "pm_score": 4, "selected": false, "text": "container.AddFacility(\"logging\", new LoggingFacility(LoggerImplementation.Log4net));\n private ILogger logger = NullLogger.Instance;\n public ILogger Logger\n {\n get { return logger; }\n set { logger = value; }\n }\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30572/" ]
245,355
<p>Is there any way I can detect when my page has been set as the user's homepage in their browser?</p> <p>I'm most interested in something in javascript, but I'd be happy to hear about other approaches as well.</p> <p><strong>Edit</strong>: I'm not looking for anything sneaky. I'm wondering if there is anything that is explicitly allowed through the browsers to find out this information.</p>
[ { "answer_id": 245621, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 1, "selected": true, "text": "window.home()" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3561/" ]
245,369
<p>If I have the following string:</p> <pre><code>string s = "abcdefghab"; </code></pre> <p>Then how do I get a string (or char[]) that has just the characters that are repeated in the original string using C# and LINQ. In my example I want to end up with "ab".</p> <p>Although not necessary, I was trying to do this in a single line of LINQ and had so far come up with:</p> <pre><code>s.ToCharArray().OrderBy(a =&gt; a)... </code></pre>
[ { "answer_id": 245621, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 1, "selected": true, "text": "window.home()" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
245,395
<p>What are some of the lesser know, but important and useful features of Windows batch files?</p> <p>Guidelines:</p> <ul> <li>One feature per answer</li> <li>Give both a short <strong>description</strong> of the feature and an <strong>example</strong>, not just a link to documentation</li> <li>Limit answers to <strong>native funtionality</strong>, i.e., does not require additional software, like the <em>Windows Resource Kit</em></li> </ul> <p>Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants.</p> <p>(See also: <a href="https://stackoverflow.com/questions/148968/windows-batch-files-bat-vs-cmd">Windows batch files: .bat vs .cmd?</a>)</p>
[ { "answer_id": 245398, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 6, "selected": false, "text": "REM blah blah blah\n :: blah blah blah\n" }, { "answer_id": 245403, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 6, "selected": false, "text": "set BAT_HOME=%~dp0\necho %BAT_HOME%\ncd %BAT_HOME%\n" }, { "answer_id": 245407, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 6, "selected": false, "text": "> set str=0123456789\n> echo %str:~0,5%\n01234\n> echo %str:~-5,5%\n56789\n> echo %str:~3,-3%\n3456\n" }, { "answer_id": 245412, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 7, "selected": false, "text": "PUSHD path\n POPD\n" }, { "answer_id": 245414, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": false, "text": "FOR /F \"eol=; tokens=2,3* delims=, \" %i in (myfile.txt) do @echo %i %j %k\n" }, { "answer_id": 245417, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 4, "selected": false, "text": "> SET /A result=10/3 + 1\n4\n" }, { "answer_id": 245419, "author": "rbrayb", "author_id": 9922, "author_profile": "https://Stackoverflow.com/users/9922", "pm_score": 5, "selected": false, "text": "> copy nul filename.ext\n" }, { "answer_id": 245425, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "@echo off\n\nset x=xxxxx\ncall :sub 10\necho %x%\nexit /b\n\n:sub\nsetlocal\nset /a x=%1 + 1\necho %x%\nendlocal\nexit /b\n 11\nxxxxx\n" }, { "answer_id": 245428, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 5, "selected": false, "text": "PAUSE\n" }, { "answer_id": 245430, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "echo. ^<resourceDir^>/%basedir%/resources^</resourceDir^>\n" }, { "answer_id": 245434, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 9, "selected": true, "text": "call C:\\WINDOWS\\system32\\ntbackup.exe ^\n backup ^\n /V:yes ^\n /R:no ^\n /RS:no ^\n /HC:off ^\n /M normal ^\n /L:s ^\n @daily.bks ^\n /F daily.bkf\n" }, { "answer_id": 245435, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": " @echo off\n call :answer 42\n goto :eof\n:do_something\n echo %1\n goto :eof\n @echo off\n setlocal enableextensions enabledelayedexpansion\n call :seq_init seq1\n:loop1\n if not %seq1%== 10 (\n call :seq_next seq1\n echo !seq1!\n goto :loop1\n )\n endlocal\n goto :eof\n\n:seq_init\n set /a \"%1 = -1\"\n goto :eof\n:seq_next\n set /a \"seq_next_tmp1 = %1\"\n set /a \"%1 = %seq_next_tmp1% + 1\"\n set seq_next_tmp1=\n goto :eof\n" }, { "answer_id": 245440, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 2, "selected": false, "text": "DIR *.txt > tmp.txt\nDIR *.exe >> tmp.txt\n" }, { "answer_id": 245442, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": " @echo off\n setlocal enableextensions enabledelayedexpansion\n set full=/u01/users/pax\n:loop1\n if not \"!full:~-1!\" == \"/\" (\n set full2=!full:~-1!!full2!\n set full=!full:~,-1!\n goto :loop1\n )\n echo !full!\n endlocal\n" }, { "answer_id": 245455, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": " echo %time%\n call :waitfor 5\n echo %time%\n goto :eof\n:waitfor\n setlocal\n set /a \"t = %1 + 1\"\n >nul ping 127.0.0.1 -n %t%\n endlocal\n goto :eof\n" }, { "answer_id": 245498, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "echo.\n" }, { "answer_id": 245504, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "rd /s /q junk\n" }, { "answer_id": 245511, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "for /l %i in (1,1,10) do echo %i\n" }, { "answer_id": 245518, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": "for /f %i in ('dir /on /b *.jpg') do echo --^> %i\n for /f \"tokens=*\" %i in ('dir /on /b *.jpg') do echo --^> %i\n" }, { "answer_id": 245635, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 4, "selected": false, "text": "C:\\> type unicodeencoded.txt > dosencoded.txt\n" }, { "answer_id": 245641, "author": "LeopardSkinPillBoxHat", "author_id": 22489, "author_profile": "https://Stackoverflow.com/users/22489", "pm_score": 7, "selected": false, "text": "C:\\some_directory> start .\n" }, { "answer_id": 245774, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": false, "text": "if \"%VS90COMNTOOLS%\"==\"\" (\n echo: Visual Studio 2008 is not installed\n exit /b\n)\n" }, { "answer_id": 245982, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 0, "selected": false, "text": ":CODELINE\nNANT.EXE -buildfile:alltargets.build -l:build.log build.product\n@pause\nGOTO :CODELINE\n" }, { "answer_id": 246210, "author": "remonedo", "author_id": 11920, "author_profile": "https://Stackoverflow.com/users/11920", "pm_score": 3, "selected": false, "text": "for /f \"tokens=2-4 delims=/- \" %a in ('DATE/T') do echo %c%b%a\n" }, { "answer_id": 246691, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 5, "selected": false, "text": "PSKILL NOTEPAD >nul 2>&1\n" }, { "answer_id": 248573, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 1, "selected": false, "text": "setlocal ENABLEDELAYEDEXPANSION\nif defined CLASSPATH (set CLASSPATH=%CLASSPATH%;.) else (set CLASSPATH=.)\nFOR /R .\\lib %%G IN (*.jar) DO set CLASSPATH=!CLASSPATH!;%%G\nEcho The Classpath definition is %CLASSPATH%\n" }, { "answer_id": 252310, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": ":: ** Edit the most recent .TXT file and exit, useful in a .CMD / .BAT **\nFOR /F %%I IN ('DIR *.TXT /B /O:-N') DO NOTEPAD %%I & EXIT\n\n\n:: ** If exist any .TXT file, display the list in NOTEPAD, if not it \n:: ** exits without any error (note the && and the 2> error redirection)\nDIR *.TXT > TXT.LST 2> NUL && NOTEPAD TXT.LST\n" }, { "answer_id": 252402, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "if foo if bar baz\n" }, { "answer_id": 252404, "author": "MoreThanChaos", "author_id": 24824, "author_profile": "https://Stackoverflow.com/users/24824", "pm_score": 4, "selected": false, "text": "date time echo test > \"%date:~0,4%-%date:~5,2%-%date:~8,2% %time:~0,2%_%time:~3,2%_%time:~6,2%.txt\" color 0 F" }, { "answer_id": 252443, "author": "SqlACID", "author_id": 19797, "author_profile": "https://Stackoverflow.com/users/19797", "pm_score": 4, "selected": false, "text": "> @set fname=%date:/=%\n > @set dayofweek=%fname:~0,3%\n" }, { "answer_id": 254169, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 5, "selected": false, "text": "echo ^| ^< ^> ^& ^\\ ^^\n" }, { "answer_id": 258335, "author": "Alin Sfetcu", "author_id": 30694, "author_profile": "https://Stackoverflow.com/users/30694", "pm_score": 2, "selected": false, "text": "for /l %%i in (startNumber, counter, endNumber) do echo %%i\n" }, { "answer_id": 259840, "author": "Mark Arnott", "author_id": 31037, "author_profile": "https://Stackoverflow.com/users/31037", "pm_score": 0, "selected": false, "text": "HELP\n cmd.exe /? \n" }, { "answer_id": 259882, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 6, "selected": false, "text": "@echo OFF\ngoto :START\n\nDescription of the script.\n\nUsage:\n myscript -parm1|parm2 > result.txt\n\n:START\n" }, { "answer_id": 263270, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "@title Searching for ...\n:: processing search\n@title preparing search results\n:: data processing\n" }, { "answer_id": 270987, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 2, "selected": false, "text": "for /f \"tokens=*\" %%g in ('find /V \"\"') do (\n :: do what you want with %%g\n echo %%g\n)\n" }, { "answer_id": 271009, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 0, "selected": false, "text": "VERIFY errors 2>nul\nSETLOCAL ENABLEEXTENSIONS\nIF ERRORLEVEL 1 echo Unable to enable extensions\n" }, { "answer_id": 300410, "author": "Lara Dougan", "author_id": 4081, "author_profile": "https://Stackoverflow.com/users/4081", "pm_score": 3, "selected": false, "text": "call set SomeEnvVariable_%extension%=%%%somevalue%%%\n call set TempVar=%%SomeEnvVariable_%extension%%%\n setlocal EnableDelayedExpansion\n" }, { "answer_id": 304851, "author": "some", "author_id": 36866, "author_profile": "https://Stackoverflow.com/users/36866", "pm_score": 0, "selected": false, "text": "set > test\ndir test\ndel test\n" }, { "answer_id": 314953, "author": "Sascha", "author_id": 36372, "author_profile": "https://Stackoverflow.com/users/36372", "pm_score": 0, "selected": false, "text": "@echo off\nfor /f \"delims=\" %%f in ('dir %* /a-d /b /s') do echo %%f\n" }, { "answer_id": 334023, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 4, "selected": false, "text": "cls & dir\ncopy a b && echo Success\ncopy a b || echo Failure\n" }, { "answer_id": 351641, "author": "reuben", "author_id": 41646, "author_profile": "https://Stackoverflow.com/users/41646", "pm_score": 2, "selected": false, "text": "SHIFT\n :ParseArgs\n\nif \"%1\"==\"\" (\n goto :DoneParsingArgs\n)\n\nrem ... do something with %1 ...\n\nshift\n\ngoto :ParseArgs\n\n\n:DoneParsingArgs\n\nrem ...\n" }, { "answer_id": 358149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "@if defined %1 (call cd \"%%%1%%\") else (call cd %1)\n" }, { "answer_id": 374361, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": "echo -n Hello # or\necho Hello\\\\c\n Hello <nul set /p any-variable-name=Hello\n set /p <nul set /p" }, { "answer_id": 374363, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "c:\\> for %i in (cmd.exe) do @echo. %~$PATH:i\nC:\\WINDOWS\\system32\\cmd.exe\n\nc:\\> for %i in (python.exe) do @echo. %~$PATH:i\nC:\\Python25\\python.exe\n\nc:\\>\n" }, { "answer_id": 382349, "author": "matt wilkie", "author_id": 14420, "author_profile": "https://Stackoverflow.com/users/14420", "pm_score": 3, "selected": false, "text": ":: REM ::" }, { "answer_id": 422692, "author": "NicJ", "author_id": 43815, "author_profile": "https://Stackoverflow.com/users/43815", "pm_score": 2, "selected": false, "text": "@echo off\necho Please choose one of the following options\necho 1. Apple\necho 2. Orange\necho 3. Pizza\necho a, b, c. Something else\nchoice /c:123abc /m \"Answer?\"\nset ChoiceLevel=%ErrorLevel%\necho Choice was: %ChoiceLevel%\n %ChoiceLevel% b=5" }, { "answer_id": 422697, "author": "NicJ", "author_id": 43815, "author_profile": "https://Stackoverflow.com/users/43815", "pm_score": 2, "selected": false, "text": "> con echo a\necho b > con\n foo.cmd > output.txt\n \"a\" output.txt \"b\"" }, { "answer_id": 534767, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "@echo off\necho %0\necho %~d0\necho %~p0\necho %~dp0\necho %~x0\necho %~s0\necho %~sp0\n test\nc:\n\\Temp\\long dir name\\\nc:\\Temp\\long dir name\\\n.bat\nc:\\Temp\\LONGDI~1\\test.bat\n\\Temp\\LONGDI~1\\\n @echo off\necho %0\ncall :test\ngoto :eof\n\n:test\necho %0\necho %~0\necho %~n0\n myBatch.bat\n:test\n:test\nmyBatch\n" }, { "answer_id": 534890, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "copy con test.bat\n" }, { "answer_id": 904295, "author": "Deniz Zoeteman", "author_id": 111731, "author_profile": "https://Stackoverflow.com/users/111731", "pm_score": 0, "selected": false, "text": "@echo off\nIF exist %windir%\\system32\\iexplore.exe goto end\n\necho Hmm... it seems you do not have Internet Explorer.\necho Great! You seem to understand ;)\n\n:end\necho Hmm... You have Internet Explorer.\necho That is bad :)\n" }, { "answer_id": 904419, "author": "cookre", "author_id": 39195, "author_profile": "https://Stackoverflow.com/users/39195", "pm_score": -1, "selected": false, "text": "@echo off\n\n:: Get time (alas, it's only HH:MM xM\n\nfor /f %%a in ('time /t') do set zD1=%%a\n\n\n\n:: Get last digit of MM\n\nset zD2=%zD1:~4,1%\n\n\n\n:: Seed the randomizer, if needed\n\nif not defined zNUM1 set /a zNUM1=%zD2%\n\n\n:: Get a kinda random number\n\nset /a zNUM1=zNUM1 * 214013 + 2531011\n\nset /a zNUM2=zNUM1 ^>^> 16 ^& 0x7fff\n\n\n:: Pull off the first digit\n\n:: (Last digit would be better, but it's late, and I'm tired)\n\nset zIDX=%zNUM2:~0,1%\n\n\n:: Map it down to 0-3\n\nset /a zIDX=zIDX/3\n\n\n:: Finally, we can set do some proper initialization\n\nset /a zIIDX=0\n\nset zLO=\n\nset zLL=\"\"\n\n\n:: Step through each line in the file, looking for line zIDX\n\nfor /f \"delims=@\" %%a in (c:\\lines.txt) do call :zoo %zIDX% %%a\n\n\n:: If line zIDX wasn't found, we'll settle for zee LastLine\n\nif \"%zLO%\"==\"\" set zLO=%zLL%\n\ngoto awdun\n\n\n:: See if the current line is line zIDX\n\n:zoo\n\n\n:: Save string of all parms\n\nset zALL=%*\n\n\n:: Strip off the first parm (sure hope lines aren't longer than 254 chars)\n\nset zWORDS=%zALL:~2,255%\n\n\n:: Make this line zee LastLine\n\nset zLL=%zWORDS%\n\n\n:: If this is the line we're looking for, make it zee LineOut\n\nif {%1}=={%zIIDX%} set zLO=%zWORDS%\n\n\n:: Keep track of line numbers\n\nset /a zIIDX=%zIIDX% + 1\n\ngoto :eof\n\n\n\n\n:awdun\n\necho ==%zLO%==\n\n\n:: Be socially responsible\n\nset zALL=\n\nset zD1=\n\nset zD2=\n\nset zIDX=\n\nset zIIDX=\n\nset zLL=\n\nset zLO=\n\n:: But don't mess with seed\n\n::set zNUM1=\n\nset zNUM2=\n\nset zWORDS=\n" }, { "answer_id": 1077250, "author": "Anton Tykhyy", "author_id": 77724, "author_profile": "https://Stackoverflow.com/users/77724", "pm_score": 1, "selected": false, "text": "SET /P SET /P SVNVERSION=<ver.tmp\n" }, { "answer_id": 1077308, "author": "Coding With Style", "author_id": 130718, "author_profile": "https://Stackoverflow.com/users/130718", "pm_score": 3, "selected": false, "text": "ENDLOCAL & SET MYGLOBAL=%SOMELOCAL% & SET MYOTHERGLOBAL=%SOMEOTHERLOCAL%\n ENDLOCAL & SET MYLOCAL=%MYLOCAL%\n" }, { "answer_id": 1228895, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 1, "selected": false, "text": "goto :eof\n:: code scraps\ncall this.bat\ncall that.bat\nset TS=%DATE:~10%%DATE:~4,2%%DATE:~7,2%-%TIME:~0,2%%TIME:~3,2%%TIME:~6%%\nfor /R C:\\temp\\ %%G in (*.bak) DO del %%G\n" }, { "answer_id": 1397803, "author": "Igor Dvorkin", "author_id": 141158, "author_profile": "https://Stackoverflow.com/users/141158", "pm_score": 2, "selected": false, "text": "C:\\src\\branch1\\mydir\\mydir2\\mydir3\\mydir4>xcopy %cd:branch1=branch2%\\foo*\nOverwrite C:\\src\\branch1\\mydir\\mydir2\\mydir3\\mydir4\\foo.txt (Yes/No/All)? y\nC:\\src\\branch2\\mydir\\mydir2\\mydir3\\mydir4\\foo.txt\n" }, { "answer_id": 1549505, "author": "sahmeepee", "author_id": 187834, "author_profile": "https://Stackoverflow.com/users/187834", "pm_score": 0, "selected": false, "text": "TYPE %1\nTYPE %2\nTYPE %3\nTYPE %4\nTYPE %5\n...etc\n if [%1] NEQ [] (\nTYPE %1\n)\nif [%2] NEQ [] (\nTYPE %2\n)\nif [%3] NEQ [] (\nTYPE %3\n)\nif [%4] NEQ [] (\nTYPE %4\n)\nif [%5] NEQ [] (\nTYPE %5\n)\n...etc\n :loop\nIF [%1] NEQ [] (\nTYPE %1\n) ELSE (\nGOTO end\n)\nSHIFT\nGOTO loop\n:end\n" }, { "answer_id": 1613169, "author": "guerda", "author_id": 32043, "author_profile": "https://Stackoverflow.com/users/32043", "pm_score": 0, "selected": false, "text": "FIND @echo off\n:begin\nset /p term=Enter query: \ntype phonebookfile.txt |find /i \"%term%\"\nif %errorlevel% == 0 GOTO :choose\necho No entry found\nset /p new_entry=Add new entry: \necho %new_entry% >> phonebookfile.txt \n:choose\nset /p action=(q)uit, (n)ew query or (e)dit? [q] \nif \"%action%\"==\"n\" GOTO anfang\nif \"%action%\"==\"e\" (\n notepad phonebookfile.txt\n goto :choose\n)\n" }, { "answer_id": 3296461, "author": "batch fool", "author_id": 397527, "author_profile": "https://Stackoverflow.com/users/397527", "pm_score": 2, "selected": false, "text": "myExe -? >nul 2>&1 \nSet errCode=%errorlevel%\n@if %errCode% EQU 0 (\n echo myExe -? does not return an error (exists)\n) ELSE (\n echo myExe -? returns an error (does not exist)\n)\n" }, { "answer_id": 3752322, "author": "Andy Morris", "author_id": 174447, "author_profile": "https://Stackoverflow.com/users/174447", "pm_score": 3, "selected": false, "text": "set VarName=Param\nset Param=This\n\ncall set Answer=%%%Varname%%%\nEcho %Answer%\n set VarName=Param\nset Param=This\ncall set Answer=%Param%\nEcho This\nThis\n" }, { "answer_id": 3786683, "author": "Andrei Coșcodan", "author_id": 359381, "author_profile": "https://Stackoverflow.com/users/359381", "pm_score": 1, "selected": false, "text": " @echo off\n\n echo hP1X500P[PZBBBfh#b##fXf-V@`$fPf]f3/f1/5++u5>in.com\n\n set /p secret_password=\"Enter password:\"<nul\n\n for /f \"tokens=*\" %%i in ('in.com') do (set secret_password=%%i)\n\n del in.com\n" }, { "answer_id": 3786739, "author": "JUST MY correct OPINION", "author_id": 282658, "author_profile": "https://Stackoverflow.com/users/282658", "pm_score": 2, "selected": false, "text": "&:: :: This is my batch file which does stuff.\ncopy thisstuff thatstuff &:: We need to make a backup in case we screw up!\n\n:: ... do lots of other stuff\n & ; :: REM" }, { "answer_id": 3786752, "author": "Andrei Coșcodan", "author_id": 359381, "author_profile": "https://Stackoverflow.com/users/359381", "pm_score": 1, "selected": false, "text": "fsutil fsinfo drives\n" }, { "answer_id": 3787015, "author": "Andrei Coșcodan", "author_id": 359381, "author_profile": "https://Stackoverflow.com/users/359381", "pm_score": 2, "selected": false, "text": "for /f \"tokens=1-4 delims=/-. \" %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)\ngoto :end_set_date\n\n:set_date\nif (\"%1:~0,1%\" gtr \"9\") shift\nfor /f \"skip=1 tokens=2-4 delims=(-)\" %%m in ('echo,^|date') do (set %%m=%1&set %%n=%2&set %%o=%3)\ngoto :eof\n\n:end_set_date\n\necho day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%\n" }, { "answer_id": 5419090, "author": "dave1010", "author_id": 315435, "author_profile": "https://Stackoverflow.com/users/315435", "pm_score": 1, "selected": false, "text": "copy con new.txt\nThis is the contents of my file\n^Z\n cat <<EOF > new.txt\nThis is the contents of my file\nEOF\n" }, { "answer_id": 5419228, "author": "Fadrian Sudaman", "author_id": 276556, "author_profile": "https://Stackoverflow.com/users/276556", "pm_score": 1, "selected": false, "text": "for /f \"useback tokens=*\" %%a in ('%str%') do set str=%%~a\n" }, { "answer_id": 5419611, "author": "Brecht Yperman", "author_id": 674927, "author_profile": "https://Stackoverflow.com/users/674927", "pm_score": 2, "selected": false, "text": "forfiles /D -2 /P \"C:\\Temp\" /S /C \"cmd /c del @path\"\n" }, { "answer_id": 5419979, "author": "BartekB", "author_id": 674943, "author_profile": "https://Stackoverflow.com/users/674943", "pm_score": 2, "selected": false, "text": "findstr \"^[0-9].*\" c:\\windows\\system32\\drivers\\etc\\hosts\n" }, { "answer_id": 5420385, "author": "caseyboardman", "author_id": 807, "author_profile": "https://Stackoverflow.com/users/807", "pm_score": 1, "selected": false, "text": "IF \"%errorlevel%\" NEQ \"0\" (\n echo \"ERROR: Something broke. Bailing out.\"\n exit /B 1\n)\n" }, { "answer_id": 5420982, "author": "thatbrentguy", "author_id": 226705, "author_profile": "https://Stackoverflow.com/users/226705", "pm_score": 2, "selected": false, "text": " C:\\>pushd \\\\yourmom\\jukebox\n\n Z:\\>pushd \\\\yourmom\\business\n\n Y:\\>\n C:\\utils>prompt $+$m$p$g\n\n C:\\utils>pushd m:\n\n +\\\\yourmom\\pub M:\\>pushd c:\\\n\n ++c:\\>pushd\n M:\\\n C:\\utils \n\n ++c:\\>popd\n\n +\\\\yourmom\\pub M:\\>popd\n\n C:\\utils>\n" }, { "answer_id": 5421017, "author": "Frans Bouma", "author_id": 44991, "author_profile": "https://Stackoverflow.com/users/44991", "pm_score": 2, "selected": false, "text": "dir /b *.* | findstr /f:/ \"thepattern\"\n" }, { "answer_id": 5421140, "author": "Soulman", "author_id": 368491, "author_profile": "https://Stackoverflow.com/users/368491", "pm_score": 1, "selected": false, "text": "mklink /d directorylink ..\\realdirectory\nmklink filelink realfile\n" }, { "answer_id": 5422998, "author": "John Fisher", "author_id": 50358, "author_profile": "https://Stackoverflow.com/users/50358", "pm_score": 0, "selected": false, "text": "copy UpdateSource.bat Current.bat\necho \"Hi!\"\n copy UpdateSource.bat Current.bat\n HI!\n" }, { "answer_id": 5423169, "author": "DaWolfman", "author_id": 162900, "author_profile": "https://Stackoverflow.com/users/162900", "pm_score": 1, "selected": false, "text": "copy file1.txt+file2.txt+file3.txt append.txt\n SET MSG=%*\n @SET MSG=%*\n@echo %MSG%\n C:\\test>test.bat Hello World!\nHello World!\n" }, { "answer_id": 5423452, "author": "bneal", "author_id": 489548, "author_profile": "https://Stackoverflow.com/users/489548", "pm_score": 1, "selected": false, "text": "findstr /S /C:\"string literal\" *.*\n findstr /S /R \"^ERROR\" *.log\n dir /S myfile.txt\n" }, { "answer_id": 5423809, "author": "jon_brockman", "author_id": 97269, "author_profile": "https://Stackoverflow.com/users/97269", "pm_score": 0, "selected": false, "text": "EXPLORER \"C:\\Documents and Settings\\myusername\\Desktop\\sandbox\"\n" }, { "answer_id": 5423962, "author": "jftuga", "author_id": 452281, "author_profile": "https://Stackoverflow.com/users/452281", "pm_score": 0, "selected": false, "text": "for /f \"usebackq tokens=1,2,3,4,5,6,7 delims=/:. \" %%a in (`echo %DATE% %TIME%`) do set NOW=%%d%%b%%c_%%e%%f%%g\nset LOG=output_%NOW%.log\n" }, { "answer_id": 5424017, "author": "jftuga", "author_id": 452281, "author_profile": "https://Stackoverflow.com/users/452281", "pm_score": -1, "selected": false, "text": "rem a.txt contains one line: abc123\nset /p DATA=<a.txt\necho data: %DATA%\n" }, { "answer_id": 5424388, "author": "Ben Burnett", "author_id": 675544, "author_profile": "https://Stackoverflow.com/users/675544", "pm_score": 2, "selected": false, "text": "set count=1\nset var%count%=42\n call echo %var%count%%\n call echo %%var%count%%%\n call set x=%var%count%%\n echo %x%\n" }, { "answer_id": 5424491, "author": "Ben Burnett", "author_id": 675544, "author_profile": "https://Stackoverflow.com/users/675544", "pm_score": 2, "selected": false, "text": ";= @echo off\n;= rem Call DOSKEY and use this file as the macrofile\n;= %SystemRoot%\\system32\\doskey /listsize=1000 /macrofile=%0%\n;= rem In batch mode, jump to the end of the file\n;= goto end\n\n;= Doskey aliases\nh=doskey /history\n\n;= File listing enhancements\nls=dir /x $*\n\n;= Directory navigation\nup=cd ..\npd=pushd\n\n;= :end\n;= rem ******************************************************************\n;= rem * EOF - Don't remove the following line. It clears out the ';' \n;= rem * macro. Were using it because there is no support for comments\n;= rem * in a DOSKEY macro file.\n;= rem ******************************************************************\n;=\n" }, { "answer_id": 5425444, "author": "Anonymous", "author_id": 675705, "author_profile": "https://Stackoverflow.com/users/675705", "pm_score": -1, "selected": false, "text": "Yet another stdout/stderr logging utility [2010-08-05]\nCopyright (C) 2010 LoRd_MuldeR <MuldeR2@GMX.de>\nReleased under the terms of the GNU General Public License (see License.txt)\n\nUsage:\n logger.exe [logger options] : program.exe [program arguments]\n program.exe [program arguments] | logger.exe [logger options] : -\n\nOptions:\n -log <file name> Name of the log file to create (default: \"<program> <time>.log\")\n -append Append to the log file instead of replacing the existing file\n -mode <mode> Write 'stdout' or 'stderr' or 'both' to log file (default: 'both')\n -format <format> Format of log file, 'raw' or 'time' or 'full' (default: 'time')\n -filter <filter> Don't write lines to log file that contain this string\n -invert Invert filter, i.e. write only lines to log file that match filter\n -ignorecase Apply filter in a case-insensitive way (default: case-sensitive)\n -nojobctrl Don't add child process to job object (applies to Win2k and later)\n -noescape Don't escape double quotes when forwarding command-line arguments\n -silent Don't print additional information to the console\n -priority <flag> Change process priority (idle/belownormal/normal/abovenormal/high)\n -inputcp <cpid> Use the specified codepage for input processing (default: 'utf8')\n -outputcp <cpid> Use the specified codepage for log file output (default: 'utf8')\n" }, { "answer_id": 5425807, "author": "MadKat", "author_id": 675731, "author_profile": "https://Stackoverflow.com/users/675731", "pm_score": 1, "selected": false, "text": "@echo off\n\nset x=xxxxx\ncall :fun 10\necho \"%x%\"\necho \"%y%\"\nexit /b\n\n:fun\nsetlocal\nset /a y=%1 + 1\nendlocal & set x=%y%\nexit /b\n \"11\"\n\"\"\n" }, { "answer_id": 9386014, "author": "Mashmagar", "author_id": 276120, "author_profile": "https://Stackoverflow.com/users/276120", "pm_score": 0, "selected": false, "text": "pause" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
245,406
<p>I have done this:</p> <pre><code>$ z() { echo 'hello world'; } </code></pre> <p>How do I get rid of it?</p>
[ { "answer_id": 245409, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 9, "selected": true, "text": "unset -f z\n unset z\n" }, { "answer_id": 59416087, "author": "Micah Elliott", "author_id": 326516, "author_profile": "https://Stackoverflow.com/users/326516", "pm_score": 3, "selected": false, "text": "unfunction z\n unhash -f z unset -f z unset unhash unalias unlimit unsetopt un<tab> realiases refunctions resetopts reenv source" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
245,418
<p>I have an ASHX handler that returns an XML response (FileStructureXML.ashx).</p> <p>Now I need to get the XML response from the ASHX handler and use it as a data source for my ASPX page.</p> <p>If I point the XMLDataSource to a static XML file on the server, the treeview populates as expected. However, if I point the XMLDataSource to the ASHX handler instead of a static XML file on the server, it doesn't work.</p> <p>Any help would be appreciated.</p> <pre><code>&lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:TreeView ID="TreeView_Folders" runat="server" DataSourceID="FileXML"&gt; &lt;DataBindings&gt; &lt;asp:TreeNodeBinding DataMember="Directory" TextField="Name" /&gt; &lt;asp:TreeNodeBinding DataMember="File" TextField="Name" /&gt; &lt;/DataBindings&gt; &lt;/asp:TreeView&gt; &lt;/div&gt; &lt;div&gt; &lt;asp:XmlDataSource ID="FileXML" runat="server" DataFile="FileStructureXML.ashx"&gt; &lt;/asp:XmlDataSource&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre>
[ { "answer_id": 245676, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "XmlDocument treeDoc = new XmlDocument();\ntreeDoc.Load( \"~/FileStructureXML.ashx\" ); // this takes a URL\nFileXml.Data = treeDoc.FirstChild.OuterXml; // everything after the xml definition\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
245,420
<p>Here's the situation - I've got a shell that loads an external .swf. Now, that .swf is 800x600, but it's an animation piece, and there are elements that extends off the stage. When I load the .swf into the shell and call its width attribute, it returns 1200 - because it's including the elements that break out of the stage.</p> <p>This isn't what I want - ideally, there would be two properties, one to return the 'calculated width' and one to return the 'default width'. Do these properties exist, and if not, what's the best workaround?</p>
[ { "answer_id": 247078, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "Loader swfLoader.contentLoaderInfo.width\nswfLoader.contentLoaderInfo.height\n stage.stageWidth stage.stageHeight" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14026/" ]
245,421
<p>As far as I can tell, the best way to do this is do it in the DataTable.RowChanging event. But what if I want to cancel the action? There is no EventArgs.Cancel option...</p>
[ { "answer_id": 246381, "author": "Mitkins", "author_id": 23401, "author_profile": "https://Stackoverflow.com/users/23401", "pm_score": 0, "selected": false, "text": "DataGridView DataTable.RowChanging DataGridView.OnError EventArgs.Cancel true" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23401/" ]
245,441
<p>I want to add complex databinding to my custom winforms control, so I can do the following:</p> <pre><code>myControl.DisplayMember = "Name"; myControl.ValueMember = "Name"; myControl.DataSource = new List&lt;someObject&gt;(); </code></pre> <p>Does anyone know what interfaces, etc. have to be implemented to achieve this?</p> <p>I have had a look into it and all I found is <code>IBindableComponent</code>, but that seems to be for Simple Binding rather than Complex Binding.</p>
[ { "answer_id": 53775033, "author": "Chris Tollefson", "author_id": 10366669, "author_profile": "https://Stackoverflow.com/users/10366669", "pm_score": 2, "selected": false, "text": "ComplexBindingPropertiesAttribute LookupBindingPropertiesAttribute ComplexBindindPropertiesAttribute DataGridView LookupBindingPropertiesAttribute ListControl DataGridView ListBox ComboBox List<T> UserControl ComplexBindingPropertiesAttribute DataGridView DataSource DataMember DataGridView // ComplexBindingControl.cs\n// Adapted from https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-complex-data-binding\n\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace BindingDemo\n{\n [ComplexBindingProperties(\"DataSource\", \"DataMember\")]\n public partial class ComplexBindingControl : UserControl\n {\n public ComplexBindingControl()\n {\n InitializeComponent();\n }\n\n // Use a DataGridView for its complex data binding implementation.\n\n public object DataSource\n {\n get => dataGridView1.DataSource;\n set => dataGridView1.DataSource = value;\n }\n\n public string DataMember\n {\n get => dataGridView1.DataMember;\n set => dataGridView1.DataMember = value;\n }\n }\n}\n LookupBindingPropertiesAttribute ListBox ComboBox DataSource DisplayMember ValueMember LookupMember ListBox ComboBox // LookupBindingControl.cs\n// Adapted from https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-lookup-data-binding\n\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace BindingDemo\n{\n [LookupBindingProperties(\"DataSource\", \"DisplayMember\", \"ValueMember\", \"LookupMember\")]\n public partial class LookupBindingControl : UserControl\n {\n public LookupBindingControl()\n {\n InitializeComponent();\n }\n\n // Use a ListBox or ComboBox for its lookup data binding implementation.\n\n public object DataSource\n {\n get => listBox1.DataSource;\n set => listBox1.DataSource = value;\n }\n\n public string DisplayMember\n {\n get => listBox1.DisplayMember;\n set => listBox1.DisplayMember = value;\n }\n\n public string ValueMember\n {\n get => listBox1.ValueMember;\n set => listBox1.ValueMember = value;\n }\n\n public string LookupMember\n {\n get => listBox1.SelectedValue?.ToString();\n set => listBox1.SelectedValue = value;\n }\n }\n}\n listBox1.SelectedValue null Form // Form1.cs\n\nusing System.Collections.Generic;\nusing System.Windows.Forms;\n\nnamespace BindingDemo\n{\n public partial class Form1 : Form\n {\n private readonly List<SomeObject> data;\n\n public Form1()\n {\n InitializeComponent();\n\n // Prepare some sample data.\n data = new List<SomeObject>\n {\n new SomeObject(\"Alice\"),\n new SomeObject(\"Bob\"),\n new SomeObject(\"Carol\"),\n };\n\n // Bind the data to your custom control...\n\n // ...for \"complex\" data binding:\n complexBindingControl1.DataSource = data;\n\n // ...for \"lookup\" data binding:\n lookupBindingControl1.DataSource = data;\n lookupBindingControl1.DisplayMember = \"Name\";\n lookupBindingControl1.ValueMember = \"Name\";\n }\n }\n\n internal class SomeObject\n {\n public SomeObject(string name)\n {\n Name = name;\n }\n\n public string Name { get; set; }\n }\n}\n" }, { "answer_id": 56788463, "author": "Frank", "author_id": 5674529, "author_profile": "https://Stackoverflow.com/users/5674529", "pm_score": 0, "selected": false, "text": "public string LookupMember {\n get {\n try {\n return listBox1.SelectedValue.ToString();\n }\n catch { return null; }\n }\n set => listBox1.SelectedValue = value;\n }\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ]
245,447
<p>Using Python I want to be able to draw text at different angles using PIL.</p> <p>For example, imagine you were drawing the number around the face of a clock. The number <strong>3</strong> would appear as expected whereas <strong>12</strong> would we drawn rotated counter-clockwise 90 degrees.</p> <p>Therefore, I need to be able to draw many different strings at many different angles.</p>
[ { "answer_id": 245837, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 2, "selected": false, "text": "\nimport Image\nim = Image.new(\"RGB\", (100, 100))\nimport ImageDraw\ndraw = ImageDraw.Draw(im)\ndraw.text((50, 50), \"hey\")\nim.rotate(45).show()\n" }, { "answer_id": 245892, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 7, "selected": true, "text": "# Demo to add rotated text to an image using PIL\n\nimport Image\nimport ImageFont, ImageDraw, ImageOps\n\nim=Image.open(\"stormy100.jpg\")\n\nf = ImageFont.load_default()\ntxt=Image.new('L', (500,50))\nd = ImageDraw.Draw(txt)\nd.text( (0, 0), \"Someplace Near Boulder\", font=f, fill=255)\nw=txt.rotate(17.5, expand=1)\n\nim.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60), w)\n" }, { "answer_id": 741592, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "(...)\nimg_main = Image.new(\"RGB\", (200, 200))\nfont = ImageFont.load_default()\n\n# Text to be rotated...\nrotate_text = u'This text should be rotated.'\n\n# Image for text to be rotated\nimg_txt = Image.new('L', font.getsize(rotate_text))\ndraw_txt = ImageDraw.Draw(img_txt)\ndraw_txt.text((0,0), rotate_text, font=font, fill=255)\nt = img_value_axis.rotate(90, expand=1)\n" }, { "answer_id": 35586716, "author": "stenci", "author_id": 1899628, "author_profile": "https://Stackoverflow.com/users/1899628", "pm_score": 3, "selected": false, "text": "from PIL import Image, ImageFont, ImageDraw\n\ntext = 'TEST'\nfont = ImageFont.truetype(r'C:\\Windows\\Fonts\\Arial.ttf', 50)\nwidth, height = font.getsize(text)\n\nimage1 = Image.new('RGBA', (200, 150), (0, 128, 0, 92))\ndraw1 = ImageDraw.Draw(image1)\ndraw1.text((0, 0), text=text, font=font, fill=(255, 128, 0))\n\nimage2 = Image.new('RGBA', (width, height), (0, 0, 128, 92))\ndraw2 = ImageDraw.Draw(image2)\ndraw2.text((0, 0), text=text, font=font, fill=(0, 255, 128))\n\nimage2 = image2.rotate(30, expand=1)\n\npx, py = 10, 10\nsx, sy = image2.size\nimage1.paste(image2, (px, py, px + sx, py + sy), image2)\n\nimage1.show()\n" }, { "answer_id": 63005869, "author": "Harry Moreno", "author_id": 630752, "author_profile": "https://Stackoverflow.com/users/630752", "pm_score": 2, "selected": false, "text": "from PIL import Image, ImageFont, ImageDraw\nimport math\n\n# sample dimensions\npdf_width = 1000\npdf_height = 1500\n\n#text_to_be_rotated = 'Harry Moreno'\ntext_to_be_rotated = 'Harry Moreno (morenoh149@gmail.com)'\nmessage_length = len(text_to_be_rotated)\n\n# load font (tweak ratio based on your particular font)\nFONT_RATIO = 1.5\nDIAGONAL_PERCENTAGE = .5\ndiagonal_length = int(math.sqrt((pdf_width**2) + (pdf_height**2)))\ndiagonal_to_use = diagonal_length * DIAGONAL_PERCENTAGE\nfont_size = int(diagonal_to_use / (message_length / FONT_RATIO))\nfont = ImageFont.truetype(r'./venv/lib/python3.7/site-packages/reportlab/fonts/Vera.ttf', font_size)\n#font = ImageFont.load_default() # fallback\n\n# target\nimage = Image.new('RGBA', (pdf_width, pdf_height), (0, 128, 0, 92))\n\n# watermark\nopacity = int(256 * .5)\nmark_width, mark_height = font.getsize(text_to_be_rotated)\nwatermark = Image.new('RGBA', (mark_width, mark_height), (0, 0, 0, 0))\ndraw = ImageDraw.Draw(watermark)\ndraw.text((0, 0), text=text_to_be_rotated, font=font, fill=(0, 0, 0, opacity))\nangle = math.degrees(math.atan(pdf_height/pdf_width))\nwatermark = watermark.rotate(angle, expand=1)\n\n# merge\nwx, wy = watermark.size\npx = int((pdf_width - wx)/2)\npy = int((pdf_height - wy)/2)\nimage.paste(watermark, (px, py, px + wx, py + wy), watermark)\n\nimage.show()\n" }, { "answer_id": 67285956, "author": "mafu", "author_id": 39590, "author_profile": "https://Stackoverflow.com/users/39590", "pm_score": 2, "selected": false, "text": "def draw_text_90_into (text: str, into, at):\n # Measure the text area\n font = ImageFont.truetype (r'C:\\Windows\\Fonts\\Arial.ttf', 16)\n wi, hi = font.getsize (text)\n\n # Copy the relevant area from the source image\n img = into.crop ((at[0], at[1], at[0] + hi, at[1] + wi))\n\n # Rotate it backwards\n img = img.rotate (270, expand = 1)\n\n # Print into the rotated area\n d = ImageDraw.Draw (img)\n d.text ((0, 0), text, font = font, fill = (0, 0, 0))\n\n # Rotate it forward again\n img = img.rotate (90, expand = 1)\n\n # Insert it back into the source image\n # Note that we don't need a mask\n into.paste (img, at)\n" }, { "answer_id": 73445706, "author": "Tobias Teleman", "author_id": 803457, "author_profile": "https://Stackoverflow.com/users/803457", "pm_score": 0, "selected": false, "text": "# Matrix operations\ndef translate(x, y):\n return np.array([[1, 0, x], [0, 1, y], [0, 0, 1]])\n\n\ndef rotate(angle):\n c, s = np.cos(angle), np.sin(angle)\n return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])\n\n\ndef draw_text(image, text, font, x, y, angle):\n \"\"\"Draw text at x,y and rotated angle radians on the given PIL image\"\"\"\n m = np.matmul(translate(x, y), rotate(angle))\n transform = [m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2]]\n draw = aggdraw.Draw(image)\n draw.settransform(transform)\n draw.text((tx, ty), text, font)\n draw.settransform()\n draw.flush()\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20498/" ]
245,453
<p>I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method. </p> <p>I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element. </p> <p>It works, but it just doesn't <em>feel</em> right!</p> <p>I have also noticed that I seem to use the static modifier much more than my classmates in general...</p> <p>Can anybody please provide any general tips as well as feedback as to how I can improve my code?</p> <pre><code>public class RecursiveTry{ static int[] n = new int[] {1,2,4,3,3,32,100}; static int current = 0; static int maxValue = 0; static int SIZE = n.length; public static void main(String[] args){ System.out.println(Max(n, SIZE)); } public static int Max(int[] n, int SIZE) { if(current &lt;= SIZE - 1){ if (maxValue &lt;= n[current]) { maxValue = n[current]; current++; Max(n, SIZE); } else { current++; Max(n, SIZE); } } return maxValue; } </code></pre> <p>}</p>
[ { "answer_id": 245468, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "function Max(data, size) {\n assert(size > 0)\n if (size == 1) {\n return data[0]\n }\n maxtail = Max(data[1..size], size-1)\n if (data[0] > maxtail) {\n return data[0]\n } else {\n return maxtail\n }\n}\n size == 1" }, { "answer_id": 245472, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": -1, "selected": false, "text": "public class RecursiveTry{\n\n private int[] n = {1,2,4,3,3,32,100};\n\n public static void main(String[] args){\n RecursiveTry maxObject = new RecursiveTry();\n System.out.println(maxObject.Max(maxObject.n, 0));\n }\n\n public int Max(int[] n, int start) {\n if(start == n.length - 1) {\n return n[start];\n } else { \n int maxRest = Max(n, start + 1);\n if(n[start] > maxRest) {\n return n[start];\n }\n return maxRest;\n }\n }\n\n}\n" }, { "answer_id": 245477, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "public class RecursiveTry{\n static int[] n;\n\n public static void main(String[] args){\n RecursiveTry t = new RecursiveTry(new int[] {1,2,4,3,3,32,100});\n System.out.println(t.Max());\n } \n\n RecursiveTry(int[] arg) {\n n = arg;\n }\n\n public int Max() {\n return MaxHelper(0);\n }\n\n private int MaxHelper(int index) {\n if(index == n.length-1) {\n return n[index];\n } else {\n int maxrest = MaxHelper(index+1);\n int current = n[index];\n if(current > maxrest)\n return current;\n else\n return maxrest;\n }\n }\n}\n" }, { "answer_id": 245492, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 2, "selected": false, "text": "static int[] n = new int[] {1,2,4,3,3,32,100};\nstatic int SIZE = n.length;\n" }, { "answer_id": 245493, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "int Max(int[] array, int currentPos, int maxValue) {\n // Ouch!\n if (currentPos < 0) {\n raise some error\n }\n // We reached the end of the array, return latest maxValue\n if (currentPos >= array.length) {\n return maxValue;\n }\n // Is current value greater then latest maxValue ?\n int currentValue = array[currentPos];\n if (currentValue > maxValue) {\n // currentValue is a new maxValue\n return Max(array, currentPos + 1, currentValue);\n } else {\n // maxValue is still a max value\n return Max(array, currentPos + 1, maxValue);\n }\n}\n...\n\nint[] array = new int[] {...};\nint currentPos = 0;\nint maxValue = array[currentPos] or minimum int value; \n maxValue = Max(array, currentPos, maxValue);\n" }, { "answer_id": 245495, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "public class RecursiveTry\n{\n public static void main(String[] args)\n {\n System.out.println(Max(new int[] {1,2,4,3,3,32,100}, 0, 0));\n } \n\n public static int Max(int[] n, int current, int maxValue) \n {\n if(current < n.Length)\n {\n if (maxValue <= n[current] || current == 0))\n {\n return Max(n, current+1, n[current]);\n }\n return Max(n, current+1, maxValue);\n }\n return maxValue;\n }\n}\n" }, { "answer_id": 245540, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "(define (max l)\n (if (= (length l) 1)\n (first l)\n (local ([define maxRest (max (rest l))])\n (if (> (first l) maxRest)\n (first l)\n maxRest))))\n define max of a list as:\n if the list has one element, return that element\n otherwise, the max of the list will be the max between the first element and the max of the rest of the list\n" }, { "answer_id": 245627, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "public class Recursion {\n\n public static void main(String[] args) {\n int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n System.out.println(\"Max: \" + max(0, data));\n }\n\n public static int max(int i, int[] arr) {\n if(i == arr.length-1) {\n return arr[i];\n }\n\n int memo = max(i+1, arr);\n if(arr[i] > memo) {\n return arr[i];\n }\n return memo;\n }\n}\n" }, { "answer_id": 245726, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "public class RecursiveTry {\n public static void main(String[] args) {\n int[] x = new int[] {1,2,4,3,3,32,100};\n System.out.println(Max(x, 0));\n } \n\n public static int Max(int[] arr, int currPos) {\n if (arr.length == 0) return -1;\n if (currPos == arr.length) return arr[0];\n int len = Max (arr, currPos + 1);\n if (len < arr[currPos]) return arr[currPos];\n return len;\n }\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
245,456
<p>I'm looking for a way to get the name of the main HTML form so I can submit it from JavaScript.</p> <p>The reason I can just set the name of the form is because the JavaScript is on a User Control that could get added to many different sites with different form names.</p> <p>Thanks.</p>
[ { "answer_id": 245491, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": " document.forms[0].submit();\n" }, { "answer_id": 245506, "author": "Andrew Theken", "author_id": 32238, "author_profile": "https://Stackoverflow.com/users/32238", "pm_score": 4, "selected": true, "text": "<script type=\"text/javascript\">\n\nvar formname = '<%=this.Page.Form.Name %>';\n\n</script>\n" }, { "answer_id": 73158533, "author": "masoud rafiee", "author_id": 4256602, "author_profile": "https://Stackoverflow.com/users/4256602", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n\nvar formname = '<%=this.Page.AppRelativeVirtualPath.Replace(this.Page.AppRelativeTemplateSourceDirectory,\"\")%>';\n\n</script>\n \n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
245,465
<p>How do you connect to a remote server via IP address in the manner that TOAD, SqlDeveloper, are able to connect to databases with just the ip address, username, SID and password?</p> <p>Whenever I try to specify and IP address, it seems to be taking it locally.</p> <p>In other words, how should the string for cx_Oracle.connect() be formatted to a non local database?</p> <p>There was a previous post which listed as an answer connecting to Oracle via cx_Oracle module with the following code:</p> <pre><code>#!/usr/bin/python import cx_Oracle connstr='scott/tiger' conn = cx_Oracle.connect(connstr) curs = conn.cursor() curs.execute('select * from emp') print curs.description for row in curs: print row conn.close() </code></pre>
[ { "answer_id": 1181699, "author": "Jeffrey Kemp", "author_id": 103295, "author_profile": "https://Stackoverflow.com/users/103295", "pm_score": 5, "selected": false, "text": "import cx_Oracle\nconnstr = 'scott/tiger@server:1521/orcl'\nconn = cx_Oracle.connect(connstr)\n" }, { "answer_id": 1870849, "author": "Kevin Horn", "author_id": 134391, "author_profile": "https://Stackoverflow.com/users/134391", "pm_score": 6, "selected": false, "text": "ip = '192.168.0.1'\nport = 1521\nSID = 'YOURSIDHERE'\ndsn_tns = cx_Oracle.makedsn(ip, port, SID)\n\ndb = cx_Oracle.connect('username', 'password', dsn_tns)\n dsn_tns print dsn_tns\n" }, { "answer_id": 39984489, "author": "Gerrat", "author_id": 429982, "author_profile": "https://Stackoverflow.com/users/429982", "pm_score": 2, "selected": false, "text": "import cx_Oracle\nip = '192.168.0.1'\nport = 1521\nservice_name = 'my_service'\ndsn = cx_Oracle.makedsn(ip, port, service_name=service_name)\n\ndb = cx_Oracle.connect('user', 'password', dsn)\n" }, { "answer_id": 48919165, "author": "Gank", "author_id": 336175, "author_profile": "https://Stackoverflow.com/users/336175", "pm_score": -1, "selected": false, "text": "import cx_Oracle\nip = '172.30.1.234'\nport = 1524\nSID = 'dev3'\ndsn_tns = cx_Oracle.makedsn(ip, port, SID)\n\nconn = cx_Oracle.connect('dbmylike', 'pass', dsn_tns)\nprint conn.version\nconn.close()\n" }, { "answer_id": 50897127, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 3, "selected": false, "text": "import cx_Oracle\n\nCONN_INFO = {\n 'host': 'xxx.xx.xxx.x',\n 'port': 12345,\n 'user': 'user_name',\n 'psw': 'your_password',\n 'service': 'abc.xyz.com',\n}\n\nCONN_STR = '{user}/{psw}@{host}:{port}/{service}'.format(**CONN_INFO)\n\nconnection = cx_Oracle.connect(CONN_STR)\n" }, { "answer_id": 57984625, "author": "admin", "author_id": 6489637, "author_profile": "https://Stackoverflow.com/users/6489637", "pm_score": 1, "selected": false, "text": "import cx_Oracle\ndsn = cx_Oracle.makedsn(host='127.0.0.1', port=1521, sid='your_sid')\nconn = cx_Oracle.connect(user='your_username', password='your_password', dsn=dsn)\nconn.close()\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
245,475
<p>Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector.</p> <pre><code>void buttonVectorCleanup(vector&lt;Button *&gt; dVector){ Button* tmpClass; for(int i = 0; i &lt; (int)dVector.size(); i++){ tmpClass = dVector[i]; delete tmpClass; } } </code></pre> <p>This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.</p>
[ { "answer_id": 245483, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 4, "selected": true, "text": "template <class T>\nvoid vectorCleanup(vector<T *>& dVector){\n T* tmpClass;\n for(vector<T*>::size_type i = 0; i < dVector.size(); i++){\n tmpClass = dVector[i];\n\n delete tmpClass;\n }\n" }, { "answer_id": 246035, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 2, "selected": false, "text": "struct delete_ptr\n{\n template <typename T>\n void operator()(T& p)\n {\n delete p;\n p = 0;\n }\n};\n std::for_each #include <algorithm> int wmain(int, wchar_t*[])\n{\n std::vector<int*> items;\n items.push_back(new int(1));\n items.push_back(new int(2));\n items.push_back(new int(3));\n std::for_each(items.begin(), items.end(), delete_ptr());\n};\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370/" ]
245,482
<p>I have form area in my view. If I click button <kbd>A</kbd>, I want to submit to <code>/Books/1</code> and if I click button <kbd>B</kbd>, I want to submit to <code>/Books/2</code></p> <p>How do I achieve this with MVC?</p>
[ { "answer_id": 245501, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 1, "selected": false, "text": "<form id=\"form1\" name=\"form1\" action=\"/Books/1\" method=\"get\">\n<!--...form fields-->\n</form>\n\n\n<form id=\"form2\" name=\"form2\" action=\"/Books/2\" method=\"get\">\n<!--...form fields-->\n</form>\n" }, { "answer_id": 245679, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 2, "selected": true, "text": "routes.MapRoute(\n \"Books\",\n \"Books/{searchExpr}/{pageId}\",\n new { controller = \"Books\", action = \"Search\", searchExpr = \"\", pageId = 1 }\n);\n" }, { "answer_id": 245718, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 2, "selected": false, "text": "<form id=\"form1\" name=\"form1\" action=\"/Books/\" method=\"get\">\n<input type=\"text\" name=\"search\" value=\"\">\n<input type=\"submit\" name=\"id\" value=\"1\">\n<input type=\"submit\" name=\"id\" value=\"2\">\n</form>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5463/" ]
245,503
<p>I am interested in mastering prefetch-related functions such as</p> <p>_mm_prefetch(...)</p> <p>so when I perform operations that loop over arrays, the memory bandwidth is fully utilized. What are the best resources for learning about this?</p> <p>I am doing this work in C using GCC 4 series on an intel linux platform.</p>
[ { "answer_id": 245556, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "__builtin_prefetch" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30636/" ]
245,507
<p>I am trying to add different styles within a textarea eg bold, different colors etc</p> <p>WYSIWYG editors (eg tinyMCE) used in web pages typically do this but I am having trouble working out how they do it.</p> <p>You cannot do this:</p> <p><a href="http://www.yart.com.au/test/html.gif">alt text http://www.yart.com.au/test/html.gif</a></p> <p>So how do they achieve it?</p>
[ { "answer_id": 245737, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": true, "text": "designMode contentEditable <br> <p> <b> <i>" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24696/" ]
245,509
<p>What's the best algorithm for comparing two arrays to see if they have the same members?</p> <p>Assume there are no duplicates, the members can be in any order, and that neither is sorted.</p> <pre><code>compare( [a, b, c, d], [b, a, d, c] ) ==&gt; true compare( [a, b, e], [a, b, c] ) ==&gt; false compare( [a, b, c], [a, b] ) ==&gt; false </code></pre>
[ { "answer_id": 245510, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "function compare($foo, $bar) {\n if (count($foo) != count($bar)) return false;\n\n foreach ($foo as $f) {\n foreach ($bar as $b) {\n if ($f == $b) {\n // $f exists in $bar, skip to the next $foo\n continue 2;\n }\n }\n return false;\n }\n return true;\n}\n" }, { "answer_id": 245529, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "def comparray(a, b): \n sa = set(a)\n return len(sa)==len(b) and all(el in sa for el in b)\n" }, { "answer_id": 245544, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "public bool MatchArrays(object[] array1, object[] array2)\n{\n if (array1.length != array2.length)\n return false;\n\n bool retValue = true;\n\n HashTable ht = new HashTable();\n\n for (int i = 0; i < array1.length; i++)\n {\n ht.Add(array1[i]);\n }\n\n for (int i = 0; i < array2.length; i++)\n {\n if (ht.Contains(array2[i])\n {\n retValue = false;\n break;\n }\n }\n\n return retValue;\n}\n" }, { "answer_id": 245651, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 1, "selected": false, "text": "O(nlogn) O(2*nlogn) == O(nlogn) O(nlogn) O(n)" }, { "answer_id": 373356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " public static bool ArrayEqual(int[] list1, int[] list2)\n {\n if (list1 == null || list2 == null)\n {\n throw new Exception(\"Invalid input\");\n }\n\n if (list1.Length != list2.Length)\n {\n return false;\n }\n\n int diff = 0;\n\n for (int i = 0; i < list1.Length; i++)\n {\n diff += list1[i] - list2[i];\n }\n\n return (diff == 0);\n }\n" }, { "answer_id": 373393, "author": "Yaniv", "author_id": 46883, "author_profile": "https://Stackoverflow.com/users/46883", "pm_score": 3, "selected": false, "text": "o(n log n) public bool MatchArrays(object[] array1, object[] array2)\n{\n if (array1.length != array2.length)\n return false;\n long signature1 = 0;\n long signature2 = 0;\n for (i=0;i<array1.length;i++) {\n signature1=CommutativeOperation(signature1,array1[i].getHashCode());\n signature2=CommutativeOperation(signature2,array2[i].getHashCode());\n }\n\n if (signature1 != signature2) \n return false;\n\n return MatchArraysTheLongWay(array1, array2);\n}\n public long CommutativeOperation(long oldValue, long newElement) {\n return oldValue + newElement;\n}\n" }, { "answer_id": 2428771, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private boolean compare(List listA, List listB){\n if (listA.size()==0||listA.size()==0) return true;\n List runner = new ArrayList();\n List maxList = listA.size()>listB.size()?listA:listB;\n List minList = listA.size()>listB.size()?listB:listA;\n int macthes = 0;\n List nextList = null;;\n int maxLength = maxList.size();\n for(int i=0;i<maxLength;i++){\n for (int j=0;j<2;j++) {\n nextList = (nextList==null)?maxList:(maxList==nextList)?minList:maList;\n if (i<= nextList.size()) {\n MatchingItem nextItem =new MatchingItem(nextList.get(i),nextList)\n int position = runner.indexOf(nextItem);\n if (position <0){\n runner.add(nextItem);\n }else{\n MatchingItem itemInBag = runner.get(position);\n if (itemInBag.getList != nextList) matches++;\n runner.remove(position);\n }\n }\n }\n }\n return maxLength==macthes;\n}\n\npublic Class MatchingItem{\nprivate Object item;\nprivate List itemList;\npublic MatchingItem(Object item,List itemList){\n this.item=item\n this.itemList = itemList\n}\npublic boolean equals(object other){\n MatchingItem otheritem = (MatchingItem)other;\n return otheritem.item.equals(this.item) and otheritem.itemlist!=this.itemlist\n}\n\npublic Object getItem(){ return this.item}\npublic Object getList(){ return this.itemList}\n" }, { "answer_id": 4154365, "author": "Mohammad Mazaz", "author_id": 467782, "author_profile": "https://Stackoverflow.com/users/467782", "pm_score": 1, "selected": false, "text": "A:array\nB:array\nC:hashtable\n\nif A.length != B.length then return false;\n\nforeach objA in A\n{\nH = objA;\nif H is not found in C.Keys then\nC.add(H as key,1 as initial value);\nelse\nC.Val[H as key]++;\n}\n\nforeach objB in B\n{\nH = objB;\nif H is not found in C.Keys then\nreturn false;\nelse\nC.Val[H as key]--;\n}\n\nif(C contains non-zero value)\nreturn false;\nelse\nreturn true;\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]