qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
362,489
<p>Using <a href="https://numpy.org/" rel="nofollow noreferrer">NumPy</a>, a matrix A has n rows and m columns, and I want add a guard ring to matrix A. That guard ring is all zero.</p> <p>What should I do? Use Reshape? But the element is not enough to make a n+1 m+1 matrix.</p> <p>Or etc.?</p> <p>Thanks in advance</p> <h6>I mean an extra ring of cells that always contain 0 surround matrix A.Basically there is a Matrix B has n+2rows m+2columns where the first row and columns and the last row and columns are all zero,and the rest of it are same as matrix A.</h6>
[ { "answer_id": 363040, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 4, "selected": true, "text": ">>> import numpy\n>>> a = numpy.array(range(9)).reshape((3,3))\n>>> b = numpy.zeros(tuple(s+2 for s in a.shape), a.dtype)\n>>> b[tuple(slice(1,-1) for s in a.shape)] = a\n>>> b\narray([[0, 0, 0, 0, 0],\n [0, 0, 1, 2, 0],\n [0, 3, 4, 5, 0],\n [0, 6, 7, 8, 0],\n [0, 0, 0, 0, 0]])\n" }, { "answer_id": 365974, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": ">>> a = numpy.array(range(9)).reshape((3,3))\n>>> a\narray([[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]])\n>>> b = numpy.zeros(a.shape + numpy.array(2), a.dtype)\n>>> b\narray([[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]])\n>>> b[1:-1,1:-1] = a\n>>> b\narray([[0, 0, 0, 0, 0],\n [0, 0, 1, 2, 0],\n [0, 3, 4, 5, 0],\n [0, 6, 7, 8, 0],\n [0, 0, 0, 0, 0]])\n" }, { "answer_id": 43906270, "author": "Russell Richie", "author_id": 2554824, "author_profile": "https://Stackoverflow.com/users/2554824", "pm_score": 2, "selected": false, "text": "pad import numpy as np\na = np.array(range(9)).reshape((3, 3))\na\nOut[15]: \narray([[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]])\n\na = np.pad(a, pad_width=((1,1),(1,1)), mode='constant', constant_values=0)\na\nOut[16]: \narray([[0, 0, 0, 0, 0],\n [0, 0, 1, 2, 0],\n [0, 3, 4, 5, 0],\n [0, 6, 7, 8, 0],\n [0, 0, 0, 0, 0]])\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44354/" ]
362,503
<p>I have been trying to remove the text before and after a particular character in each line of a text. It would be very hard to do manually since it contain 5000 lines and I need to remove text before that keyword in each line. Any software that could do it, would be great or any Perl scripts that could run on Windows. I run Perl scripts in ActivePerl, so scripts that could do this and run on ActivePerl would be helpful.</p> <p>Thanks</p>
[ { "answer_id": 362517, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": 1, "selected": false, "text": "$text =~ s/^.*(keyword1|keyword2).*$/$1/m;\n m ^ $" }, { "answer_id": 362554, "author": "Xetius", "author_id": 274, "author_profile": "https://Stackoverflow.com/users/274", "pm_score": 2, "selected": false, "text": "s/.*?keyword(.*?)keyword.*/keyword$1keyword/;\n" }, { "answer_id": 362580, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "$text =~ s/ .*? (keyword) .* /$1/gx;\n" }, { "answer_id": 362685, "author": "Jørn Jensen", "author_id": 34585, "author_profile": "https://Stackoverflow.com/users/34585", "pm_score": 0, "selected": false, "text": "keyword1 keyword2 while (<>) {\n s/.*(keyword1)/$1/;\n s/(keyword2).*/$1/;\n print;\n}\n fix.pl original.txt > new.txt\n perl -i.bak -pe 's/.*(keyword1)/$1/; s/(keyword2).*/$1/;' original.txt original2.txt\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45614/" ]
362,514
<p>I wanted to set a CSS class in my master page, which depends on the current controller and action. I can get to the current controller via <code>ViewContext.Controller.GetType().Name</code>, but how do I get the current action (e.g. <code>Index</code>, <code>Show</code> etc.)?</p>
[ { "answer_id": 362536, "author": "terjetyl", "author_id": 29519, "author_profile": "https://Stackoverflow.com/users/29519", "pm_score": 3, "selected": false, "text": "ViewData[\"CssClass\"] = \"bold\";\n" }, { "answer_id": 362539, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 7, "selected": true, "text": "ViewContext RouteData" }, { "answer_id": 362706, "author": "tsquillario", "author_id": 45509, "author_profile": "https://Stackoverflow.com/users/45509", "pm_score": 6, "selected": false, "text": "ViewContext.RouteData.Values[\"id\"].ToString()\n ViewContext.RouteData.Values[\"controller\"].ToString() \n" }, { "answer_id": 527830, "author": "Christian Dalager", "author_id": 11239, "author_profile": "https://Stackoverflow.com/users/11239", "pm_score": 9, "selected": false, "text": "ViewContext.Controller.ValueProvider[\"action\"].RawValue\nViewContext.Controller.ValueProvider[\"controller\"].RawValue\nViewContext.Controller.ValueProvider[\"id\"].RawValue\n ViewContext.Controller.ValueProvider.GetValue(\"action\").RawValue\nViewContext.Controller.ValueProvider.GetValue(\"controller\").RawValue\nViewContext.Controller.ValueProvider.GetValue(\"id\").RawValue\n ViewContext.Controller.RouteData.Values[\"action\"]\nViewContext.Controller.RouteData.Values[\"controller\"]\nViewContext.Controller.RouteData.Values[\"id\"]\n ViewContext.RouteData.Values[\"action\"]\nViewContext.RouteData.Values[\"controller\"]\nViewContext.RouteData.Values[\"id\"]\n" }, { "answer_id": 1408919, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 5, "selected": false, "text": "protected override void OnActionExecuting(ActionExecutingContext filterContext)\n{\n ActionDescriptor actionDescriptor = filterContext.ActionDescriptor;\n string actionName = actionDescriptor.ActionName;\n string controllerName = actionDescriptor.ControllerDescriptor.ControllerName;\n // Now that you have the values, set them somewhere and pass them down with your ViewModel\n // This will keep your view cleaner and the controller will take care of everything that the view needs to do it's job.\n}\n" }, { "answer_id": 1451649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "string currentActionName = ViewContext.RouteData.GetRequiredString(\"action\");\n string currentViewName = ((WebFormView)ViewContext.View).ViewPath;\n" }, { "answer_id": 4381735, "author": "RunnerRick", "author_id": 392176, "author_profile": "https://Stackoverflow.com/users/392176", "pm_score": 0, "selected": false, "text": "public class MyCustomApplicationController : Controller {}\n\npublic class HomeController : MyCustomApplicationController {}\n protected ActionDescriptor ExecutingAction { get; set; }\n string currentActionName = this.ExecutingAction.ActionName;\n" }, { "answer_id": 4437048, "author": "Michael Vashchinsky", "author_id": 260240, "author_profile": "https://Stackoverflow.com/users/260240", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Web.Mvc;\n\nnamespace MyMvcApp.Helpers {\n public class LocationHelper {\n public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {\n bool result = false;\n string normalizedControllerName = controllerName.EndsWith(\"Controller\") ? controllerName : String.Format(\"{0}Controller\", controllerName);\n\n if(viewContext == null) return false;\n if(String.IsNullOrEmpty(actionName)) return false;\n\n if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&\n viewContext.Controller.ValueProvider.GetValue(\"action\").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {\n result = true;\n }\n\n return result;\n }\n }\n}\n <div id=\"menucontainer\">\n\n <ul id=\"menu\">\n <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction(\"home\", \"index\", ViewContext)) {\n @:class=\"selected\"\n }>@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction(\"account\",\"logon\", ViewContext)) {\n @:class=\"selected\"\n }>@Html.ActionLink(\"Logon\", \"Logon\", \"Account\")</li>\n <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction(\"home\",\"about\", ViewContext)) {\n @:class=\"selected\"\n }>@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n </ul>\n\n </div>\n" }, { "answer_id": 4696794, "author": "Viacheslav Smityukh", "author_id": 558457, "author_profile": "https://Stackoverflow.com/users/558457", "pm_score": 4, "selected": false, "text": "ViewContext.RouteData.Values[\"controller\"]\nViewContext.RouteData.Values[\"action\"]\n" }, { "answer_id": 20271607, "author": "kiewic", "author_id": 27211, "author_profile": "https://Stackoverflow.com/users/27211", "pm_score": 2, "selected": false, "text": "ControllerContext.Controller.ValueProvider.GetValue(\"controller\").RawValue\nControllerContext.Controller.ValueProvider.GetValue(\"action\").RawValue\n" }, { "answer_id": 37805059, "author": "Santosh Pandey", "author_id": 6240932, "author_profile": "https://Stackoverflow.com/users/6240932", "pm_score": 0, "selected": false, "text": "protected override void HandleUnknownAction(string actionName) \n{ TempData[\"actionName\"] = actionName;\n View(\"urViewName\").ExecuteResult(this.ControllerContext);\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33647/" ]
362,516
<p>How can one ignore Unexpected element situation in JAXB ans still get all other kind of javax.xml.bind.UnmarshalException?</p> <pre><code>obj = unmler.unmarshal(new StringReader(xml)) </code></pre> <p>Notice i still want to get the obj result of the xml parsing.</p>
[ { "answer_id": 362533, "author": "João", "author_id": 35323, "author_profile": "https://Stackoverflow.com/users/35323", "pm_score": 5, "selected": true, "text": "class CustomValidationEventHandler implements ValidationEventHandler{\n\n public boolean handleEvent(ValidationEvent evt) {\n System.out.println(\"Event Info: \"+evt);\n if(evt.getMessage().contains(\"Unexpected element\"))\n return true;\n return false;\n }\n\n}\n Unmarshaller u = ...;\n\nu.setEventHandler(new CustomValidationEventHandler());\n\nu.unmarshal(new StringReader(xml));\n" }, { "answer_id": 66778858, "author": "Franziskus Karsunke", "author_id": 762585, "author_profile": "https://Stackoverflow.com/users/762585", "pm_score": 0, "selected": false, "text": "JAXB.unmarshal()" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35323/" ]
362,522
<p>I recently tried switching from using <code>python-mode.el</code> to <code>python.el</code> for editing python files in emacs, found the experience a little alien and unproductive, and scurried back. I've been using <code>python-mode.el</code> for something like ten years, so perhaps I'm a little set in my ways. I'd be interested in hearing from anyone who's carefully evaluated the two modes, in particular of the pros and cons they perceive of each and how their work generally interacts with the features specific to <code>python.el</code>.</p> <p>The two major issues for me with <code>python.el</code> were </p> <ol> <li><p>Each buffer visiting a python file gets its own inferior interactive python shell. I am used to doing development in one interactive shell and sharing data between python files. (Might seem like bad practice from a software-engineering perspective, but I'm usually working with huge datasets which take a while to load into memory.)</p></li> <li><p>The skeleton-mode support in python.el, which seemed absolutely gratuitous (python's syntax makes such automation unnecessary) and badly designed (for instance, it has no knowledge of "<code>for</code>" loop generator expressions or "<code>&lt;expr 1&gt; if &lt;cond&gt; else &lt;expr 2&gt;</code>" expressions, so you have to go back and remove the colons it helpfully inserts after insisting that you enter the expression clauses in the minibuffer.) I couldn't figure out how to turn it off. There was a <code>python.el</code> variable which claimed to control this, but it didn't seem to work. It could be that the version of <code>python.el</code> I was using was broken (it came from the debian emacs-snapshot package) so if anyone knows of an up-to-date version of it, I'd like to hear about it. (I had the same problem with the version in CVS emacs as of approximately two weeks ago.)</p></li> </ol>
[ { "answer_id": 368719, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 2, "selected": false, "text": "(define-key inferior-python-mode-map \"\\C-c\\t\" 'python-complete-symbol)\n >>> import os\n>>> os.f[C-c TAB]\n Click <mouse-2> on a completion to select it.\nIn this buffer, type RET to select the completion near point.\n\nPossible completions are:\nos.fchdir os.fdatasync\nos.fdopen os.fork\nos.forkpty os.fpathconf\nos.fstat os.fstatvfs\nos.fsync os.ftruncate\n" }, { "answer_id": 71343689, "author": "Steve Newcomb", "author_id": 3976240, "author_profile": "https://Stackoverflow.com/users/3976240", "pm_score": 0, "selected": false, "text": "c-X ; git clone https://gitlab.com/python-mode-devs/python-mode.git" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1941213/" ]
362,541
<p>I'm new to TDD. So any help would be appreciated. I'm using NUnit and Rhino mocks. How can I set the ID value to 1 in my mock object?</p> <p>I had a look at this: <a href="http://www.iamnotmyself.com/2008/06/26/RhinoMocksAndReadOnlyPropertyInjectionPart2.aspx" rel="nofollow noreferrer">http://www.iamnotmyself.com/2008/06/26/RhinoMocksAndReadOnlyPropertyInjectionPart2.aspx</a> but the reflection doesn't seem to work against interfaces.</p> <pre><code> public interface IBatchInfo { int ID { get;} Branches Branch { get; set; } string Description { get; set; } } [SetUp] public void PerFixtureSetup() { _mocks = new MockRepository(); _testRepository = _mocks.StrictMock&lt;IOLERepository&gt;(); } [Test] public void ItemsAreReturned() { IBatchInfo aBatchItem= _mocks.Stub&lt;IBatchInfo&gt;(); aBatchItem.ID = 1; //fails because ID is a readonly property aBatchItem.Branch = Branches.Edinburgh; List&lt;IBatchInfo&gt; list = new List&lt;IBatchInfo&gt;(); list.Add( aBatchItem); Expect.Call(_testRepository.BatchListActive()).Return(list); _mocks.ReplayAll(); BatchList bf = new BatchList(_testRepository, "usercreated", (IDBUpdateNotifier)DBUpdateNotifier.Instance); List&lt;Batch&gt; listofBatch = bf.Items; Assert.AreEqual(1, listofBatch.Count); Assert.AreEqual(1, listofBatch[0].ID); Assert.AreEqual( Branches.Edinburgh,listofBatch[0].Branch); } </code></pre>
[ { "answer_id": 368719, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 2, "selected": false, "text": "(define-key inferior-python-mode-map \"\\C-c\\t\" 'python-complete-symbol)\n >>> import os\n>>> os.f[C-c TAB]\n Click <mouse-2> on a completion to select it.\nIn this buffer, type RET to select the completion near point.\n\nPossible completions are:\nos.fchdir os.fdatasync\nos.fdopen os.fork\nos.forkpty os.fpathconf\nos.fstat os.fstatvfs\nos.fsync os.ftruncate\n" }, { "answer_id": 71343689, "author": "Steve Newcomb", "author_id": 3976240, "author_profile": "https://Stackoverflow.com/users/3976240", "pm_score": 0, "selected": false, "text": "c-X ; git clone https://gitlab.com/python-mode-devs/python-mode.git" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
362,544
<p>I was trying to find online some exercises to practice scaling techniques (memchached, SQL Optimization, sharding dbs), but I could only find descriptions of these techniques, not any project on which to try them.</p> <p>This link with <a href="http://www.slideshare.net/Georgio_1999/how-to-scale-your-web-app" rel="nofollow noreferrer">slides on scaling techniques</a>, is an interesting one, as it sums up some tools to achieve scalability quite well.</p> <p>Is there a projecteuler kind of site for these kind of activities? Or at least some excercises (such as a downloadable ASP.NET/PHP site with obvious slowdowns, concurrency issues, subtle bugs) for people to try and learn how to fight this issue?</p>
[ { "answer_id": 393769, "author": "James Brady", "author_id": 29903, "author_profile": "https://Stackoverflow.com/users/29903", "pm_score": 1, "selected": false, "text": "memcached" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4749/" ]
362,548
<p>I am trying to find the best practice for generating and outputting html which would require a database query first to obtain the info. Currently in the aspx page I have a div with runat server:</p> <pre><code>&lt;div runat="server" id="leaflet"&gt;&lt;/div&gt; </code></pre> <p>Now just as a start to do a bit of testing I have a method that runs on page_load that basically does:</p> <pre><code>private void BuildLeaflet(string qnid) { //gets leaflet details QueryLeafletDetails(); //return concatenated content string leaflet.InnerHtml "&lt;h1&gt;" + dr["LSC Descriptor"] + "&lt;/h1&gt;"; } </code></pre> <p>In the real solution the return is a concatenation of about 10 fields some very long as they are content. </p> <p>I don't by any means think this is the best solution, but what is? A StringBuilder? Can I Write Each Part in turn to the site avoiding the concatenation in the method? Is the server div even best?</p> <p>Edit: Forgot to put some of my content sections have simple (limited) html in them already such as paragraph, list... This allows me to easily produce documents for web and printing, I just use different stylesheets.</p>
[ { "answer_id": 362558, "author": "Vilx-", "author_id": 41360, "author_profile": "https://Stackoverflow.com/users/41360", "pm_score": 3, "selected": true, "text": "<asp:Literal runat=\"server\" enableViewState=\"false\" id=\"leaflet\" /> <asp:Literal />" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
362,555
<p><code>FromIp</code> contains <code>"192.168.1.1"</code>. I want to get the last number, but I can't figure out what's wrong here:</p> <pre><code> Dim str As String str = FromIP.Text.Substring(FromIP.Text.LastIndexOf("."), FromIP.Text.Length).ToString() MessageBox.Show(FromIP.Text.Length) </code></pre>
[ { "answer_id": 362562, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 3, "selected": true, "text": " Dim FromIp As String = \"192.168.1.1\"\n Dim str As String\n str = FromIp.Substring(FromIp.LastIndexOf(\".\") + 1).ToString()\n MessageBox.Show(str)\n Dim FromIp As String = \"192.168.1.1\"\n Dim IpPart As String() = FromIp.Split(\".\")\n MessageBox.Show(IpPart(3))\n" }, { "answer_id": 362566, "author": "Marcel Jackwerth", "author_id": 28401, "author_profile": "https://Stackoverflow.com/users/28401", "pm_score": 0, "selected": false, "text": "txt.Substring(IndexOf, txt.Length - IndexOf)" }, { "answer_id": 362571, "author": "lakshmanaraj", "author_id": 44541, "author_profile": "https://Stackoverflow.com/users/44541", "pm_score": 1, "selected": false, "text": "FromIP.Text.LastIndexOf(\".\") + 1 \n FromIP.Text.LastIndexOf(\".\") \n FromIP.TextLength-FromIP.Text.LastIndexOf(\".\") \n FromIP.TextLength\n" }, { "answer_id": 362572, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "String.Substring(int, int)" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,556
<p>i'm having an issue with creating a query in oracle which doesnt seem to want to join on missing values </p> <p>the table i have is this:</p> <pre><code>table myTable(refnum, contid, type) values are: 1, 10, 90000 2, 20, 90000 3, 30, 90000 4, 20, 10000 5, 30, 10000 6, 10, 20000 7, 20, 20000 8, 30, 20000 </code></pre> <p>a break down of the fields i'm after is this:</p> <pre><code>select a.refnum from myTable a where type = 90000 select b.refnum from myTable b where type = 10000 and contid in (select contid from myTable where type = 90000) select c.refnum from myTable c where type = 20000 and contid in (select contid from myTable where type = 90000) </code></pre> <p>the outcome of the query i'm after is this:</p> <pre><code>a.refnum, b.refnum, c.refnum </code></pre> <p>i thought this would work:</p> <pre><code>select a.refnum, b.refnum, c.refnum from myTable a left outer join myTable b on (a.contid = b.contid) left outer join myTable c on (a.contid = c.contid) where a.id_tp_cd = 90000 and b.id_tp_cd = 10000 and c.id_tp_cd = 20000 </code></pre> <p>so the values should be:</p> <pre><code>1, null, 6 2, 4, 7 3, 5, 8 </code></pre> <p>but its only returning:</p> <pre><code>2, 4, 7 3, 5, 8 </code></pre> <p>i thought left joins would show all values in the left and create a null for the right.</p> <p>help :(</p>
[ { "answer_id": 362569, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 6, "selected": true, "text": "and b.id_tp_cd = 10000\nand c.id_tp_cd = 20000\n select a.refnum, b.refnum, c.refnum\nfrom myTable a \nleft outer join myTable b on (a.contid = b.contid and b.id_tp_cd = 10000) \nleft outer join myTable c on (a.contid = c.contid and c.id_tp_cd = 20000) \nwhere a.id_tp_cd = 90000\n" }, { "answer_id": 7775367, "author": "Trevor North", "author_id": 929796, "author_profile": "https://Stackoverflow.com/users/929796", "pm_score": 2, "selected": false, "text": "select a.refnum, b.refnum, c.refnum\nfrom myTable a, mytable b, mytable c\nwhere a.contid=b.contid(+)\nand a.contid=c.contid(+)\nand a.type = 90000\nand b.type(+) = 10000\nand c.type(+) = 20000;\n\n\nREFNUM REFNUM REFNUM\n---------- ---------- ----------\n 1 6\n 2 4 7\n 3 5 8\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21180/" ]
362,560
<p>In a nutshell: I want to do the same thing "Dependency Walker" does.</p> <p>Is there any Win32 API function which can enumerate the dependencies of a EXE and/or DLL file?</p> <p>And is there any safe way to detect dependencies on ActiveX classes? (I doubt it is possible, but who knows ...)</p> <p><strong>EDIT:</strong> I'm aware of available tools which provide the same core functionality (Dependency Walker, ProcessExplorer, AQTime, ...) but I want to create my own program which dumps a text file containing the required modules. </p>
[ { "answer_id": 362655, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 3, "selected": false, "text": "dumpbin /imports some.exe\n" }, { "answer_id": 46087150, "author": "Ed Williams", "author_id": 4651886, "author_profile": "https://Stackoverflow.com/users/4651886", "pm_score": 0, "selected": false, "text": " private static HashSet<string> ReferencedAssemblies = new HashSet<string>();\n\n ...\n OutputDependencies(Assembly.GetAssembly(typeof(Program)), 0);\n ...\n\n static void OutputDependencies(Assembly assembly, int indent)\n {\n if (assembly == null) return;\n\n Console.WriteLine(new String(' ', indent * 4) + assembly.FullName);\n if (!ReferencedAssemblies.Contains(assembly.FullName))\n {\n ReferencedAssemblies.Add(assembly.FullName);\n\n foreach (var childAssembly in assembly.GetReferencedAssemblies())\n {\n OutputDependencies(Assembly.Load(childAssembly.FullName), indent + 1);\n }\n }\n }\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23368/" ]
362,570
<p>I am using Carbide (just upgraded to 2.0) to develop an S60 3rd Edition application.</p> <p>I would like to know the easiest way to change the icon (both the application icon on the device menu <strong>and</strong> the icon at the top left of the main view) because I have the need to skin my application in many different ways as easily as possible.</p> <p>All my efforts with messing around with .mif files have so far failed. I have a 44x44 .svg icon I made with Illustrator, could someone please help me in the right direction?</p> <p>Thanks!</p>
[ { "answer_id": 368093, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 3, "selected": true, "text": "CEikStatusPane* sp=iEikonEnv->AppUiFactory()->StatusPane();\nCAknContextPane* cp=(CAknContextPane *)sp->ControlL(TUid::Uid(EEikStatusPaneUidContext));\n_LIT(KContextBitMapFile, \"my_bitmap_file.mbm\");\nCFbsBitmap* bitmap = iEikonEnv->CreateBitmapL(KContextBitMapFile, EMbmBitmap);\nCleanupStack::PushL(bitmap);\nCFbsBitmap* bitmapmask = iEikonEnv->CreateBitmapL(KContextBitMapFile, EMbmBitmapMask);\nCleanupStack::PushL(bitmapmask);\ncp->SetPicture(bitmap, bitmapmask);\nCleanupStack::Pop(); // bitmapmask\nCleanupStack::Pop(); // bitmap\nDrawNow();\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33604/" ]
362,586
<p>I am trying to use the Data View Web Part in Sharepoint. There are many articles on the web related to populating it with data. My question is, what if the data source is empty? Is there a way to display a default message in this scenario?</p>
[ { "answer_id": 366807, "author": "Bjørn Furuknap", "author_id": 28382, "author_profile": "https://Stackoverflow.com/users/28382", "pm_score": 3, "selected": true, "text": " <xsl:variable name=\"dvt_IsEmpty\" select=\"$dvt_RowCount = 0\" />\n <xsl:choose>\n <xsl:when test=\"$dvt_IsEmpty\">\n <xsl:call-template name=\"dvt_1.empty\" />\n </xsl:when>\n <xsl:otherwise><!-- Do stuff if not empty --></xsl:otherwise>\n\n<xsl:template name=\"dvt_1.empty\"><!-- Default template from SPD -->\n <xsl:variable name=\"dvt_ViewEmptyText\">There are no items to show in this view.</xsl:variable>\n <table border=\"0\" width=\"100%\">\n <tr>\n <td class=\"ms-vb\">\n <xsl:value-of select=\"$dvt_ViewEmptyText\" />\n </td>\n </tr>\n </table>\n</xsl:template>\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,603
<p>How do I set a disabled TextBox's current text color to be the same as its current background color in C#?</p> <p>Simply doing txtLala.ForeColor = txtLala.BackColor does not seems to work.</p>
[ { "answer_id": 362608, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 0, "selected": false, "text": "txtLala.BackColor = System.Drawing.SystemColors.Info;\ntxtLala.ForeColor = txtLala.BackColor;\n .Visible = false Enabled = false" }, { "answer_id": 362616, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 2, "selected": false, "text": "txtLala.Text = \"Red\";\ntxtLala.BackColor = System.Drawing.Color.Red;\ntxtLala.ForeColor = txtLala.BackColor;\ntxtLala.ReadOnly = true;\n color readonly txtLala.Attributes.Add(\"style\",\"background-color:Red;color:Red\");\n txtLala.Visible = False;\n txtLala.Enabled = false;\n ReadOnly Visible = False Enabled = false" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,614
<p>How do I call onclick on a radiobutton list using javascript?</p>
[ { "answer_id": 362634, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 5, "selected": false, "text": "<input type=\"radio\" onclick=\"alert('hello');\"/>\n foreach(ListItem RadioButton in RadioButtons){\n RadioButton.Attributes.Add(\"onclick\", \"alert('hello');\");\n}\n" }, { "answer_id": 362643, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 4, "selected": false, "text": "onclick <html>\n <head>\n <script type=\"text/javascript\">\n window.onload = function() {\n\n var ex1 = document.getElementById('example1');\n var ex2 = document.getElementById('example2');\n var ex3 = document.getElementById('example3');\n\n ex1.onclick = handler;\n ex2.onclick = handler;\n ex3.onclick = handler;\n\n }\n\n function handler() {\n alert('clicked');\n }\n </script>\n </head>\n <body>\n <input type=\"radio\" name=\"example1\" id=\"example1\" value=\"Example 1\" />\n <label for=\"example1\">Example 1</label>\n <input type=\"radio\" name=\"example2\" id=\"example2\" value=\"Example 2\" />\n <label for=\"example1\">Example 2</label>\n <input type=\"radio\" name=\"example3\" id=\"example3\" value=\"Example 3\" />\n <label for=\"example1\">Example 3</label>\n </body>\n</html>\n" }, { "answer_id": 8244315, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 5, "selected": false, "text": "click() document.getElementById(\"radioButton\").click()\n $(\"#radioButton\").click()\n angular.element('#radioButton').trigger('click')\n" }, { "answer_id": 44079158, "author": "saim2025", "author_id": 5672979, "author_profile": "https://Stackoverflow.com/users/5672979", "pm_score": 2, "selected": false, "text": "<div id=\"variant\">\n<label><input type=\"radio\" name=\"toggle\" class=\"radio\" value=\"19,99€\"><span>A</span></label>\n<label><input type=\"radio\" name=\"toggle\" class=\"radio\" value=\"<<<\"><span>B</span></label>\n<label><input type=\"radio\" name=\"toggle\" class=\"radio\" value=\"xxx\"><span>C</span></label>\n<p id=\"price\"></p>\n $(document).ready(function () {\n $('.radio').click(function () {\n document.getElementById('price').innerHTML = $(this).val();\n });\n\n });\n" }, { "answer_id": 55315850, "author": "Daniela", "author_id": 6483694, "author_profile": "https://Stackoverflow.com/users/6483694", "pm_score": 3, "selected": false, "text": "Hi, I think all of the above might work. In case what you need is simple, I used:\n\n<body>\n <div class=\"radio-buttons-choice\" id=\"container-3-radio-buttons-choice\">\n <input type=\"radio\" name=\"one\" id=\"one-variable-equations\" onclick=\"checkRadio(name)\"><label>Only one</label><br>\n <input type=\"radio\" name=\"multiple\" id=\"multiple-variable-equations\" onclick=\"checkRadio(name)\"><label>I have multiple</label>\n </div>\n\n<script>\nfunction checkRadio(name) {\n if(name == \"one\"){\n console.log(\"Choice: \", name);\n document.getElementById(\"one-variable-equations\").checked = true;\n document.getElementById(\"multiple-variable-equations\").checked = false;\n\n } else if (name == \"multiple\"){\n console.log(\"Choice: \", name);\n document.getElementById(\"multiple-variable-equations\").checked = true;\n document.getElementById(\"one-variable-equations\").checked = false;\n }\n}\n</script>\n</body>" }, { "answer_id": 57849804, "author": "Roshna Omer", "author_id": 6914806, "author_profile": "https://Stackoverflow.com/users/6914806", "pm_score": 0, "selected": false, "text": "click() function KeyPressed(sender, eventArgs) {\n var button = $find(\"<%= RadButton1.ClientID %>\");\n button.click();\n }\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,618
<p>Among the data my application sends to a third-party SOA server are complex XMLs. The server owner does provide the XML schemas (<code>.xsd</code>) and, since the server rejects invalid XMLs with a meaningless message, I need to validate them locally before sending.</p> <p>I could use a stand-alone XML schema validator but they are slow, mainly because of the time required to parse the schema files. So I wrote my own schema validator (in Java, if that matters) in the form of an <em>HTTP Server</em> which caches the already parsed schemas.</p> <p>The problem is: many things can go wrong in the course of the validation process. Other than unexpected exceptions and successful validation:</p> <ul> <li>the server may not find the schema file specified</li> <li>the file specified may not be a valid schema file</li> <li>the XML is invalid against the schema file</li> </ul> <p>Since it's an HTTP Server I'd like to provide the client with meaningful <em>status codes</em>. Should the server answer with a <em>400</em> error (<em>Bad request</em>) for all the above cases? Or they have nothing to do with HTTP and it should answer <em>200</em> with a message in the body? Any other suggestion?</p> <p><em>Update</em>: the main application is written in <em>Ruby</em>, which doesn't have a good xml schema validation library, so a separate validation server is not over-engineering.</p>
[ { "answer_id": 362625, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 2, "selected": false, "text": "400 Bad request X-Parse-Error: 10451" }, { "answer_id": 362734, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": -1, "selected": false, "text": "X-Validation-Result: true/false" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23193/" ]
362,628
<p>I am calling 4-5 scripts from a file at once. But I need to give only one input to the file in the first sql that I am calling.</p> <p>That input will be the input for all the other sql files I have called after the first one.</p> <p>Is there any way to do that?</p> <p>please help.</p>
[ { "answer_id": 362652, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "create view view1 as select * from table1;\ncreate view view2 as select * from view2;\ncreate view view3 as select * from view3;\ncreate view view4 as select * from view4;\nselect * from view4\n" }, { "answer_id": 363149, "author": "James Piggot", "author_id": 28213, "author_profile": "https://Stackoverflow.com/users/28213", "pm_score": 0, "selected": false, "text": "DELIMITER // [1]\n\nCREATE PROCEDURE payment [2]\n(payment_amount DECIMAL(6,2),\npayment_seller_id INT)\nBEGIN\nDECLARE n DECIMAL(6,2);\nSET n = payment_amount - 1.00;\nINSERT INTO Moneys VALUES (n, CURRENT_DATE);\nIF payment_amount > 1.00 THEN\nUPDATE Sellers\nSET commission = commission + 1.00\nWHERE seller_id = payment_seller_id;\nEND IF;\nEND;\n//\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,632
<p>the other day a colleague of mine stated that using static classes can cause performance issues on multi-core systems, because the static instance cannot be shared between the processor caches. Is that right? Are there some benchmarks around proofing this statement? This statement was made in the context of .Net development (with C#) related discussion, but it sounds to me like a language and environment independent problem.</p> <p>Thx for your comments.</p>
[ { "answer_id": 362667, "author": "bangroot", "author_id": 45693, "author_profile": "https://Stackoverflow.com/users/45693", "pm_score": 2, "selected": false, "text": "Foo setBar(true)" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43633/" ]
362,670
<p>I am dropping something in a ListView in WPF. I need to know the item in the (X,Y) position I am dropping. How can I do this?</p> <hr> <p>The WPF ListView doesn't have GetItemAt. I return to my original problem.</p>
[ { "answer_id": 363572, "author": "Mariano", "author_id": 12514, "author_profile": "https://Stackoverflow.com/users/12514", "pm_score": 4, "selected": true, "text": "private int GetCurrentIndex(GetPositionDelegate getPosition)\n{\n int index = -1;\n for (int i = 0; i < clasesListView.Items.Count; ++i)\n {\n ListViewItem item = GetListViewItem(i);\n if (this.IsMouseOverTarget(item, getPosition))\n {\n index = i;\n break;\n }\n }\n return index;\n}\n\nprivate bool IsMouseOverTarget(Visual target, GetPositionDelegate getPosition)\n{\n Rect bounds = VisualTreeHelper.GetDescendantBounds(target);\n Point mousePos = getPosition((IInputElement)target);\n return bounds.Contains(mousePos);\n}\n\ndelegate Point GetPositionDelegate(IInputElement element);\n\nListViewItem GetListViewItem(int index)\n{\n if (clasesListView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)\n return null;\n\n return clasesListView.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;\n}\n" }, { "answer_id": 363584, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 3, "selected": false, "text": "FrameworkElement element = (FrameworkElement)e.OriginalSource;\n\nListViewItem lvi = (ListViewItem)listView1.ItemContainerGenerator.ContainerFromItem(element.DataContext);\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12514/" ]
362,674
<p>I am trying to work out the overhead of the ASP.NET auto-naming of server controls. I have a page which contains 7,000 lines of HTML rendered from hundreds of nested ASP.NET controls, many of which have id / name attributes that are hundreds of characters in length. </p> <p>What I would ideally like is something that would extract every HTML attribute value that begins with "ctl00" into a list. The regex Find function in Notepad++ would be perfect, if only I knew what the regex should be?</p> <p>As an example, if the HTML is:<br> &lt;input name="ctl00$Header$Search$Keywords" type="text" maxlength="50" class="search" /&gt;</p> <p>I would like the output to be something like:<br> name="ctl00$Header$Search$Keywords"<br> A more advanced search might include the element name as well (e.g. control type):<br> input|name="ctl00$Header$Search$Keywords" </p> <p>In order to cope with both Id and Name attributes I will simply rerun the search looking for Id instead of Name (i.e. I don't need something that will search for both at the same time).</p> <p>The final output will be an excel report that lists the number of server controls on the page, and the length of the name of each, possibly sorted by control type.</p>
[ { "answer_id": 362709, "author": "Tim Pietzcker", "author_id": 20670, "author_profile": "https://Stackoverflow.com/users/20670", "pm_score": 1, "selected": false, "text": "\\w+\\s*=\\s*\"ctl00[^\"]*\"\n name=\"ctl00test\" attr = \"ctl00longer text\"" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45698/" ]
362,727
<p>How do you go about building a complete keyboard-accessible web application? Assuming that this for a controlled deployment environment (for use within an org) where access is restricted (not open to public). </p> <p>Update: Forgot to mention that this is aimed at improving data entry efficiency and is not disability-related.</p> <p>Update 2: Would it make sense to use Flash for the entire application? Considering that the environment is browser based and NOT web-based?</p>
[ { "answer_id": 365566, "author": "Jeff.Crossett", "author_id": 44746, "author_profile": "https://Stackoverflow.com/users/44746", "pm_score": 2, "selected": false, "text": "shortcut.add(\"Ctrl+Shift+X\",function() {\n alert(\"Hi there!\");\n});\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17404/" ]
362,730
<p>Somewhere along the line I picked up the notion that using iframes is 'bad practice'. </p> <p>Is this true? What are the pros/cons of using them?</p>
[ { "answer_id": 362752, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 6, "selected": false, "text": "iframe iframe iframe iframe XmlHttpRequest iframe XmlHttpRequest iframe" }, { "answer_id": 17141400, "author": "mel3kings", "author_id": 2023728, "author_profile": "https://Stackoverflow.com/users/2023728", "pm_score": 3, "selected": false, "text": "Document.write(); Document.write()" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
362,737
<p>I am developing an interface that takes as input an encrypted byte stream -- probably a very <em>large</em> one -- that generates output of more or less the same format.</p> <p>The input format is this:</p> <pre><code>{N byte envelope} - encryption key IDs &amp;c. {X byte encrypted body} </code></pre> <p>The output format is the same.</p> <p>Here's the usual use case (heavily pseudocoded, of course):</p> <pre><code>Message incomingMessage = new Message (inputStream); ProcessingResults results = process (incomingMessage); MessageEnvelope messageEnvelope = new MessageEnvelope (); // set message encryption options &amp;c. ... Message outgoingMessage = new Message (); outgoingMessage.setEnvelope (messageEnvelope); writeProcessingResults (results, message); message.writeToOutput (outputStream); </code></pre> <p>To me, it seems to make sense to use the same object to encapsulate this behaviour, but I'm at a bit of a loss as to how I should go about this. It isn't practical to load all of the encrypted body in at a time; I need to be able to stream it (so, I'll be using some kind of input stream filter to decrypt it) but at the same time I need to be able to write out new instances of this object. What's a good approach to making this work? What should <code>Message</code> look like internally?</p>
[ { "answer_id": 362792, "author": "Gunnar Steinn", "author_id": 33468, "author_profile": "https://Stackoverflow.com/users/33468", "pm_score": 0, "selected": false, "text": "ConcurrentLinkedQueue<String> outputQueue = new ConcurrentLinkedQueue<String>();\n...\n\nprivate void readInput(Stream stream) {\n String str;\n while ((str = stream.readLine()) != null) {\n outputQueue.put(processStream(str));\n }\n}\n\nprivate String processStream(String input) {\n // do something\n return output;\n}\n\nprivate void writeOutput(Stream out) {\n while (true) {\n while (outputQueue.peek() == null) {\n sleep(100);\n }\n\n String msg = outputQueue.poll();\n out.write(msg);\n }\n}\n" }, { "answer_id": 407449, "author": "iny", "author_id": 27067, "author_profile": "https://Stackoverflow.com/users/27067", "pm_score": 0, "selected": false, "text": "Message message = new Message(inputStream);\nresults = process(message.getInputStream());\n Message message = new Message(outputStream);\nwriteContent(message.getOutputStream());\n" }, { "answer_id": 463015, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 1, "selected": false, "text": "InputStream decrypted = new DecryptingStream(inputStream, decryptionParameters);\n...\nOutputStream encrypted = new EncryptingStream(outputSream, encryptionOptions);\n read() write()" }, { "answer_id": 466657, "author": "Kothar", "author_id": 37416, "author_profile": "https://Stackoverflow.com/users/37416", "pm_score": 0, "selected": false, "text": "class Message {\n InputStream input;\n Envelope envelope;\n\n public Message(InputStream input) {\n assert input != null;\n this.input = input;\n }\n\n public Message(Envelope envelope) {\n assert envelope != null;\n this.envelope = envelope;\n }\n\n public Envelope getEnvelope() {\n if (envelope == null && input != null) {\n // Read envelope from beginning of stream\n envelope = new Envelope(input);\n }\n return envelope\n }\n\n public InputStream read() {\n assert input != null\n\n // Initialise the decryption stream\n return new DecryptingStream(input, getEnvelope().getEncryptionParameters());\n }\n\n public OutputStream write(OutputStream output) {\n // Write envelope header to output stream\n getEnvelope().write(output);\n\n // Initialise the encryption\n return new EncryptingStream(output, getEnvelope().getEncryptionParameters());\n }\n}\n public void process(InputStream input, OutputStream output) {\n byte[] buffer = new byte[1024];\n int read;\n while ((read = input.read(buffer) > 0) {\n // Process buffer, writing to output as you go.\n }\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23309/" ]
362,739
<p>Is there anyway how to check which website is being used with that pool without browsing each website and checks its assigned pool?</p> <p>I have approximately 35 websites and I can't afford browsing the websites one by one....</p> <p>Thanks</p>
[ { "answer_id": 362792, "author": "Gunnar Steinn", "author_id": 33468, "author_profile": "https://Stackoverflow.com/users/33468", "pm_score": 0, "selected": false, "text": "ConcurrentLinkedQueue<String> outputQueue = new ConcurrentLinkedQueue<String>();\n...\n\nprivate void readInput(Stream stream) {\n String str;\n while ((str = stream.readLine()) != null) {\n outputQueue.put(processStream(str));\n }\n}\n\nprivate String processStream(String input) {\n // do something\n return output;\n}\n\nprivate void writeOutput(Stream out) {\n while (true) {\n while (outputQueue.peek() == null) {\n sleep(100);\n }\n\n String msg = outputQueue.poll();\n out.write(msg);\n }\n}\n" }, { "answer_id": 407449, "author": "iny", "author_id": 27067, "author_profile": "https://Stackoverflow.com/users/27067", "pm_score": 0, "selected": false, "text": "Message message = new Message(inputStream);\nresults = process(message.getInputStream());\n Message message = new Message(outputStream);\nwriteContent(message.getOutputStream());\n" }, { "answer_id": 463015, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 1, "selected": false, "text": "InputStream decrypted = new DecryptingStream(inputStream, decryptionParameters);\n...\nOutputStream encrypted = new EncryptingStream(outputSream, encryptionOptions);\n read() write()" }, { "answer_id": 466657, "author": "Kothar", "author_id": 37416, "author_profile": "https://Stackoverflow.com/users/37416", "pm_score": 0, "selected": false, "text": "class Message {\n InputStream input;\n Envelope envelope;\n\n public Message(InputStream input) {\n assert input != null;\n this.input = input;\n }\n\n public Message(Envelope envelope) {\n assert envelope != null;\n this.envelope = envelope;\n }\n\n public Envelope getEnvelope() {\n if (envelope == null && input != null) {\n // Read envelope from beginning of stream\n envelope = new Envelope(input);\n }\n return envelope\n }\n\n public InputStream read() {\n assert input != null\n\n // Initialise the decryption stream\n return new DecryptingStream(input, getEnvelope().getEncryptionParameters());\n }\n\n public OutputStream write(OutputStream output) {\n // Write envelope header to output stream\n getEnvelope().write(output);\n\n // Initialise the encryption\n return new EncryptingStream(output, getEnvelope().getEncryptionParameters());\n }\n}\n public void process(InputStream input, OutputStream output) {\n byte[] buffer = new byte[1024];\n int read;\n while ((read = input.read(buffer) > 0) {\n // Process buffer, writing to output as you go.\n }\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44973/" ]
362,740
<p>For years and years, I've tried to understand the <a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4" rel="noreferrer">part</a> of Java specification that deals with memory model and concurrency. I have to admit that I've failed miserably. Yes' I understand about locks and "synchronized" and wait() and notify(). And I can use them just fine, thank you. I even have a vague idea about what "volatile" does. But all of that was not derived from the language spec - rather from general experience.</p> <p>Here are two sample questions that I am asking. I am not so much interested in particular answers, as I need to understand how the answers are derived from the spec (or may be how I conclude that the spec has no answer).</p> <ul> <li>What does "volatile" do, exactly?</li> <li>Are writes to variable atomic? Does it depend on variable's type?</li> </ul>
[ { "answer_id": 362804, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "Thread 1: foo.x = 257;\nThread 2: int y = foo.x;\n y x" }, { "answer_id": 362844, "author": "Michael Borgwardt", "author_id": 16883, "author_profile": "https://Stackoverflow.com/users/16883", "pm_score": 4, "selected": false, "text": "volatile volatile long double" }, { "answer_id": 65382087, "author": "yoAlex5", "author_id": 4770877, "author_profile": "https://Stackoverflow.com/users/4770877", "pm_score": 1, "selected": false, "text": "class MainClass {\n void method1() { //<- main\n int variable1 = 1;\n Class1 variable2 = new Class1();\n\n variable2.method2();\n }\n}\n\nclass Class1 {\n static Class2 classVariable4 = new Class2();\n int instanceVariable5 = 0;\n Class2 instanceVariable6 = new Class2();\n\n void method2() {\n int variable3 = 3;\n }\n}\n\nclass Class2 { }\n thread stack heap" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,748
<p>I have a product registration form that allows the user to add additional product fields by clicking "add product". When the user clicks add product, Javascript creates new product field in an existing div.</p> <p>I currently allow up to 10 products to be added on the form, so I setup a div structure like this:</p> <pre><code>&lt;div id="product1"&gt;&lt;/div&gt; &lt;div id="product2"&gt;&lt;/div&gt; &lt;div id="product3"&gt;&lt;/div&gt; etc... </code></pre> <p>I have one empty div for each product box that may be added by the user. I use Javascript's innerHTML method to populate the divs.</p> <p>On to my question: How can I allow an unlimited number of products to be added at once? Obviously, my current setup won't support this since I need to hard code separate div's for each potential product so Javascript has a specific place to drop more data. </p> <p>NOTE: Before someone suggests using a single div and appending new data into it, that doesn't work. Sadly, all data entered in previous fields is cleared whenever another field is added to the div by appending data like this: </p> <pre><code>document.getElementById('product').innerHTML += &lt;input name="product"&gt; </code></pre>
[ { "answer_id": 362782, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 3, "selected": true, "text": "$(\"someContainerDiv\").insert(new Element(\"div\", { id: \"product_\"+prodId, 'class':'prod' }))\n $(\"product_\"+prodId).innerHTML" }, { "answer_id": 362811, "author": "Jay", "author_id": 41690, "author_profile": "https://Stackoverflow.com/users/41690", "pm_score": 0, "selected": false, "text": "output = '';\nfor(i in products){\n output += '<div id=\"product_' + products[i].id + '\">';\n output += '<input type=\"text\" name=\"products[' + products[i].id + '][name]\">';\n output += '<input type=\"text\" name=\"products[' + products[i].id + '][price]\">';\n output += '</div>';\n}\n$('#products_list').append(output);\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26180/" ]
362,760
<p>I have two questions.</p> <ol> <li><p>Do <code>realloc()</code> and <code>memcpy()</code> copy the entries in an array to another in a way faster than just iterating on each element <code>O(N)</code> ? If the answer is yes then what do you think is its complexity ?</p></li> <li><p>If the size allocated is smaller than the original size, does <code>realloc()</code> copy the entries to somewhere else or just leave them as they are decreasing the size of the array ?</p></li> </ol>
[ { "answer_id": 362841, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": false, "text": "memcpy memcpy realloc realloc" }, { "answer_id": 394654, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 5, "selected": false, "text": "memcpy memcpy memcpy unsigned char *\nmemcpy(unsigned char * s1, unsigned char * s2, long size){\n long ix;\n for(ix=0; ix < size; ix++)\n s1[ix] = s2[ix];\n return s1;\n}\n MOVL LR 3,S1 LOAD S1 ADDR in Register 3\nLR 4,S2 \nMOVL 3,4,SIZE\n memcpy" }, { "answer_id": 394711, "author": "RogerV", "author_id": 48048, "author_profile": "https://Stackoverflow.com/users/48048", "pm_score": 0, "selected": false, "text": "CMPS/MOVS/SCAS/STOS\nREP, REPE, REPNE, REPNZ, REPZ\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27400/" ]
362,770
<p>My question is, if an interface that is implemented implicitly by extending a class that already implements it, should be explicitly implemented by the class, if the class wants to advertise the fact, that it fulfills the contract of that interface. </p> <p>For instance, if you want to write a class, that fulfills the contract of the interface <code>java.util.List</code>. You implement this, extending the class <code>java.util.AbstractList</code>, that already implements the interface <code>List</code>. Do you explicitly declare, that you implement List?</p> <pre><code>public class MyList extends AbstractList implements List </code></pre> <p>Or do you save typing by using the implicit way?</p> <pre><code>public class MyList extends AbstractList </code></pre> <p>Which way is considered better style? What reasons do you have to prefer one way or another? In which situations you would prefer way 1 or way 2?</p>
[ { "answer_id": 539501, "author": "Sean McCauliff", "author_id": 62720, "author_profile": "https://Stackoverflow.com/users/62720", "pm_score": 2, "selected": false, "text": "import java.io.Serializable;\n\nclass Test implements Serializable {\n class Inner extends Test {\n }\n\n public static void main(String[] argv) throws Exception {\n System.out.println(Test.class.getInterfaces().length);\n System.out.println(Inner.class.getInterfaces().length);\n }\n}\n" }, { "answer_id": 68285284, "author": "user2501323", "author_id": 2501323, "author_profile": "https://Stackoverflow.com/users/2501323", "pm_score": 1, "selected": false, "text": "public abstract class Condition extends AbstractWebCondition\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
362,790
<p>I need to get all dlls in my application root directory. What is the best way to do that?</p> <pre><code>string root = Application.StartupPath; </code></pre> <p>Or,</p> <pre><code>string root = new FileInfo(Assembly.GetExecutingAssembly().Location).FullName; </code></pre> <p>And after that,</p> <pre><code>Directory.GetFiles(root, "*.dll"); </code></pre> <p>Which way is better? Are there better ways?</p>
[ { "answer_id": 362842, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 7, "selected": true, "text": "AppDomain.CurrentDomain.BaseDirectory Application.StartupPath AppDomain.BaseDirectory" }, { "answer_id": 362858, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 5, "selected": false, "text": "string root = string.Empty;\nAssembly ass = Assembly.GetAssembly( typeof( MyApp.MyClass ) );\nif ( ass != null )\n{\n root = ass.Location;\n}\n" }, { "answer_id": 18056411, "author": "Telan Niranga", "author_id": 1684891, "author_profile": "https://Stackoverflow.com/users/1684891", "pm_score": 1, "selected": false, "text": "string path =new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName\n" }, { "answer_id": 25629062, "author": "eried", "author_id": 2278659, "author_profile": "https://Stackoverflow.com/users/2278659", "pm_score": 3, "selected": false, "text": "Environment.CurrentDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);\n var r = new List<long>();\nvar s = Stopwatch.StartNew();\n\ns.Restart();\nstring root1 = Application.StartupPath;\nr.Add(s.ElapsedTicks);\n\ns.Restart();\nstring root2 = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);\nr.Add(s.ElapsedTicks);\n\ns.Restart();\nstring root3 = Path.GetDirectoryName(new FileInfo(Assembly.GetExecutingAssembly().Location).FullName);\nr.Add(s.ElapsedTicks);\n\ns.Restart();\nstring root4 = AppDomain.CurrentDomain.BaseDirectory;\nr.Add(s.ElapsedTicks);\n\ns.Restart();\nstring root5 = Path.GetDirectoryName(Assembly.GetAssembly( typeof( Form1 ) ).Location);\nr.Add(s.ElapsedTicks);\n AppDomain.CurrentDomain.BaseDirectory" }, { "answer_id": 45823657, "author": "Someguy", "author_id": 7838665, "author_profile": "https://Stackoverflow.com/users/7838665", "pm_score": 0, "selected": false, "text": "Path.GetDirectoryName(new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath)\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41956/" ]
362,793
<p>Is there a regular expression that matches valid regular expressions? </p> <p>(I know there are several flavors of regexps. One would do.)</p>
[ { "answer_id": 365200, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 6, "selected": true, "text": "^ $ \\w ( )" }, { "answer_id": 481695, "author": "kajaco", "author_id": 30924, "author_profile": "https://Stackoverflow.com/users/30924", "pm_score": 2, "selected": false, "text": "/\\/(\\\\[^\\x00-\\x1f]|\\[(\\\\[^\\x00-\\x1f]|[^\\x00-\\x1f\\\\\\/])*\\]|[^\\x00-\\x1f\\\\\\/\\[])+\\/[gim]*/" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19734/" ]
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app" rel="noreferrer">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app" rel="noreferrer">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
[ { "answer_id": 363563, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "/etc/hosts %WINDIR%\\SYSTEM32\\DRIVERS\\ETC\\HOSTS" }, { "answer_id": 662541, "author": "Ty.", "author_id": 53390, "author_profile": "https://Stackoverflow.com/users/53390", "pm_score": 2, "selected": false, "text": "::1 localhost\n" }, { "answer_id": 2209435, "author": "westmark", "author_id": 3999, "author_profile": "https://Stackoverflow.com/users/3999", "pm_score": 0, "selected": false, "text": "Include pattern : http://localhost*\nRedirect to : http://127.0.0.1$1\n" }, { "answer_id": 7123271, "author": "Tyler Brock", "author_id": 216314, "author_profile": "https://Stackoverflow.com/users/216314", "pm_score": 3, "selected": false, "text": "local.test.com 127.0.0.1\n dscacheutil -flushcache" }, { "answer_id": 57203081, "author": "Flux", "author_id": 5916915, "author_profile": "https://Stackoverflow.com/users/5916915", "pm_score": 0, "selected": false, "text": "python manage.py runserver runserver_plus --threaded runserver" }, { "answer_id": 60596673, "author": "Muhammad Usama", "author_id": 11422896, "author_profile": "https://Stackoverflow.com/users/11422896", "pm_score": 1, "selected": false, "text": "setting.py DEBUG = False\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5978/" ]
362,822
<p>I have a dll that contains a templated class. Is there a way to export it without explicit specification?</p>
[ { "answer_id": 362924, "author": "Laserallan", "author_id": 11758, "author_profile": "https://Stackoverflow.com/users/11758", "pm_score": 3, "selected": false, "text": "typedef std::vector<int> IntVec;\n" }, { "answer_id": 46392757, "author": "Peter Driscoll", "author_id": 4139508, "author_profile": "https://Stackoverflow.com/users/4139508", "pm_score": 2, "selected": false, "text": "#ifdef XXXX_BUILD\n #define XXXX_EXPORT __declspec(dllexport)\n #define XXXX_EXTERN\n#else\n #define XXXX_EXPORT __declspec(dllimport)\n #define XXXX_EXTERN extern\n#endif\n XXXX_EXTERN template class XXXX_EXPORT YourClass<double>;\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38106/" ]
362,830
<p>I have a circular dependency between two functions. I would like each of these functions to reside in its own dll. Is it possible to build this with visual studio?</p> <pre><code>foo(int i) { if (i &gt; 0) bar(i -i); } </code></pre> <p>-> should compile into foo.dll</p> <pre><code>bar(int i) { if (i &gt; 0) foo(i - i); } </code></pre> <p>-> should compile into bar.dll</p> <p>I have created two projects in visual studio, one for foo and one for bar. By playing with the 'References' and compiling a few times, I managed to get the dll's that I want. I would like to know however whether visual studio offers a way to do this in a clean way.</p> <p>If foo changes, bar does not need to be recompiled, because I only depend on the signature of bar, not on the implementation of bar. If both dll's have the lib present, I can recompile new functionality into either of the two and the whole system still works.</p> <p>The reason I am trying this is that I have a legacy system with circular dependencies, which is currently statically linked. We want to move towards dll's for various reasons. We don't want to wait until we clean up all the circular dependencies. I was thinking about solutions and tried out some things with gcc on linux and there it is possible to do what I suggest. So you can have two shared libraries that depend on each other and can be built independent of each other.</p> <p>I know that circular dependencies are not a good thing to have, but that is not the discussion I want to have.</p>
[ { "answer_id": 363077, "author": "Keith", "author_id": 42845, "author_profile": "https://Stackoverflow.com/users/42845", "pm_score": 1, "selected": false, "text": "Public Function foo(ByVal value As C.IB) As Integer Implements C.IA.foo\n Return value.bar(Me)\nEnd Function\n Public Function bar(ByVal value As C.IA) As Integer Implements C.IB.bar\n Return value.foo(Me)\nEnd Function\n Public Interface IA\n Function foo(ByVal value As IB) As Integer\nEnd Interface\n\nPublic Interface IB\n Function bar(ByVal value As IA) As Integer\nEnd Interface\n Sub Main()\n\n Dim a As New A.A\n Dim b As New B.B\n\n a.foo(b)\n\nEnd Sub\n" }, { "answer_id": 387380, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 4, "selected": false, "text": "LoadLibrary GetProcAddress" }, { "answer_id": 1376725, "author": "zumalifeguard", "author_id": 75129, "author_profile": "https://Stackoverflow.com/users/75129", "pm_score": 0, "selected": false, "text": "// IFoo.cs: (build IFoo.dll)\n interface IFoo {\n void foo(int i);\n }\n\n public class FooFactory {\n public static IFoo CreateInstance()\n {\n return (IFoo)Activator.CreateInstance(\"Foo\", \"foo\").Unwrap();\n }\n }\n // IBar.cs: (build IBar.dll)\n interface IBar {\n void bar(int i);\n }\n\n public class BarFactory {\n public static IBar CreateInstance()\n {\n return (IBar)Activator.CreateInstance(\"Bar\", \"bar\").Unwrap();\n }\n }\n // foo.cs: (build Foo.dll, references IFoo.dll and IBar.dll)\n public class Foo : IFoo {\n void foo(int i) {\n IBar objBar = BarFactory.CreateInstance();\n if (i > 0) objBar.bar(i -i);\n }\n }\n // bar.cs: (build Bar.dll, references IBar.dll and IFoo.dll)\n public class Bar : IBar {\n void bar(int i) {\n IFoo objFoo = FooFactory.CreateInstance();\n if (i > 0) objFoo.foo(i -i);\n }\n }\n IFoo objFoo = FooFactory.CreateInstance();\n IFoo objFoo = (IFoo)Activator.CreateInstance(\"Foo\", \"foo\").Unwrap();\n" }, { "answer_id": 1376755, "author": "ijprest", "author_id": 130205, "author_profile": "https://Stackoverflow.com/users/130205", "pm_score": 0, "selected": false, "text": "// foo.h\n#if defined(COMPILING_BAR_DLL)\ninline void foo(int x) \n{\n HMODULE hm = LoadLibrary(_T(\"foo.dll\");\n typedef void (*PFOO)(int);\n PFOO pfoo = (PFOO)GetProcAddress(hm, \"foo\");\n pfoo(x); // call the function!\n FreeLibrary(hm);\n}\n#else\nextern \"C\" {\n__declspec(dllexport) void foo(int);\n}\n#endif\n" }, { "answer_id": 54848623, "author": "MetNP", "author_id": 1303854, "author_profile": "https://Stackoverflow.com/users/1303854", "pm_score": 2, "selected": false, "text": "g++ -shared -Wl,--out-implib=a.lib -o a.dll a.obj //without specifying b.lib \ng++ -shared -Wl,--out-implib=b.lib -o b.dll b.obj //without specifying a.lib\n a.lib b.lib g++ -shared -Wl,--out-implib=a.lib -o a.dll a.obj b.lib \ng++ -shared -Wl,--out-implib=b.lib -o b.dll b.obj a.lib\n a.dll b.dll" }, { "answer_id": 68742311, "author": "Azrael3000", "author_id": 1174988, "author_profile": "https://Stackoverflow.com/users/1174988", "pm_score": 0, "selected": false, "text": "a b a.dll b_init /FORCE:UNRESOLVED a b_init b b.lib a b.lib PRIVATE b.lib b CMakeLists.txt project(circ_dll CXX)\n\ncmake_minimum_required(VERSION 3.15)\n\nset(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)\n\nadd_library(b_init SHARED b_dll.cpp)\nset_target_properties(b_init PROPERTIES LINK_FLAGS \"/FORCE:UNRESOLVED\")\nset_target_properties(b_init PROPERTIES OUTPUT_NAME \"b\")\n\nadd_library(a SHARED a_dll.cpp)\ntarget_link_libraries(a PRIVATE b_init)\n\nadd_library(b SHARED b_dll.cpp)\ntarget_link_libraries(b a)\n\nadd_executable(main main.cpp)\ntarget_link_libraries(main a b)\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45711/" ]
362,861
<p>I'm implementing a COM interface that should return int values either <code>S_OK</code> or <code>E_FAIL</code>. I'm ok returning <code>S_OK</code> as I get that back from another call (Marshal.QueryInterface), but if I want to return a failure value what actual value do I use for <code>E_FAIL</code>?</p> <p>(It's such a basic fundamental question that it's hard to find an answer to)</p> <p>Assuming it's a specific number defined in the Win32 API, is there way to use it within .net code without declaring my own constant?</p> <p>thanks!</p> <p><strong>Update (answered below):</strong></p> <p>Maybe I'm being a complete plonker, but I'm having problems with this. According to my Platform SDK, <code>HRESULT</code> is a <code>LONG</code>, which is a 32-bit signed integer, right? So possible values –2,147,483,648 to 2,147,483,647. But 0x80004005 = 2,147,500,037 which is &gt; 2,147,483,647. What gives!?</p> <p>This means when I try to put this in my code:</p> <pre><code>const int E_FAIL = 0x80004005; </code></pre> <p>I get a compiler error <em>Cannot implicitly convert type 'uint' to 'int'</em>.</p> <p><strong>Update 2:</strong></p> <p>I'm going to declare it like this:</p> <pre><code>const int E_FAIL = -2147467259; </code></pre> <p>because if I try to do something like this:</p> <pre><code>const UInt32 E_FAIL = 0x80004005; return (Int32)E_FAIL; </code></pre> <p>I get a compiler error <em>Constant value '2147500037' cannot be converted to a 'int' (use 'unchecked' syntax to override)</em></p> <p>Phew! Who knew how tricky it would be to declare a standard return value.... Somewhere there must be a class lurking that I should have used like <strong>return Win32ReturnCodes.E_FAIL;</strong> ... <em>sigh</em></p> <p><strong>ULTIMATE SOLUTION:</strong></p> <p>I now do this by getting the (massive but very useful) HRESULT enum from <a href="http://www.pinvoke.net/default.aspx/Enums/HRESULT.html" rel="nofollow noreferrer">pinvoke.net</a> and adding it to my solution. Then use it something like this:</p> <pre><code>return HRESULT.S_OK; </code></pre>
[ { "answer_id": 362876, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 4, "selected": true, "text": " static void Main(string[] args)\n {\n UInt32 us = 0x80004005;\n Int32 s = (Int32)us;\n\n Console.WriteLine(\"Unsigned {0}\", us);\n Console.WriteLine(\"Signed {0}\", s);\n Console.WriteLine(\"Signed as unsigned {0}\", (UInt32)s);\n\n Console.ReadKey();\n }\n" }, { "answer_id": 362881, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L)\n C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\include\n" }, { "answer_id": 362890, "author": "Cédric Guillemette", "author_id": 43701, "author_profile": "https://Stackoverflow.com/users/43701", "pm_score": -1, "selected": false, "text": "typedef long HRESULT;\n\n#ifdef RC_INVOKED\n#define _HRESULT_TYPEDEF_(_sc) _sc\n#else // RC_INVOKED\n#define _HRESULT_TYPEDEF_(_sc) ((HRESULT)_sc)\n#endif // RC_INVOKED\n\n#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L)\n#define S_OK ((HRESULT)0x00000000L)\n" }, { "answer_id": 2170534, "author": "cliffwi", "author_id": 262770, "author_profile": "https://Stackoverflow.com/users/262770", "pm_score": 1, "selected": false, "text": "const int EFail = int.MinValue + 0x00004005;\n" }, { "answer_id": 13733689, "author": "Simon Giles", "author_id": 1880665, "author_profile": "https://Stackoverflow.com/users/1880665", "pm_score": 3, "selected": false, "text": "const int E_FAIL = unchecked((int)0x80004005);\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
362,872
<p>I'm getting the following exception when saving an object:</p> <blockquote> <p>Found shared references to a collection</p> </blockquote> <p>Does anyone know what this means?</p>
[ { "answer_id": 362921, "author": "Scott Cowan", "author_id": 253, "author_profile": "https://Stackoverflow.com/users/253", "pm_score": 2, "selected": false, "text": " rel Group n --- 1 User\n m ^\n | | inh\n | rel |\n --------- n Member\n" }, { "answer_id": 866477, "author": "codemonkeh", "author_id": 73027, "author_profile": "https://Stackoverflow.com/users/73027", "pm_score": 2, "selected": false, "text": "Blog blog1 = Blog.Find(1);\nBlog blog2 = new Blog();\nblog2.Entries = blog1.Entries;\nblog2.Save();\n Blog blog1 = Blog.Find(1);\nBlog blog2 = new Blog();\n\nforeach (BlogEntry entry in blog1.Entries)\n blog2.Entries.Add(entry);\nblog2.Save();\n" }, { "answer_id": 7516221, "author": "Asbjørn Ulsberg", "author_id": 61818, "author_profile": "https://Stackoverflow.com/users/61818", "pm_score": 0, "selected": false, "text": "public class Being\n{\n public string DnaSequence { get; protected set; }\n}\n\npublic class Animal : Being\n{\n public IList<Animal> Relatives { get; protected set; }\n}\n\npublic class Human : Animal\n{\n public string Name { get; protected set; }\n}\n Human Relatives Being DnaSequence Animal Relatives Human Name Relatives Human" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,902
<p>I have a two-page SSRS report. When I exported it to PDF it was taking 4 pages due to its width, where the 2nd and 4th pages were displaying one of my fields from the table. I tried to set the layout size in report properties as width=18in and height =8.5in.</p> <p>It gave me the whole table in a single page of PDF, but I am still getting the 2nd and 4th pages blank. </p> <p>Is the way I am doing it incorrect? How else can I get rid of those blank pages?</p>
[ { "answer_id": 10096554, "author": "Joshua Drake", "author_id": 19308, "author_profile": "https://Stackoverflow.com/users/19308", "pm_score": 3, "selected": false, "text": "+ &" }, { "answer_id": 17710993, "author": "Chrysalis", "author_id": 788117, "author_profile": "https://Stackoverflow.com/users/788117", "pm_score": 7, "selected": false, "text": "ConsumeContainerWhitespace True false" }, { "answer_id": 28152728, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 5, "selected": false, "text": "page ConsumeContainerWhitespace true" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,907
<p>In a custom role provider (inheriting from RoleProvider) in .NET 2.0, the IsUserInRole method has been hard-coded to always return true:</p> <pre><code>public override bool IsUserInRole(string username, string roleName) { return true; } </code></pre> <p>In an ASP.NET application configured to use this role provider, the following code returns true (as expected):</p> <pre><code>Roles.IsUserInRole("any username", "any rolename"); // results in true </code></pre> <p>However, the following code returns false:</p> <pre><code>Roles.IsUserInRole("any rolename"); // results in false </code></pre> <p>Note that User.IsInRole("any rolename") is also returning false.</p> <ol> <li>Is this the expected behavior?</li> <li>Is it incorrect to assume that the overload that only takes a role name would still be invoking the overridden IsUserInRole?</li> </ol> <p><strong>Update</strong>: Note that there doesn't seem to be an override available for the version that takes a single string, which has led to my assumption in #2.</p>
[ { "answer_id": 362990, "author": "Andrew Rollings", "author_id": 40410, "author_profile": "https://Stackoverflow.com/users/40410", "pm_score": 3, "selected": true, "text": "public static bool IsUserInRole(string roleName)\n{\n return IsUserInRole(GetCurrentUserName(), roleName);\n}\n private static string GetCurrentUserName()\n{\n IPrincipal currentUser = GetCurrentUser();\n if ((currentUser != null) && (currentUser.Identity != null))\n {\n return currentUser.Identity.Name;\n }\n return string.Empty;\n}\n IsUserInRole(string username, string roleName) if (username.Length < 1)\n {\n return false;\n }\n GetCurrentUserName()" }, { "answer_id": 2515442, "author": "FiveTools", "author_id": 185961, "author_profile": "https://Stackoverflow.com/users/185961", "pm_score": 0, "selected": false, "text": " protected void crtlLoginUserLogin_Authenticate(object sender, AuthenticateEventArgs e)\n{\n bool blnAuthenticate = false;\n string strUserName = crtlLoginUserLogin.UserName;\n\n if (IsValidEmail(strUserName))\n {\n\n //if more than one user has email address - must authenticate by username.\n\n MembershipUserCollection users = Membership.FindUsersByEmail(strUserName);\n if (users.Count > 1)\n {\n crtlLoginUserLogin.FailureText = \"We are unable to determine which account is registered to that email address. Please enter your Username to login.\";\n\n }\n else\n {\n strUserName = Membership.GetUserNameByEmail(strUserName);\n blnAuthenticate = Membership.ValidateUser(strUserName, crtlLoginUserLogin.Password);\n\n //setting the userLogin to the correct user name (only on successful authentication)\n if (blnAuthenticate)\n {\n crtlLoginUserLogin.UserName = strUserName;\n }\n\n }\n\n\n }\n else\n {\n blnAuthenticate = Membership.ValidateUser(strUserName, crtlLoginUserLogin.Password);\n }\n\n e.Authenticated = blnAuthenticate;\n\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25837/" ]
362,911
<p>I'm working with NHibernate and need to retrieve and process up to 2 million rows. Ideally, I could process each row - one at a time - without NHibernate loading all 2 million in memory at once (because, you know, that hurts). </p> <p>I'd prefer to get an IEnumerable which would call the data reader iteratively for each read so I could process the data read - then discard it. By doing it this way I save a boatload of memory, and begin processing results far faster. I could also improve performance through multithreading and/or the use of PLinq.</p> <p>Is this possible with NHibernate's ICriteria? Everything it returns seems to be IList, and fully loaded before handing the collection reference off. Why IList instead of IEnumerable?!</p> <p>I don't mean "lazy" in the traditional sense that NHibernate uses with regards to loading child or parent objects. I want a <strong>lazy IEnumerable meaning someway of getting a IEnumerable from an ICriteria object</strong>. ICriteria only has a List() method which loads the results in an ArrayList.</p>
[ { "answer_id": 362933, "author": "Strelok", "author_id": 2788, "author_profile": "https://Stackoverflow.com/users/2788", "pm_score": 0, "selected": false, "text": "public IEnumerable<YourObject> GetALotOfRows() {\n ..execute DataReader\n while(..read..) {\n yield return yourObject;\n }\n}\n" }, { "answer_id": 363240, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 0, "selected": false, "text": "Session.CreateCriteria(typeof(T)).SetFirstResult(0).SetMaxResults(1).UniqueResult<T>();\nSession.CreateCriteria(typeof(T)).SetFirstResult(1).SetMaxResults(1).UniqueResult<T>();\nSession.CreateCriteria(typeof(T)).SetFirstResult(2).SetMaxResults(1).UniqueResult<T>();\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18941/" ]
362,918
<p>I'm looking for a good pattern to resolve the following circular reference in a Windows Form application:</p> <ul> <li>Assembly 1 contains a Windows Form with an Infragistics menu item ".Show"ing a Form in Assembly 2</li> <li>Assembly 2 contains a Windows Form with an Infragistics menu item ".Show"ing a Form in Assembly 1</li> </ul> <p>The menu has generally the same items on it throughout the application. So both Assembly 1 and Assembly 2 have references to one another to "New up" one anothers' forms and .Show them.</p> <p>A note about size: My app is an existing app, so the situation is not quite as simple as the above two-assembly situation. But if I can solve the above simply (probably not implementing a , I can apply that to a much larger application (about 20 components, all with several forms that pop each other up across components).</p> <p>I've thought through a few solutions, but they all seem cumbersome. Is there a simple solution I'm missing?</p>
[ { "answer_id": 362942, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Windows.Forms;\nclass Form1 : Form\n{\n public event EventHandler Foo;\n public Form1()\n {\n Button btn = new Button();\n btn.Click += delegate { if(Foo!=null) Foo(this, EventArgs.Empty);};\n Controls.Add(btn);\n }\n}\nclass Form2 : Form\n{\n public event EventHandler Bar;\n public Form2()\n {\n Button btn = new Button();\n btn.Click += delegate { if (Bar!= null) Bar(this, EventArgs.Empty); };\n Controls.Add(btn);\n }\n}\nstatic class Program\n{\n [STAThread]\n static void Main()\n {\n ShowForm1();\n Application.Run();\n }\n static void ShowForm1()\n {\n Form1 f1 = new Form1();\n f1.Foo += delegate { ShowForm2(); };\n f1.Show();\n }\n static void ShowForm2()\n {\n Form2 f2 = new Form2();\n f2.Bar += delegate { ShowForm1(); };\n f2.Show();\n }\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45720/" ]
362,945
<p>I want to select nodes for which a specific attribute does not exist. I've tried the Not() function, but it doesn't work. Is there a way for this?</p> <p>Example: The following Xpath query:</p> <pre><code>group/msg[not(@owner)] </code></pre> <p>Should retrieve the first node but not the 2nd one. However, both SketchPath (tool to test Xpath queries) and my C# code consider that the 2 nodes are ok.</p> <pre><code>&lt;group&gt; &lt;msg id="EVENTDATA_CCFLOADED_XMLCONTEXT" numericId="14026" translate="False" topicId="302" status="translated" &gt; &lt;text&gt;Context&lt;/text&gt; &lt;comment&gt;&lt;/comment&gt; &lt;/msg&gt; &lt;msg id="EVENTDATA_CCFLOADED_XMLCONTEXT_HELP" numericId="14027" translate="False" topicId="302" status="translated" owner="EVENTDATA_CCFLOADED_XMLCONTEXT" &gt; &lt;text&gt;Provides the new data displayed in the Object.&lt;/text&gt; &lt;comment&gt;&lt;/comment&gt; &lt;/msg&gt; &lt;/group&gt; </code></pre> <hr> <p>In fact the Not() function works correctly, it's just that I had other conditions and parentheses weren't set correctly. <em>errare humanum est</em>.</p>
[ { "answer_id": 363017, "author": "Jonas Elfström", "author_id": 44620, "author_profile": "https://Stackoverflow.com/users/44620", "pm_score": 4, "selected": false, "text": "string-length(@attr)=0" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29568/" ]
362,948
<p>I spent several hours yesterday trying to digitally sign a short file using an X509 certificate (one of the "freemail" certificates from thawte). I finally got openssl to sign it as an SMIME message, but I can't successfully verify it, AND it's in the SMIME format -- I don't have access to a "sendmail" program which can actually send out the SMIME file.</p> <p>I just want to create some file that is "excerptable" via plain cut &amp; paste, like:</p> <pre><code>===BEGIN SIGNED DOCUMENT=== ===BEGIN DOCUMENT=== blah blah blah this is the plaintext ... ===END DOCUMENT=== ===BEGIN SIGNATURE=== AFab12121abadAF ... ===END SIGNATURE=== ===END SIGNED DOCUMENT=== </code></pre> <p>Alternatively I guess I could make a .zip file that contains the original file and also the signature.</p> <p>so I guess my requirements are:</p> <ol> <li>input plaintext = arbitrary file</li> <li>input signkey = from X509 certificate</li> <li>output = something I can easily email to someone else by cut&amp;paste or by attaching a single .zip file</li> <li>program = something that is free &amp; open source like openssl or gpg</li> <li>program != a magic GUI where I don't understand what's going on</li> <li>ability to easily use the program to generate output from inputs</li> <li>ability to easily extract the plaintext from the output (e.g. either directly by eye or as a component of the .zip file)</li> <li>ability to verify that the plaintext was signed by the grantee of the X509 certificate (i.e. me) and that the grantor (CA) of the certificate is a Well-Known CA... assuming that I am a rational person who keeps the certificate secure from use by other parties (otherwise someone could sign things as me).</li> </ol> <p>Is there a good tutorial for X509 certificates &amp; how they are used in practice for this stuff? I have the 2nd edition of Schneier's "Applied Cryptography" &amp; have a fair amount of experience with cryptographic algorithms + protocols, but don't know much at all about X509 and I'm really confused as to what a certificate actually is in practical terms. (In other words, "a certificate is a cryptographic assertion by the issuing party CA that the party X named in the certificate is an identity known to the CA?" AND "a certificate enables its bearer to _____")</p> <p>When I get one it shows up in Firefox's "Your Certificates" tab of the Certificate Manager, and I can export it and read it with openssl, but I want to make sure that it's not stored in any way that someone else can use it w/o knowing the cert. passphrase -- and I get really confused because it seems like some certificates only have the public key &amp; others have encrypted private keys.</p> <p>Is there a good, simple GUI wrapper around openssl that allows you to have it explain what it's doing?</p> <hr> <p><strong>edit:</strong> thawte doesn't easily let you use certificate requests directly; instead it talks to web browsers (I use Firefox) &amp; that generatese the private key and handles all the certificate protocol. So I can export that as a PKCS12 file but am not exactly sure how to use that.</p>
[ { "answer_id": 373099, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 2, "selected": false, "text": "openssl pkcs12 -in file.p12 -out file.pem\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44330/" ]
362,953
<p>I just learned about the C++ construct called "placement new". It allows you to exactly control where a pointer points to in memory. It looks like this:</p> <pre><code> #include &lt;new&gt; // Must #include this to use "placement new" #include "Fred.h" // Declaration of class Fred void someCode() { char memory[sizeof(Fred)]; void* place = memory; Fred* f = new(place) Fred(); // Create a pointer to a Fred(), // stored at "place" // The pointers f and place will be equal ... } </code></pre> <p>(example from <a href="http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10" rel="noreferrer" title="C++ FAQ Lite">C++ FAQ Lite</a>)<br><br> In this example, the <code>this</code> pointer of Fred will be equal to <code>place</code>.</p> <hr> <p>I've seen it used in our team's code once or twice. In your experience, what does this construct enable? Do other pointer languages have similar constructs? To me, it seems reminiscent of <code>equivalence</code> in FORTRAN, which allows disparate variables to occupy the same location in memory.</p>
[ { "answer_id": 362975, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 3, "selected": false, "text": "variant new" }, { "answer_id": 363707, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "template<typename T>\nclass SillyVectorExample\n{\n public:\n SillyVectorExample()\n :reserved(10)\n ,size(0)\n ,data(new char[sizeof(T) * reserved])\n {}\n void push_back(T const& object)\n {\n if (size >= reserved)\n {\n // Do Somthing.\n }\n // Place a copy of the object into the data store.\n new (data+(sizeof(T)*size)) T(object);\n ++size;\n }\n // Add other methods to make sure data is copied and dealllocated correctly.\n private:\n size_t reserved;\n size_t size;\n char* data;\n };\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6688/" ]
362,955
<p>Is it a good idea to have a factory class using generics to instantiate objects?</p> <p>Let's say I have a class Animal and some subclasses (Cat, Dog, etc):</p> <pre><code>abstract class Animal { public abstract void MakeSound(); } class Cat : Animal { public override void MakeSound() { Console.Write("Mew mew"); } } class Dog : Animal { public override void MakeSound() { Console.Write("Woof woof"); } } static class AnimalFactory { public static T Create&lt;T&gt;() where T : Animal, new() { return new T(); } } </code></pre> <p>Then in my code I would use AnimalFactory like this:</p> <pre><code>class Program { static void Main(string[] args) { Dog d = AnimalFactory.Create&lt;Dog&gt;(); d.MakeSound(); } } </code></pre>
[ { "answer_id": 363020, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "class Foo\n{\n static Foo<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value) \n {...}\n}\n\nclass Foo<TKey>\n{\n static Foo<TKey, TValue> Create<TValue>(TValue value)\n {...}\n}\n\nclass Foo<TKey, TValue>\n{\n}\n Foo.Create(x, y);\nFoo<string>.Create(y);\nnew Foo<string, int>(x, y);\n" }, { "answer_id": 363023, "author": "Scott Cowan", "author_id": 253, "author_profile": "https://Stackoverflow.com/users/253", "pm_score": 0, "selected": false, "text": "static class AnimalFactory\n{\n public static Animal Create<T>() where T : Animal\n {\n return Create<T>(\"blue\");\n }\n\n public static Animal Create<T>(string colour) where T : Animal, new()\n {\n return new T() {Colour = colour};\n }\n}\n" }, { "answer_id": 363039, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 1, "selected": false, "text": "public class Factory \n{\n public static T Create<T>() where T : ParentClass, new(String)\n {\n\n }\n}\n public class Factory \n{\n public static T Create<T>() where T : ParentClass\n {\n T child = new T(\"hi\")\n }\n}\n public class Factory \n{\n public static T Create<T>() where T : ParentClass, new()\n {\n T child;\n\n child = new T();\n\n if (child is ChildClass)\n {\n child = new ChildClass(\"hi\");\n }\n\n return child;\n }\n}\n" }, { "answer_id": 363258, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 0, "selected": false, "text": "Factory<IAwesome> awesomeFactory = new Factory<IAwesome>();\nIAwesome awesomeObject = awesomeFactory.Load(configValue);\n" }, { "answer_id": 367435, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 1, "selected": false, "text": "public interface IFactory<T>\n{\n T Create();\n}\n\npublic class DefaultConstructorFactory<T> : IFactory<T> where T : new()\n{\n public T Create()\n {\n return new T();\n }\n}\n\npublic class ActivatorFactory<T> : IFactory<T>\n{\n public T Create()\n {\n return Activator.CreateInstance<T>();\n }\n}\n\npublic class AnimalTamer<TAnimal> where TAnimal : Animal\n{\n IFactory<TAnimal> _animalFactory;\n\n public AnimalTamer(IFactory<TAnimal> animalFactory)\n {\n if(animalFactory == null)\n {\n throw new ArgumentNullException(\"animalFactory\");\n }\n\n _animalFactory= animalFactory;\n }\n\n public void PutOnShow()\n {\n var animal = _animalFactory.Create();\n\n animal.MakeSound();\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var tamer = new AnimalTamer<Tiger>(new DefaultConstructorFactory<Tiger>());\n\n tamer.PutOnShow();\n }\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
362,956
<p>Is it Oracle or MySQL or something they have built themselves?</p>
[ { "answer_id": 362970, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 10, "selected": true, "text": "anchor:cnnsi.com anchor:my.look.ca t3 t5 t6" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041/" ]
362,958
<p>I have compiled code that erroneously tries to add a number and Double.NaN. I'm wondering if it's throwing an exception that's not getting caught? Does anyone know how that situation is handled?<br> Thanks.</p>
[ { "answer_id": 362977, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 0, "selected": false, "text": "public static void main(String args[])\n{\n Double d = Double.NaN + 1.0;\n System.out.println(d);\n}\n public static final double POSITIVE_INFINITY = 1.0 / 0.0;\n public static final double NEGATIVE_INFINITY = -1.0 / 0.0;\n public static final double NaN = 0.0d / 0.0;\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45728/" ]
362,972
<p>I am new to grails.I am doing web application that uploads the image from client side and it stores that in server.</p> <p>My Gsp code is:</p> <pre><code>&lt;g:uploadForm action="saveImage"&gt; &lt;input type="file" name="image"&gt; &lt;input type="submit" value="Submit"&gt; &lt;/g:uploadForm&gt; </code></pre> <p>My saveImage action in controller is:</p> <pre><code>def saveImage={ def file = request.getFile('image') if (file &amp;&amp; !file.empty) { file.transferTo(new java.io.File("image.jpg")) flash.message = 'Image uploaded' redirect(action: 'uploadImage') } } </code></pre> <p>In this code if i upload some other files like text files it throws Exception.For that i want to check the file Extension and I want to use If loop that ensures the uploaded file is image file or not.But i dont know how to find the file extension in grails.</p> <p>Is there any other way to upload images in grails application.It has to accept only image files.</p> <p>can anyone provide help?</p> <p>thanks.</p>
[ { "answer_id": 4426671, "author": "Sree", "author_id": 540208, "author_profile": "https://Stackoverflow.com/users/540208", "pm_score": 2, "selected": false, "text": "if(params?.photo?.getContentType()=='image/jpeg' || \n params?.photo?.getContentType()=='image/gif' ||\n params?.photo?.getContentType()=='image/png' || \n params?.photo?.getContentType()=='image/bmp'\n)\n" }, { "answer_id": 9514496, "author": "fluxon", "author_id": 518976, "author_profile": "https://Stackoverflow.com/users/518976", "pm_score": 0, "selected": false, "text": "file.getContentType() image/jpeg" }, { "answer_id": 11363720, "author": "Eugene", "author_id": 735991, "author_profile": "https://Stackoverflow.com/users/735991", "pm_score": 1, "selected": false, "text": "file.getContentType() text/plain application/vnd.ms-excel" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40945/" ]
362,979
<p>As the name suggests I am trying to group rows in a datatable. To go into further detail this table has identical rows except for one field(column). Basically what I am trying to do is put all the different fields of the identical rows and put them in single field whilst deleting the other rows.</p> <p>Here is the syntax that I am currently using</p> <pre><code> Dim i As Integer Dim j As Integer For i = 0 To (ds.Tables(0).Rows.Count() - 1) Step 1 If (i &lt; ds.Tables(0).Rows.Count()) Then roleHtml = "&lt;table&gt;&lt;tr&gt;&lt;td&gt;" + ds.Tables(0).Rows(i).Item("roleName") + "&lt;/td&gt;&lt;/tr&gt;" For j = (ds.Tables(0).Rows.Count() - 1) To 0 Step -1 If (ds.Tables(0).Rows(i).Item("UserName") = ds.Tables(0).Rows(j).Item("UserName")) And (ds.Tables(0).Rows(i).Item("roleName") IsNot ds.Tables(0).Rows(j).Item("roleName")) Then roleHtml += "&lt;tr&gt;&lt;td&gt;" + ds.Tables(0).Rows(j).Item("roleName") + "&lt;/td&gt;&lt;/tr&gt;" ds.Tables(0).Rows.Remove(ds.Tables(0).Rows(j)) i -= 1 End If Next j roleHtml += "&lt;/table&gt;" ds.Tables(0).Rows(i).Item("roleName") = roleHtml End If Next i </code></pre> <p>The problem is when deleting the rows their index changes and basically the field gets thrown in another row that has nothing to do with it.</p>
[ { "answer_id": 363117, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "control" }, { "answer_id": 363342, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": true, "text": "Dim i As Integer = 0\nDim CurUser As String = \"\"\nDim CurRole As String = \"\"\nDim result As new StringBuilder()\nDim r as DataRowCollection = ds.Tables(0).Rows\n\nWhile i < r.Count\n 'Next User:'\n CurUser = r(i)(\"UserName\")\n result.AppendFormat(\"<h2>{0}</h2>\", CurUser).AppendLine()\n result.AppendLine(\"<table>\")\n\n While i < r.Count AndAlso CurUser = r(i)(\"UserName\")\n 'Next Role:'\n CurRole = r(i)(\"roleName\")\n result.AppendFormat(\"<tr><td>{0}</td></tr>\", CurRole).AppendLine()\n\n While i < r.Count AndAlso CurUser = r(i)(\"UserName\") AndAlso CurRole = r(i)(\"roleName\")\n i += 1 'Next Record: same user, role '\n End While\n 'Finished this role'\n End While\n 'Finished this user:'\n result.AppendLine(\"</table>\").AppendLine()\nEnd While\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45471/" ]
362,983
<p>I am trying to get a list of all unit test assemblies under the root of my project. I can do this as follows:</p> <pre><code>&lt;CreateItem Include="**\bin\**\*.UnitTest.*.dll"&gt; &lt;Output TaskParameter="Include" ItemName="Items"/&gt; &lt;/CreateItem&gt; </code></pre> <p>However, this will find the same DLLs multiple times since they exist in multiple sub-directories. Is there an easy way for me to normalize based on item metadata (ie. the file name and extension) so that I get a list of unique unit test DLLs? Or do I have to resort to writing my own task?</p>
[ { "answer_id": 366677, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 2, "selected": false, "text": "<NormalizeByMetadata Items=\"@(ItemsToNormalize)\" MetadataName=\"Filename\">\n <Output TaskParameter=\"NormalizedItems\" ItemName=\"MyNormalizedItems\"/>\n</NormalizeByMetadata>\n MyNormalizedItems ItemsToNormalize Filename Filename public class NormalizeByMetadata : Task\n{\n [Required]\n public ITaskItem[] Items\n {\n get;\n set;\n }\n\n [Required]\n public string MetadataName\n {\n get;\n set;\n }\n\n [Output]\n public ITaskItem[] NormalizedItems\n {\n get;\n private set;\n }\n\n public override bool Execute()\n {\n NormalizedItems = Items.Distinct(new ItemEqualityComparer(MetadataName)).ToArray();\n return true;\n }\n\n private sealed class ItemEqualityComparer : IEqualityComparer<ITaskItem>\n {\n private readonly string _metadataName;\n\n public ItemEqualityComparer(string metadataName)\n {\n Debug.Assert(metadataName != null);\n _metadataName = metadataName;\n }\n\n public bool Equals(ITaskItem x, ITaskItem y)\n {\n if (x == null || y == null)\n {\n return x == y;\n }\n\n var xMetadata = x.GetMetadata(_metadataName);\n var yMetadata = y.GetMetadata(_metadataName);\n return string.Equals(xMetadata, yMetadata);\n }\n\n public int GetHashCode(ITaskItem obj)\n {\n if (obj == null)\n {\n return 0;\n }\n\n var objMetadata = obj.GetMetadata(_metadataName);\n return objMetadata.GetHashCode();\n }\n }\n}\n" }, { "answer_id": 389137, "author": "Thomas Freudenberg", "author_id": 4747, "author_profile": "https://Stackoverflow.com/users/4747", "pm_score": 3, "selected": true, "text": "<CreateItem Include=\"**\\bin\\**\\*.UnitTest.*.dll\">\n <Output TaskParameter=\"Include\" ItemName=\"Items\"/>\n</CreateItem>\n<MSBuild.ExtensionPack.Framework.MsBuildHelper TaskAction=\"RemoveDuplicateFiles\" InputItems1=\"@(Items)\">\n <Output TaskParameter=\"OutputItems\" ItemName=\"Items\"/>\n</MSBuild.ExtensionPack.Framework.MsBuildHelper>\n" }, { "answer_id": 17323675, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<ItemGroup>\n <TestAssemblies Include=\"$(SolutionRoot)\\**\\bin\\*.Tests.dll\" />\n <TestItems Include=\"%(TestAssemblies.FileName)%(TestAssemblies.Extension)\">\n <ItemPath>%(TestAssemblies.Identity)</ItemPath>\n </TestItems>\n <DistinctTestItems Include=\"@(TestItems->Distinct())\"></DistinctTestItems>\n</ItemGroup>\n<Message Text=\"%(DistinctTestItems.ItemPath)\" Importance=\"high\" />\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5380/" ]
362,986
<p>I want to capture the screen in my code to get an image - like using the 'print screen' button on the keyboard .</p> <p>Does anyone have an idea how to do this? I have no starting point.</p>
[ { "answer_id": 363008, "author": "Gary Willoughby", "author_id": 13227, "author_profile": "https://Stackoverflow.com/users/13227", "pm_score": 8, "selected": true, "text": "CopyFromScreen() //Create a new bitmap.\nvar bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,\n Screen.PrimaryScreen.Bounds.Height,\n PixelFormat.Format32bppArgb);\n\n// Create a graphics object from the bitmap.\nvar gfxScreenshot = Graphics.FromImage(bmpScreenshot);\n\n// Take the screenshot from the upper left corner to the right bottom corner.\ngfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,\n Screen.PrimaryScreen.Bounds.Y,\n 0,\n 0,\n Screen.PrimaryScreen.Bounds.Size,\n CopyPixelOperation.SourceCopy);\n\n// Save the screenshot to the specified path that the user has chosen.\nbmpScreenshot.Save(\"Screenshot.png\", ImageFormat.Png);\n" }, { "answer_id": 25408623, "author": "Skhanpara", "author_id": 2334498, "author_profile": "https://Stackoverflow.com/users/2334498", "pm_score": 3, "selected": false, "text": "// Use this version to capture the full extended desktop (i.e. multiple screens)\n\nBitmap screenshot = new Bitmap(SystemInformation.VirtualScreen.Width, \n SystemInformation.VirtualScreen.Height, \n PixelFormat.Format32bppArgb);\nGraphics screenGraph = Graphics.FromImage(screenshot);\nscreenGraph.CopyFromScreen(SystemInformation.VirtualScreen.X, \n SystemInformation.VirtualScreen.Y, \n 0, \n 0, \n SystemInformation.VirtualScreen.Size, \n CopyPixelOperation.SourceCopy);\n\nscreenshot.Save(\"Screenshot.png\", System.Drawing.Imaging.ImageFormat.Png);\n" }, { "answer_id": 42037996, "author": "user4340666", "author_id": 4340666, "author_profile": "https://Stackoverflow.com/users/4340666", "pm_score": 1, "selected": false, "text": "Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);\nGraphics gr = Graphics.FromImage(bmp);\ngr.CopyFromScreen(0, 0, 0, 0, bmp.Size);\npictureBox1.Image = bmp;\nbmp.Save(\"img.png\",System.Drawing.Imaging.ImageFormat.Png);\n" }, { "answer_id": 46461064, "author": "trung thong hoang", "author_id": 5730247, "author_profile": "https://Stackoverflow.com/users/5730247", "pm_score": 0, "selected": false, "text": "Bitmap memoryImage;\n//Set full width, height for image\nmemoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,\n Screen.PrimaryScreen.Bounds.Height,\n PixelFormat.Format32bppArgb);\nSize s = new Size(memoryImage.Width, memoryImage.Height);\nGraphics memoryGraphics = Graphics.FromImage(memoryImage);\nmemoryGraphics.CopyFromScreen(0, 0, 0, 0, s);\nstring str = \"\";\ntry\n{\n str = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +\n @\"\\Screenshot.png\");//Set folder to save image\n}\ncatch { };\nmemoryImage.save(str);\n" }, { "answer_id": 54425546, "author": "colton7909", "author_id": 987968, "author_profile": "https://Stackoverflow.com/users/987968", "pm_score": 3, "selected": false, "text": "Screen Screen.AllScreens EnumDisplaySettings using System.Drawing;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n const int ENUM_CURRENT_SETTINGS = -1;\n\n static void Main()\n {\n foreach (Screen screen in Screen.AllScreens)\n {\n DEVMODE dm = new DEVMODE();\n dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));\n EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref dm);\n\n using (Bitmap bmp = new Bitmap(dm.dmPelsWidth, dm.dmPelsHeight))\n using (Graphics g = Graphics.FromImage(bmp))\n {\n g.CopyFromScreen(dm.dmPositionX, dm.dmPositionY, 0, 0, bmp.Size);\n bmp.Save(screen.DeviceName.Split('\\\\').Last() + \".png\");\n }\n }\n }\n\n [DllImport(\"user32.dll\")]\n public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);\n\n [StructLayout(LayoutKind.Sequential)]\n public struct DEVMODE\n {\n private const int CCHDEVICENAME = 0x20;\n private const int CCHFORMNAME = 0x20;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]\n public string dmDeviceName;\n public short dmSpecVersion;\n public short dmDriverVersion;\n public short dmSize;\n public short dmDriverExtra;\n public int dmFields;\n public int dmPositionX;\n public int dmPositionY;\n public ScreenOrientation dmDisplayOrientation;\n public int dmDisplayFixedOutput;\n public short dmColor;\n public short dmDuplex;\n public short dmYResolution;\n public short dmTTOption;\n public short dmCollate;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]\n public string dmFormName;\n public short dmLogPixels;\n public int dmBitsPerPel;\n public int dmPelsWidth;\n public int dmPelsHeight;\n public int dmDisplayFlags;\n public int dmDisplayFrequency;\n public int dmICMMethod;\n public int dmICMIntent;\n public int dmMediaType;\n public int dmDitherType;\n public int dmReserved1;\n public int dmReserved2;\n public int dmPanningWidth;\n public int dmPanningHeight;\n }\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12637/" ]
362,993
<p>I'm developing a basic dip-switch user control as a personal learning exercise. Originally I had it set up where you could declare some custom color properties on the user control, and they would be used on elements inside the control.</p> <p>However, I recenly discovered ToggleButtons, and rebuilt my control to take advantage of them. Since then, my custom color properties (SwitchColor and SwitchBkgndColor) no longer work properly. They are always rendered with the default colors, not the colors I specified when I place them in my Window. Here's some code:</p> <pre><code> &lt;UserControl x:Class="DipSwitchToggleBtn" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:SwitchesApp" Width="20" Height="40"&gt; &lt;ToggleButton Name="ToggleBtn" IsThreeState="False"&gt; &lt;ToggleButton.Template&gt; &lt;ControlTemplate&gt; &lt;Canvas Name="SwitchBkgnd" Background="{TemplateBinding app:DipSwitchToggleBtn.SwitchBkgndColor}" &gt; &lt;Rectangle Name="SwitchBlock" Fill="{TemplateBinding app:DipSwitchToggleBtn.SwitchColor}" Width="16" Height="16" Canvas.Top="22" Canvas.Left="2" /&gt; &lt;/Canvas&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="ToggleButton.IsChecked" Value="True"&gt; &lt;Trigger.EnterActions&gt; &lt;BeginStoryboard&gt; &lt;Storyboard&gt; &lt;DoubleAnimation Storyboard.TargetName="SwitchBlock" Duration="00:00:00.05" Storyboard.TargetProperty="(Canvas.Top)" To="2" /&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/Trigger.EnterActions&gt; &lt;Trigger.ExitActions&gt; &lt;BeginStoryboard&gt; &lt;Storyboard&gt; &lt;DoubleAnimation Storyboard.TargetName="SwitchBlock" Duration="00:00:00.05" Storyboard.TargetProperty="(Canvas.Top)" To="22" /&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/Trigger.ExitActions&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/ToggleButton.Template&gt; &lt;/ToggleButton&gt; &lt;/UserControl&gt; </code></pre> <p>...and the code behind:</p> <pre><code>Partial Public Class DipSwitchToggleBtn Public Property State() As Boolean Get Return Me.ToggleBtn.IsChecked End Get Set(ByVal value As Boolean) Me.ToggleBtn.IsChecked = value End Set End Property Public Sub Toggle() Me.State = Not Me.State End Sub #Region " Visual Properties " Public Shared ReadOnly SwitchColorProperty As DependencyProperty = _ DependencyProperty.Register("SwitchColor", _ GetType(Brush), GetType(DipSwitchToggleBtn), _ New FrameworkPropertyMetadata(Brushes.LightGray)) Public Property SwitchColor() As Brush Get Return GetValue(SwitchColorProperty) End Get Set(ByVal value As Brush) SetValue(SwitchColorProperty, value) End Set End Property Public Shared ReadOnly SwitchBkgndColorProperty As DependencyProperty = _ DependencyProperty.Register("SwitchBkgndColor", _ GetType(Brush), GetType(DipSwitchToggleBtn), _ New FrameworkPropertyMetadata(Brushes.Gray)) Public Property SwitchBkgndColor() As Brush Get Return GetValue(SwitchBkgndColorProperty) End Get Set(ByVal value As Brush) SetValue(SwitchBkgndColorProperty, value) End Set End Property #End Region End Class </code></pre> <p>The default Gray and LightGray show up in the VS2008 designer and the compiled app, but when I do something like this in my window:</p> <pre><code>&lt;app:DipSwitchToggleBtn x:Name="DipSwitchTest" SwitchColor="#0000FF" SwitchBkgndColor="#000000" /&gt; </code></pre> <p>The colors I specified for this instance do not get used. Everything compiles without error, but my control is still displayed with the default colors.</p> <p>I believe there is some new hierarchy at play since I nested my items in the ToggleButton.</p> <p>Any help would be appreciated. Thank you.</p>
[ { "answer_id": 363145, "author": "Bryan Anderson", "author_id": 21186, "author_profile": "https://Stackoverflow.com/users/21186", "pm_score": 2, "selected": false, "text": "Public Property SwitchBkgndColor() As Brush\n Get\n Return CType(GetValue(SwitchBkgndColorProperty), Brush)\n End Get\n\n Set(ByVal value As Brush)\n SetValue(SwitchBkgndColorProperty, value)\n End Set\nEnd Property\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/362993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/641985/" ]
363,006
<p>When I do an update and zillions of files are updated, I often miss the one that aren't merged because of conflicts. The only way I have is to go through all my changelists and look at file icons.</p> <p>Isn't there a nicer way ? even a console based command would do...</p>
[ { "answer_id": 364518, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 2, "selected": true, "text": "p4 resolve -n\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39263/" ]
363,026
<p>I have the following linq code...</p> <pre><code>CMSDataContext dc = new CMSDataContext(); var q = from u in dc.CMSUsers join d in dc.tblDistricts on u.DistrictCode equals d.District into orders select u; </code></pre> <p>District shows this error: Ambiguity between 'tblDistrict.District' and 'tblDistrict.District'</p> <p>Any ideas?</p> <p>EDIT:</p> <p>It turns out that I had the same table in two different dbml files. Apparently, I cannot do this. I will have to end up joining a table from one dbml file with another table from a different dbml file. If anyone can enlighten me on how to do this, I will deem it as an answer. Thanks.</p>
[ { "answer_id": 16130996, "author": "gkiko", "author_id": 660408, "author_profile": "https://Stackoverflow.com/users/660408", "pm_score": 2, "selected": false, "text": ".dbml" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316/" ]
363,031
<p>I want to open a ZIP-file, that have no entries with java.util.zip.ZipFile. But on the constructor I get the following exception: 'java.util.zip.ZipException: error in opening zip file'. How can I open the empty ZIP?</p> <p>That ZIP-file is created by the commandline zip-program under linux. I simply deleted all entries from a ZIP-file.</p> <p>I need this as testdata for a class I write. The class should simply return an empty list for this case, but broken ZIP-files should return an error.</p> <p>For some more explanation on the problem. I have an interface, for extracting some documents from different sources. Other implementations gather them from webservices or directories, this implementation from ZIP-files. The interface give an Iterator with some more functionality. So I want to decide, if the ZIP-file is empty or broken.</p>
[ { "answer_id": 366680, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": -1, "selected": false, "text": "ZipOutputStream" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
363,038
<p>I am messing around with different PHP logging frameworks. I am currently trying PEAR::Log. I figured that I would use its <code>singleton</code> function to make sure there was only one instance of the class around.</p> <p>I have a small daemon-like script I wanted to add logging to because it was probably the simplest script in the system to test. This script has several functions. I will probably want to log things inside the functions.</p> <p>The question I have is how do I best manage this singleton? </p> <p>To me calling this:</p> <pre><code>&amp;Log::singleton($handler, $name, $ident, $conf, $maxLevel); </code></pre> <p>in every function doesn't seem ideal especially since I already specified all of the options in the initial call. Pear::Log serializes this info, but from what it looks like you still have to provide all of those variables to get the instance.</p> <p>Another alternative is passing the instance into every function. Again, seems like it's less than ideal.</p> <p>I suppose you could make the instance a 'global' as well.</p> <p>What do you in this situation? Are there better solutions? </p>
[ { "answer_id": 363146, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 2, "selected": true, "text": "class Logger {\n\n private static $log;\n\n private function __construct() { }\n\n public static function init(Log $log) {\n self::$log = $log;\n }\n\n public static function get() {\n return self::$log;\n }\n\n}\n Logger Log Logger::get Logger::get()->doSomething($foo, $bar);\n" }, { "answer_id": 363241, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 2, "selected": false, "text": "Logger::Write(\"Something happened\");\n class Logger {\n private static $log = null;\n\n public static function init(Log $log) {\n self::$log = $log;\n }\n\n public static function Write(String $str) {\n if($log == null)\n init(Log::singleton(...));\n\n $this->log->Write($str);\n }\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28714/" ]
363,049
<p>I have a <code>crontab</code> that looks like</p> <pre><code>0 0 * * * pg_dump DB_NAME &gt; /path/to/dumps/`date +%Y%m%d`.dmp </code></pre> <p>which works fine when I run it manually, but not when <code>cron</code> runs it. After digging through the logs, I see</p> <pre><code>Dec 12 00:00:01 localhost crond[17638]: (postgres) CMD (pg_dump DB_NAME &gt; /path/to/dumps/`date +) </code></pre> <p>It looks like a problem with percent signs, but the <code>man</code> page doesn't even contain the percent character at all, so I thought they were alright.</p>
[ { "answer_id": 363073, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 5, "selected": true, "text": "0 0 * * * pg_dump DB_NAME > /path/to/dumps/`date +\\%Y\\%m\\%d`.dmp\n man 5 crontab" }, { "answer_id": 363144, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "cron % at cron cron $HOME/bin # @(#)$Id: crontab,v 4.2 2007/09/17 02:41:00 jleffler Exp $\n# Crontab file for Home Directory for Jonathan Leffler (JL)\n#-----------------------------------------------------------------------------\n#Min Hour Day Month Weekday Command\n#-----------------------------------------------------------------------------\n0 * * * * /usr/bin/ksh /work1/jleffler/bin/Cron/hourly\n1 1 * * * /usr/bin/ksh /work1/jleffler/bin/Cron/daily\n23 1 * * 1-5 /usr/bin/ksh /work1/jleffler/bin/Cron/weekday\n2 3 * * 0 /usr/bin/ksh /work1/jleffler/bin/Cron/weekly\n21 3 1 * * /usr/bin/ksh /work1/jleffler/bin/Cron/monthly\n /work1/jleffler/bin/Cron /work1/jleffler/bin Cron" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4203/" ]
363,084
<p>How would I Export tables specifying only certain fields?</p> <p>I am using mysql 5.0 - using either a sql command or mysqldump.</p> <p>My table is X, and the fields I want to export are A,B,C</p>
[ { "answer_id": 363089, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 5, "selected": true, "text": "SELECT A,B,C\nFROM X\nINTO OUTFILE 'file name';\n INTO OUTFILE FIELDS ENCLOSED BY FIELDS ESCAPED BY SELECT A,B,C\nINTO OUTFILE '/tmp/result.txt'\nFIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\nLINES TERMINATED BY '\\n'\nFROM X;\n LOAD DATA INFILE LOAD DATA INFILE '/tmp/result.txt'\nINTO TABLE X\nFIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\nLINES TERMINATED BY '\\n';\n" }, { "answer_id": 363095, "author": "inxilpro", "author_id": 12549, "author_profile": "https://Stackoverflow.com/users/12549", "pm_score": 1, "selected": false, "text": "SELECT col1, col2\n INTO OUTFILE '/filepath/export.txt'\n FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\n LINES TERMINATED BY '\\n'\nFROM table;\n" }, { "answer_id": 11550099, "author": "Victor Sergienko", "author_id": 207791, "author_profile": "https://Stackoverflow.com/users/207791", "pm_score": 3, "selected": false, "text": "OUTFILE mysqldump create table temp_weeeee select ...." }, { "answer_id": 16032992, "author": "nacholibre", "author_id": 1047510, "author_profile": "https://Stackoverflow.com/users/1047510", "pm_score": 2, "selected": false, "text": "echo 'select field from db.table;' | mysql -u user -p password > output.txt\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37109/" ]
363,086
<p>I want to create custom tooltips where I can put any kind of controls. I have derived from CDialog and used the <code>WS_POPUP | WS_BORDER</code> styles. I also add the <code>CS_DROPSHADOW</code> style in the OnInitDialog to get the tooltip shadow.</p> <p>Then I manage myself the <code>WM_MOUSEHOVER</code> and <code>WM_MOUSELEAVE</code> events to show/hide the tooltips.</p> <p>I display the tooltip using <code>SetWindowPos</code> and <code>SWP_NOACTIVATE</code> to prevent the parent from becoming inactive and the new dialog from becoming active. But anyway, when I create the dialog using <code>CDialog::Create</code> method...the main window becomes inactive...what makes a very bad effect.</p> <p>So my custion is how can I create a CDialog with the WS_POPUP style without my main window (or the parent window of the dialog) becomening inactive when the new dialog shows up???</p> <p>Thanks for helping!</p> <p>Edited: I do not use the WS_VISIBLE style to create the dialog...this this the resource:</p> <pre><code> IDD_LABEL_TOOLTIP_DLG DIALOGEX 0, 0, 100, 9 STYLE DS_SETFONT | WS_POPUP | WS_BORDER FONT 8, "Tahoma", 0, 0, 0x0 BEGIN LTEXT "##################",IDC_TOOLTIP_LBL_TEXT,0,0,99,9 END </code></pre> <p>The code that display the tooltip is something like that:</p> <pre><code>if(!pTooltipDlg) { pTooltipDlg = new MyCustomTooltipDlg(); pTooltipDlg-&gt;Create( MyCustomTooltipDlg::IDD, this); } pTooltipDlg-&gt;ShowWindow(SW_SHOWNOACTIVATE); </code></pre> <p>The first time (ie when the create is being call) the main windows lose the focus...the rest of them this ugly effect is not happening...so I am sure is because of the Create.</p>
[ { "answer_id": 363101, "author": "JTeagle", "author_id": 162171, "author_profile": "https://Stackoverflow.com/users/162171", "pm_score": 1, "selected": false, "text": "CDialog::Create() WS_VISIBLE Create() WM_SETFOCUS" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14053/" ]
363,094
<p>Windows Mobile devices have different behaviour for suspending when the device is on battery power, or on external power.</p> <p>in my application, written using VB.net, I need to be able to determine whether the device has external power connected.</p> <p>is there a method to get this status from the Compact framework?</p>
[ { "answer_id": 363152, "author": "bezmax", "author_id": 43677, "author_profile": "https://Stackoverflow.com/users/43677", "pm_score": 1, "selected": false, "text": "if (SystemState.PowerBatteryState & BatteryState.Charging) ...\n" }, { "answer_id": 33953706, "author": "Febraiz", "author_id": 4875755, "author_profile": "https://Stackoverflow.com/users/4875755", "pm_score": 1, "selected": false, "text": "Public Function isOnCharge() As Boolean\n Dim status As New SYSTEM_POWER_STATUS_EX2\n GetSystemPowerStatusEx2(status, Convert.ToUInt32(Marshal.SizeOf(status)), True) \n\n If status.BatteryCurrent < 10000 Then\n return true 'plugged in\n else return false 'Unplugged\n End If\nEnd Function\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5146/" ]
363,096
<p>IE causes a very unattractive flash or flicker when the page posts back. Without using an UpdatePanel, how can I reduce or remove it?</p> <p>Most solutions suggest using page transitions like so:</p> <pre><code>&lt;meta content="BlendTrans(Duration=0.1)" http-equiv="Page-Exit" /&gt; </code></pre> <p>We have been using this with success for a couple of years, but it's broken in IE8 Beta 2.</p>
[ { "answer_id": 363127, "author": "Dave Haynes", "author_id": 7072, "author_profile": "https://Stackoverflow.com/users/7072", "pm_score": 3, "selected": true, "text": "<meta http-equiv=\"Page-Exit\" content=\"Alpha(opacity=100)\" />\n" }, { "answer_id": 363167, "author": "Egil Hansen", "author_id": 32809, "author_profile": "https://Stackoverflow.com/users/32809", "pm_score": -1, "selected": false, "text": "<!-- Fixes the \"Flash of Unstyled Content\" problem (info here: http://www.bluerobot.com/web/css/fouc.asp) -->\n<script type=\"text/javascript\"></script> \n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7072/" ]
363,099
<p>I am using <a href="http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fillpolygon.aspx" rel="nofollow noreferrer">FillPolygon</a> with a semi-transparent color to draw a triangle (an arrow pointer). I have noticed that FillPolygon gives awkward results with an isocel triangle. One of the sides is overlapping <a href="http://msdn.microsoft.com/en-us/library/system.drawing.graphics.drawpolygon.aspx" rel="nofollow noreferrer">DrawPolygon</a>'s side, while the two others aren't. I would have expected none or all, but not something in between.</p> <p>Here's a sample: DrawPolygon uses a semi-transparent red, while FillPolygon uses a semi-transparent green. You can see one side is brown, the two other sides are red.</p> <p><a href="http://www.slimcode.com/downloads/arrow.png" rel="nofollow noreferrer">alt text http://www.slimcode.com/downloads/arrow.png</a></p> <p>The coordinates for this example are: {X=36,Y=201}, {X=42,Y=207}, {X=30,Y=207}.</p> <p>Using an opaque color would solve everything as I could call both DrawPolygon and FillPolygon, but I need to use a semi-transparent color. I'm drawing into an image if it can make a difference.</p>
[ { "answer_id": 363352, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 1, "selected": false, "text": " Dim image As New Bitmap(<my_Xsize>, <my_Ysize>)\n Dim gr As Graphics = Graphics.FromImage(image)\n <Draw your FillPolygon>\n <Erase the leftside of the polygon>\n <Draw your Polygon>\n\n gr.DrawImage(image, <myXcoor>, <myYcoor>)\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4898/" ]
363,111
<p>I use Vim and Vim plugins for Visual Studio when writing C++. Often, I find myself wanting to search for a string within a function, for example every call to <code>object-&gt;public_member.memberfunc()</code>.</p> <p>I know Vim offers a convenient way to search for a single word, by pressing <code>*</code> and <code>#</code>, and it can also search for typed strings using the ubiquitous slash <code>/</code> command. When trying to search for all the instances of a longer string like the one above, it takes a while to re-type after <code>/</code>.</p> <p>Is there a way to search for the selection? For example, highlight with <code>v</code>, then copy with <code>y</code>, is there a way to paste after <code>/</code>? Is there an easier shortcut?</p>
[ { "answer_id": 10452438, "author": "Cory Klein", "author_id": 446554, "author_profile": "https://Stackoverflow.com/users/446554", "pm_score": 7, "selected": false, "text": "q/ / p p :help q/" }, { "answer_id": 14747639, "author": "cutemachine", "author_id": 409550, "author_profile": "https://Stackoverflow.com/users/409550", "pm_score": 4, "selected": false, "text": "* #" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22724/" ]
363,156
<p>I have a cocoa app with two types windows each of which requires a different main menu to be displayed.</p> <p>In my MainMenu.xib I have the default MainMenu. In Window1.xib I have Window1 and in Window2.xib I have Window2 and it's MainMenu.</p> <p>When I have the first Window open I have the default Menu, when I open Window2 I get it's menu.</p> <p>However, when I switch back to Window1 I still see Window2's menu. How do I make the menu that is displayed follow the key window?</p>
[ { "answer_id": 363204, "author": "Marc Charbonneau", "author_id": 35136, "author_profile": "https://Stackoverflow.com/users/35136", "pm_score": 4, "selected": true, "text": "- (void)setMainMenu:(NSMenu *)aMenu - (void)windowDidBecomeKey:(NSNotification *)notification" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39138/" ]
363,158
<p>We work extensively in the .Net Compact Framework and Windows Mobile. I've seen plenty of questions come up regarding specifics to development of ASP.Net apps or other .Net based desktop apps but nothing CF specific.</p> <p>Anyone else a mobile developer out there that can share some things to start doing, stop doing, and avoid doing when developing in the Compact Framework?</p>
[ { "answer_id": 363180, "author": "Mat Nadrofsky", "author_id": 26853, "author_profile": "https://Stackoverflow.com/users/26853", "pm_score": 4, "selected": false, "text": "dgDataGrid.DataSource = dsDataSet;\n bsData.DataSource = dsDataSet;\n\ndgDataGrid.DataSource = bsData;\n" }, { "answer_id": 698224, "author": "Mat Nadrofsky", "author_id": 26853, "author_profile": "https://Stackoverflow.com/users/26853", "pm_score": 2, "selected": false, "text": "using System.Windows.Forms;\nusing System.Data;\n\npublic static void SortDataGrid(object sender, System.Windows.Forms.MouseEventArgs e)\n{\n DataGrid.HitTestInfo hitTest;\n DataTable dataTable;\n DataView dataView;\n string columnName;\n DataGrid dataGrid;\n\n // Use only left mouse button clicks.\n if (e.Button == MouseButtons.Left)\n {\n // Set dataGrid equal to the object that called this event handler.\n dataGrid = (DataGrid)sender;\n\n // Perform a hit test to determine where the mousedown event occured.\n hitTest = dataGrid.HitTest(e.X, e.Y);\n\n // If the MouseDown event occured on a column header,\n // then perform the sorting operation.\n if (hitTest.Type == DataGrid.HitTestType.ColumnHeader)\n {\n // Get the DataTable associated with this datagrid.\n dataTable = (DataTable)dataGrid.DataSource;\n\n // Get the DataView associated with the DataTable.\n dataView = dataTable.DefaultView;\n\n // Get the name of the column that was clicked.\n if(dataGrid.TableStyles.Count != 0)\n columnName = dataGrid.TableStyles[0].GridColumnStyles[hitTest.Column].MappingName;\n else\n columnName = dataTable.Columns[hitTest.Column].ColumnName;\n\n // If the sort property of the DataView is already the current\n // column name, sort that column in descending order.\n // Otherwise, sort on the column name.\n if (dataView.Sort == columnName)\n dataView.Sort = columnName + \" DESC\";\n else\n dataView.Sort = columnName;\n }\n }\n}\n\nprivate void dgDataGrid_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)\n{\n if(dgDataGrid.VisibleRowCount == 0) return;\n SortDataGrid(sender, e);\n dgDataGrid.Select(dgDataGrid.CurrentRowIndex);\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26853/" ]
363,159
<p>hey guys, i'm getting an exception on the following </p> <p>inner exception: {"Value cannot be null.\r\nParameter name: String"}</p> <p>Which reads like a simple error message, but none of the values (image, fileName) are null. How can i find out where this null String is?</p> <pre><code>RipHelper.UploadImage(image, fileName); </code></pre> <p>which calls</p> <pre><code>public static void UploadImage(System.Drawing.Image image, string fileName) { // this line is never reached } </code></pre> <p>Here is the full error log</p> <h1>#</h1> <p>System.ArgumentNullException: Value cannot be null. Parameter name: String at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer&amp; number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at Helpers.RipHelper..cctor() in C:\Helpers\RipHelper.cs:line 23 --- End of inner exception stack trace --- at Helpers.RipHelper.UploadImage(HttpPostedFile uploadFile, String fileName) at Helpers.UploadHelper.UploadImage(HttpContext context) in C:\Helpers\UploadHelper.cs:line 79</p>
[ { "answer_id": 363201, "author": "frosty", "author_id": 461880, "author_profile": "https://Stackoverflow.com/users/461880", "pm_score": 0, "selected": false, "text": "private static readonly int previewImageHeight = int.Parse(ConfigurationManager.AppSettings[\"PreviewImageHeight\"]);\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/461880/" ]
363,171
<p>So I have this regex:</p> <pre><code>(^(\s+)?(?P&lt;NAME&gt;(\w)(\d{7}))((01f\.foo)|(\.bar|\.goo\.moo\.roo))$|(^(\s+)?(?P&lt;NAME2&gt;R1_\d{6}_\d{6}_)((01f\.foo)|(\.bar|\.goo\.moo\.roo))$)) </code></pre> <p>Now if I try and do a match against this:</p> <pre> B048661501f.foo </pre> <p>I get this error:</p> <pre> File "C:\Python25\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: redefinition of group name 'NAME' as group 9; was group 3 </pre> <p>If I can't define the same group twice in the same regex expression for two different cases, what do I do?</p>
[ { "answer_id": 363264, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "^\\s*(?P<NAME>\\w\\d{7}|R1_(?:\\d{6}_){2})(01f\\.foo|\\.(?:bar|goo|moo|roo))$\n \"R1_\" \"_\" \"01f.foo\" \".\" \"bar\" \"goo\" \"moo\" \"roo\" ^\\s*(?P<NAME>\\w\\d{7}01f|R1_(?:\\d{6}_){2})\\.(?:foo|bar|goo|moo|roo)$\n \"R1_\" \"_\" \"foo\" \"bar\" \"goo\" \"moo\" \"roo\"" }, { "answer_id": 56310906, "author": "Naveen", "author_id": 8311124, "author_profile": "https://Stackoverflow.com/users/8311124", "pm_score": 2, "selected": false, "text": "NameError: basestring regex regex re sudo pip install regex\n re re2 regex import regex as re\n" }, { "answer_id": 66687939, "author": "lucazav", "author_id": 416988, "author_profile": "https://Stackoverflow.com/users/416988", "pm_score": 0, "selected": false, "text": "regex" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34395/" ]
363,189
<p>I have a sql statement that consists of multiple SELECT statements. I want to limit the total number of rows coming back to let's say 1000 rows. I thought that using the SET ROWCOUNT 1000 directive would do this...but it does not. For example:</p> <pre><code>SET ROWCOUNT 1000 select orderId from TableA select name from TableB </code></pre> <p>My initial thought was that SET ROWCOUNT would apply to the <strong>entire</strong> batch, not the individual statements within it. The behavior I'm seeing is it will limit the first select to 1000 and then the second one to 1000 for a total of 2000 rows returned. Is there any way to have the 1000 limit applied to the batch as a whole?</p>
[ { "answer_id": 363205, "author": "AlexJReid", "author_id": 32320, "author_profile": "https://Stackoverflow.com/users/32320", "pm_score": 1, "selected": false, "text": "SELECT TOP 1000 * \nFROM (select orderId \n from TableA \n UNION ALL \n select name from TableB) t\n" }, { "answer_id": 363346, "author": "D'Arcy Rittich", "author_id": 39430, "author_profile": "https://Stackoverflow.com/users/39430", "pm_score": 1, "selected": false, "text": "select top 1000 from (\n select orderId, null as name, 'TableA' as Source from TableA\n union all\n select null as orderID, name, 'TableB' as Source from TableB\n) a order by Source\n" }, { "answer_id": 3999309, "author": "kateroh", "author_id": 439213, "author_profile": "https://Stackoverflow.com/users/439213", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE selectTopN\n(\n @numberOfRecords int\n)\nAS\n SELECT TOP (@numberOfRecords) * FROM Customers\nGO\n" }, { "answer_id": 18820165, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 0, "selected": false, "text": "SET ROWCOUNT will not affect DELETE INSERT UPDATE Avoid SET ROWCOUNT DELETE INSERT UPDATE" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4398/" ]
363,190
<p>I have input field value from that is used for forming XPath query. What symbols in input string should I check to minimise possibility of XML injection?</p>
[ { "answer_id": 363212, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 1, "selected": false, "text": ": \\" }, { "answer_id": 363236, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 1, "selected": false, "text": "// / :: @* *" }, { "answer_id": 363460, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 3, "selected": false, "text": "doc" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39292/" ]
363,200
<p>I have a QTreeWidget with a column filled with some numbers, how can I sort them?</p> <p>If I use setSortingEnabled(true); I can sort correctly only strings, so my column is sorted:</p> <p>1 10 100 2 20 200</p> <p>but this is not the thing I want! Suggestions?</p>
[ { "answer_id": 363242, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": -1, "selected": false, "text": "\"19999\" < \"2\" 19 121 \"19\"[0] != \"121\"[0] ? // no\n\"19\"[1] != \"121\"[1] ? // yes\n '9' > '2' ? // yes\n return some value that indicates \"19\" greater than \"121\";\n" }, { "answer_id": 366637, "author": "Emilio", "author_id": 39796, "author_profile": "https://Stackoverflow.com/users/39796", "pm_score": 5, "selected": true, "text": "class TreeWidgetItem : public QTreeWidgetItem {\n public:\n TreeWidgetItem(QTreeWidget* parent):QTreeWidgetItem(parent){}\n private:\n bool operator<(const QTreeWidgetItem &other)const {\n int column = treeWidget()->sortColumn();\n return text(column).toLower() < other.text(column).toLower();\n }\n};\n" }, { "answer_id": 5075433, "author": "PedroMorgan", "author_id": 118412, "author_profile": "https://Stackoverflow.com/users/118412", "pm_score": 3, "selected": false, "text": "__lt__ class TreeWidgetItem(QtGui.QTreeWidgetItem):\n\n def __init__(self, parent=None):\n QtGui.QTreeWidgetItem.__init__(self, parent)\n\n def __lt__(self, otherItem):\n column = self.treeWidget().sortColumn()\n return self.text(column).toLower() < otherItem.text(column).toLower()\n" }, { "answer_id": 12145624, "author": "Alen", "author_id": 1628179, "author_profile": "https://Stackoverflow.com/users/1628179", "pm_score": 2, "selected": false, "text": "class TreeWidgetItem( QtGui.QTreeWidgetItem ):\n def __init__(self, parent=None):\n QtGui.QTreeWidgetItem.__init__(self, parent)\n\n def __lt__(self, otherItem):\n column = self.treeWidget().sortColumn()\n try:\n return float( self.text(column) ) > float( otherItem.text(column) )\n except ValueError:\n return self.text(column) > otherItem.text(column)\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39339/" ]
363,209
<p>I would like to know if it is possible to copy/move files to a destination based on the origin name.</p> <p>Basically, I have a /mail folder, which has several subfolders such as cur and new etc. I then have an extracted backup in /mail/home/username that is a duplicate. mv -f will not work, as I do not have permission to overwrite the directories, but only the files within.</p> <p>I get errors such as mv: cannot overwrite directory `/home/username/mail/username.com'</p> <p>What I want to do is for each file in the directory username.com, move it to the folder of the same name in /mail. There could be any number of folders in place of username.com, with seperate sub sirectories of their own.</p> <p>What is the best way to do this?</p> <p>I have to do it this way as due to circumstances I only have access to my host with ftp and bash via php.</p> <p>edit: clarification</p> <p>I think I need to clarify what happened. I am on a shared host, and apparently do not have write access to the directories themselves. At least the main ones such as mail and public_html. I made a backup of ~/mail with tar, but when trying to extract it extracted to ~/mail/home/mail etc, as I forgot about the full path. Now, I cannot simply untar because the path is wrong, and I cannot mv -f because I only have write access to files, not directories.</p>
[ { "answer_id": 363253, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "for file in /mail/*; do\n mv -f $file /home/username/mail/$(basename $file)\ndone\n" }, { "answer_id": 363305, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": true, "text": "cpio -p cd /mail; find . -type f | cpio -pvdmB /home/username/mail\n -v -d -m -B -u cd find /mail -type f | cpio -pvdmB /home/username\n /home/username find /var/spool/mail -type f | cpio -pvdmB /home/username/mail\n /home/username/mail/var/spool/mail tar (cd /mail; tar -cf - . ) | (cd /home/username/mail; tar -xf - )\n (cd /mail; find . -type f | tar -cf - -F - ) | (cd /home/username/mail; tar -xf - )\n" }, { "answer_id": 363311, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 0, "selected": false, "text": "tar tar /mail/ tar" }, { "answer_id": 363316, "author": "PEZ", "author_id": 44639, "author_profile": "https://Stackoverflow.com/users/44639", "pm_score": 0, "selected": false, "text": "for file in /mail/*; do\n mv -f $file /home/username/mail/$(basename $file) 2> /tmp/mailbackup.username.errors\ndone\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
363,211
<p>ASP.NET MVC routes have names when mapped:</p> <pre><code>routes.MapRoute( "Debug", // Route name -- how can I use this later???? "debug/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = string.Empty } ); </code></pre> <p>Is there a way to get the route name, e.g. "Debug" in the above example? I'd like to access it in the controller's OnActionExecuting so that I can set up stuff in the ViewData when debugging, for example, by prefixing a URL with /debug/...</p>
[ { "answer_id": 363856, "author": "Nicolas Cadilhac", "author_id": 29244, "author_profile": "https://Stackoverflow.com/users/29244", "pm_score": 7, "selected": true, "text": "public static class RouteCollectionExtensions\n{\n public static Route MapRouteWithName(this RouteCollection routes,\n string name, string url, object defaults, object constraints)\n {\n Route route = routes.MapRoute(name, url, defaults, constraints);\n route.DataTokens = new RouteValueDictionary();\n route.DataTokens.Add(\"RouteName\", name);\n\n return route;\n }\n}\n routes.MapRouteWithName(\n \"myRouteName\",\n \"{controller}/{action}/{username}\",\n new { controller = \"Home\", action = \"List\" }\n );\n RouteData.DataTokens[\"RouteName\"]\n" }, { "answer_id": 6189226, "author": "Мишка Коробков", "author_id": 5074894, "author_profile": "https://Stackoverflow.com/users/5074894", "pm_score": -1, "selected": false, "text": "RouteData.DataTokens[\"Namespaces\"]" }, { "answer_id": 13482670, "author": "ajbeaven", "author_id": 161735, "author_profile": "https://Stackoverflow.com/users/161735", "pm_score": -1, "selected": false, "text": "protected override OnActionExecuting()\n{\n #if DEBUG\n\n // set up stuff in the ViewData\n\n #endif\n\n // continue\n}\n" }, { "answer_id": 38635229, "author": "logicalguy", "author_id": 3789658, "author_profile": "https://Stackoverflow.com/users/3789658", "pm_score": 0, "selected": false, "text": "RouteConfig.cs routes.MapRoute(\n name: \"MyRoute\",\n url: \"Cont/Act/{blabla}\",\n defaults: new { controller = \"Cont\", action = \"Act\"}\n );\n var myRoute = Url.RouteUrl(\"MyRoute\", new { blabla = \"blabla\" }).Replace(\"blabla\", \"\");\n /Cont/Act/\n" }, { "answer_id": 50302831, "author": "Alexander", "author_id": 7914637, "author_profile": "https://Stackoverflow.com/users/7914637", "pm_score": 1, "selected": false, "text": "routes.MapRoute(\n name: \"MyRoute\",\n url: \"{controller}/{action}/{id}\",\n defaults: new { routeName = \"MyRoute\", controller = \"Home\", action = \"Index\", id=UrlParameter.Optional }\n);\n string routeName = ControllerContext.RouteData.Values[\"routeName\"].ToString();\n" }, { "answer_id": 57829427, "author": "Alan Shaw", "author_id": 7237891, "author_profile": "https://Stackoverflow.com/users/7237891", "pm_score": 2, "selected": false, "text": "routes.MapRoute( name: \"Default\",\n url: \"{controller}/{action}/{id}\",\n defaults: new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }\n var routeName = Url.RequestContext.RouteData.Values[\"action\"].ToString();\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43649/" ]
363,223
<p>I have a script which will be run interactively by non-technical users. The script writes status updates to STDOUT so that the user can be sure that the script is running OK.</p> <p>I want both STDOUT and STDERR redirected to the terminal (so that the user can see that the script is working as well as see if there was a problem). I also want both streams redirected to a log file.</p> <p>I've seen a bunch of solutions on the net. Some don't work and others are horribly complicated. I've developed a workable solution (which I'll enter as an answer), but it's kludgy.</p> <p>The perfect solution would be a single line of code that could be incorporated into the beginning of any script that sends both streams to both the terminal and a log file.</p> <p><strong>EDIT:</strong> Redirecting STDERR to STDOUT and piping the result to tee works, but it depends on the users remembering to redirect and pipe the output. I want the logging to be fool-proof and automatic (which is why I'd like to be able to embed the solution into the script itself.)</p>
[ { "answer_id": 363239, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 9, "selected": true, "text": "./a.out 2>&1 | tee output\n ./a.out |& tee output\n #!/bin/sh\n{\n ... whatever you had in your script before\n} 2>&1 | tee output.file\n" }, { "answer_id": 363243, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": " program 2>&1 | tee > logfile\n" }, { "answer_id": 363245, "author": "JPLemme", "author_id": 1019, "author_profile": "https://Stackoverflow.com/users/1019", "pm_score": 1, "selected": false, "text": "${APP_HOME}/${1}.sh ${2} ${3} ${4} ${5} ${6} 2>&1 | tee -a ${APP_HOME}/${1}.log\n ./RunScript.sh ScriptToRun Param1 Param2 Param3 ...\n" }, { "answer_id": 363257, "author": "flolo", "author_id": 36472, "author_profile": "https://Stackoverflow.com/users/36472", "pm_score": 3, "selected": false, "text": "2>&1 tee mycommand 2>&1 | tee mylogfile.log\n #!/bin/sh\nwhatever1\nwhatever2\n...\nwhatever3\n #!/bin/sh\n( whatever1\nwhatever2\n...\nwhatever3 ) 2>&1 | tee mylogfile.log\n" }, { "answer_id": 363444, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 2, "selected": false, "text": "script #!/bin/sh\nscript -c './realscript.sh'\nexit\n #!/bin/sh\necho 'Output'\n ~: sh wrap.sh \nScript started, file is typescript\nOutput\nScript done, file is typescript\n~: cat typescript \nScript started on fr. 12. des. 2008 kl. 18.07 +0100\nOutput\n\nScript done on fr. 12. des. 2008 kl. 18.07 +0100\n~:\n" }, { "answer_id": 1728810, "author": "denis", "author_id": 86643, "author_profile": "https://Stackoverflow.com/users/86643", "pm_score": 1, "selected": false, "text": "teelog make ... make #!/bin/bash\nme=teelog\nVersion=\"2008-10-9 oct denis-bz\"\n\nHelp() {\ncat <<!\n\n $me anycommand args ...\n\nlogs the output of \"anycommand ...\" as well as displaying it on the screen,\nby running\n anycommand args ... 2>&1 | tee `day`-command-args.log\n\nThat is, stdout and stderr go to both the screen, and to a log file.\n(The Unix \"tee\" command is named after \"T\" pipe fittings, 1 in -> 2 out;\nsee http://en.wikipedia.org/wiki/Tee_(command) ).\n\nThe default log file name is made up from \"command\" and all the \"args\":\n $me cmd -opt dir/file logs to `day`-cmd--opt-file.log .\nTo log to xx.log instead, either export log=xx.log or\n $me log=xx.log cmd ...\nIf \"logdir\" is set, logs are put in that directory, which must exist.\nAn old xx.log is moved to /tmp/\\$USER-xx.log .\n\nThe log file has a header like\n # from: command args ...\n # run: date pwd etc.\nto show what was run; see \"From\" in this file.\n\nCalled as \"Log\" (ln -s $me Log), Log anycommand ... logs to a file:\n command args ... > `day`-command-args.log\nand tees stderr to both the log file and the terminal -- bash only.\n\nSome commands that prompt for input from the console, such as a password,\ndon't prompt if they \"| tee\"; you can only type ahead, carefully.\n\nTo log all \"make\" s, including nested ones like\n cd dir1; \\$(MAKE)\n cd dir2; \\$(MAKE)\n ...\nexport MAKE=\"$me make\"\n\n!\n # See also: output logging in screen(1).\n exit 1\n}\n\n\n#-------------------------------------------------------------------------------\n# bzutil.sh denisbz may2008 --\n\nday() { # 30mar, 3mar\n /bin/date +%e%h | tr '[A-Z]' '[a-z]' | tr -d ' '\n}\n\nedate() { # 19 May 2008 15:56\n echo `/bin/date \"+%e %h %Y %H:%M\"`\n}\n\nFrom() { # header # from: $* # run: date pwd ...\n case `uname` in Darwin )\n mac=\" mac `sw_vers -productVersion`\"\n esac\n cut -c -200 <<!\n${comment-#} from: $@\n${comment-#} run: `edate` in $PWD `uname -n` $mac `arch` \n\n!\n # mac $PWD is pwd -L not -P real\n}\n\n # log name: day-args*.log, change this if you like --\nlogfilename() {\n log=`day`\n [[ $1 == \"sudo\" ]] && shift\n for arg\n do\n log=\"$log-${arg##*/}\" # basename\n (( ${#log} >= 100 )) && break # max len 100\n done\n # no blanks etc in logfilename please, tr them to \"-\"\n echo $logdir/` echo \"$log\".log | tr -C '.:+=[:alnum:]_\\n' - `\n}\n\n#-------------------------------------------------------------------------------\ncase \"$1\" in\n-v* | --v* )\n echo \"$0 version: $Version\"\n exit 1 ;;\n\"\" | -* )\n Help\nesac\n\n # scan log= etc --\nwhile [[ $1 == [a-zA-Z_]*=* ]]; do\n export \"$1\"\n shift\ndone\n\n: ${logdir=.}\n[[ -w $logdir ]] || {\n echo >&2 \"error: $me: can't write in logdir $logdir\"\n exit 1\n }\n: ${log=` logfilename \"$@\" `}\n[[ -f $log ]] &&\n /bin/mv \"$log\" \"/tmp/$USER-${log##*/}\"\n\n\ncase ${0##*/} in # basename\nlog | Log ) # both to log, stderr to caller's stderr too --\n{\n From \"$@\"\n \"$@\"\n} > $log 2> >(tee /dev/stderr) # bash only\n # see http://wooledge.org:8000/BashFAQ 47, stderr to a pipe\n;;\n\n* )\n#-------------------------------------------------------------------------------\n{\n From \"$@\" # header: from ... date pwd etc.\n\n \"$@\" 2>&1 # run the cmd with stderr and stdout both to the log\n\n} | tee $log\n # mac tee buffers stdout ?\n\nesac\n" }, { "answer_id": 15794304, "author": "Jason Sydes", "author_id": 825457, "author_profile": "https://Stackoverflow.com/users/825457", "pm_score": 5, "selected": false, "text": "exec > >(tee -a $HOME/logfile) 2>&1\n #!/usr/bin/env bash\n\nexec > >(tee -a $HOME/logfile) 2>&1\n\n# Test redirection of STDOUT\necho test_stdout\n\n# Test redirection of STDERR\nls test_stderr___this_file_does_not_exist\n" }, { "answer_id": 53051506, "author": "MatrixManAtYrService", "author_id": 1054322, "author_profile": "https://Stackoverflow.com/users/1054322", "pm_score": 5, "selected": false, "text": "the_cmd 1> >(tee stdout.txt ) 2> >(tee stderr.txt >&2 )\n tee #! /usr/bin/env bash\nthe_cmd()\n{\n echo out;\n 1>&2 echo err;\n}\n\nthe_cmd 1> >(tee stdout.txt ) 2> >(tee stderr.txt >&2 )\n $ foo=$(./example)\n err\n\n$ echo $foo\n out\n\n$ cat stdout.txt\n out\n\n$ cat stderr.txt\n err\n tee the_cmd 1> /proc/self/fd/13 2> /proc/self/fd/14 the_cmd the_cmd the_cmd tee tee the_cmd tee tee stdout stderr the_cmd" }, { "answer_id": 59435204, "author": "Don Hatch", "author_id": 2552290, "author_profile": "https://Stackoverflow.com/users/2552290", "pm_score": 3, "selected": false, "text": "my_command 3>&1 1>&2 2>&3-\n { my_command 3>&1 1>&2 2>&3- | stderr_filter;} 3>&1 1>&2 2>&3-\n { { my_command | stdout_filter;} 3>&1 1>&2 2>&3- | stderr_filter;} 3>&1 1>&2 2>&3-\n { my_command 3>&1 1>&2 2>&3- | stderr_filter;} 3>&1 1>&2 2>&3- | stdout_filter\n alias my_command='{ echo \"to stdout\"; echo \"to stderr\" >&2;}'\nalias stdout_filter='{ sleep 1; sed -u \"s/^/teed stdout: /\" | tee stdout.txt;}'\nalias stderr_filter='{ sleep 2; sed -u \"s/^/teed stderr: /\" | tee stderr.txt;}'\n ...(1 second pause)...\nteed stdout: to stdout\n...(another 1 second pause)...\nteed stderr: to stderr\n teed stderr: to stderr 2>&3- 2>&3 3>&- {my_command 3>&1 1>&- 1>&2 2>&- 2>&3 3>&- | stderr_filter;} 3>&1 1>&- 1>&2 2>&- 2>&3 3>&- | stdout_filter my_command >&1 >stdout.txt 2>&2 2>stderr.txt\n >&1 2>&2" }, { "answer_id": 65738448, "author": "Xiaowei Song", "author_id": 618968, "author_profile": "https://Stackoverflow.com/users/618968", "pm_score": -1, "selected": false, "text": "#!/bin/bash\nexec 1> >(tee x.log) 2> >(tee x.err >&2)\n\necho \"test for log\"\necho \"test for err\" 1>&2\n" }, { "answer_id": 67930569, "author": "osexp2003", "author_id": 2293666, "author_profile": "https://Stackoverflow.com/users/2293666", "pm_score": 0, "selected": false, "text": "tee /proc/self/fd/2\n tee /proc/self/fd/2 file\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1019/" ]
363,231
<p>i'm using ASP.net with .NET 3.5 on IIS7 (Vista) with the URL Rewrite Module from Microsoft.</p> <p>This means, that i have a </p> <pre><code>&lt;system.webServer&gt; &lt;rewrite&gt;...&lt;/rewrite&gt; ... &lt;/system.webServer&gt; </code></pre> <p>section within the web.config, but i get a warning, that within the system.webServer the element "rewrite" is not allowed.</p> <p>How can i configure my system to allow (and maybe even have Intellisense) on the rewrite-part of the web.config?</p> <p>Thank you Christoph</p>
[ { "answer_id": 1813504, "author": "mellamokb", "author_id": 116614, "author_profile": "https://Stackoverflow.com/users/116614", "pm_score": 2, "selected": false, "text": "<system.webServer>\n <modules>\n <add name=\"UrlRewriteModule\" type=\"UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter\" />\n </modules>\n</system.webServer>\n <sectionGroup name=\"rewrite\">\n <section name=\"rules\" overrideModeDefault=\"Allow\" />\n <section name=\"globalRules\" overrideModeDefault=\"Deny\" allowDefinition=\"AppHostOnly\" />\n <section name=\"rewriteMaps\" overrideModeDefault=\"Allow\" />\n</sectionGroup>\n" }, { "answer_id": 3486086, "author": "Jonathan Freeland", "author_id": 90227, "author_profile": "https://Stackoverflow.com/users/90227", "pm_score": 6, "selected": true, "text": "C:\\download_directory\\rewrite2_intellisense>cscript UpdateSchemaCache.js VS90COMNTOOLS VS100COMNTOOLS <rewrite>" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34464/" ]
363,234
<p>Is it possible to get a URL from an action without knowing ViewContext (e.g., in a controller)? Something like this:</p> <pre><code>LinkBuilder.BuildUrlFromExpression(ViewContext context, Expression&lt;Action&lt;T&gt;&gt; action) </code></pre> <p>...but using Controller.RouteData instead of ViewContext. I seem to have metal block on this.</p>
[ { "answer_id": 363287, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 4, "selected": true, "text": " private string RouteValueDictionaryToUrl(RouteValueDictionary rvd)\n {\n var context = MvcMockHelpers.FakeHttpContext(\"~/\");\n // _routes is a RouteCollection\n var vpd = _routes.GetVirtualPath(\n new RequestContext(context, _\n routes.GetRouteData(context)), rvd);\n return vpd.VirtualPath;\n }\n string path = RouteTable.Routes.GetVirtualPath(\n new RequestContext(HttpContext, \n RouteTable.Routes.GetRouteData(HttpContext)),\n new RouteValueDictionary( \n new { controller = \"Foo\",\n action = \"Bar\" })).VirtualPath;\n" }, { "answer_id": 365469, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "public static string GetUrlFor<T>(this HttpContextBase c, Expression<Func<T, object>> action)\n where T : Controller\n{\n return RouteTable.Routes.GetVirtualPath(\n new RequestContext(c, RouteTable.Routes.GetRouteData(c)), \n GetRouteValuesFor(action)).VirtualPath;\n}\n\npublic static RouteValueDictionary GetRouteValuesFor<T>(Expression<Func<T, object>> action) \n where T : Controller\n{\n var methodCallExpresion = ((MethodCallExpression) action.Body);\n var controllerTypeName = methodCallExpresion.Object.Type.Name;\n var routeValues = new RouteValueDictionary(new\n {\n controller = controllerTypeName.Remove(controllerTypeName.LastIndexOf(\"Controller\")), \n action = methodCallExpresion.Method.Name\n });\n var methodParameters = methodCallExpresion.Method.GetParameters();\n for (var i = 0; i < methodParameters.Length; i++)\n {\n var value = Expression.Lambda(methodCallExpresion.Arguments[i]).Compile().DynamicInvoke();\n var name = methodParameters[i].Name;\n routeValues.Add(name, value);\n }\n return routeValues;\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29493/" ]
363,244
<p>I chose AjaxToolKit to build a WebForm login. Has anyone else had problems trying to do this? I'm planning to use DropShadow Extender and RoundedCorners with Panels, but this is my first time working with panels.</p> <p>Please check <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ConfirmButton/ConfirmButton.aspx" rel="nofollow noreferrer">this link</a>.</p> <p>I want to put a login panel into something like the screenshot shows, whenever the user clicks a button. This would be similar functionality to what happens on StackOverflow when you try to insert an image or hyperlink in 'ask a question'. Is this possible? How much effort is it?</p>
[ { "answer_id": 363287, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 4, "selected": true, "text": " private string RouteValueDictionaryToUrl(RouteValueDictionary rvd)\n {\n var context = MvcMockHelpers.FakeHttpContext(\"~/\");\n // _routes is a RouteCollection\n var vpd = _routes.GetVirtualPath(\n new RequestContext(context, _\n routes.GetRouteData(context)), rvd);\n return vpd.VirtualPath;\n }\n string path = RouteTable.Routes.GetVirtualPath(\n new RequestContext(HttpContext, \n RouteTable.Routes.GetRouteData(HttpContext)),\n new RouteValueDictionary( \n new { controller = \"Foo\",\n action = \"Bar\" })).VirtualPath;\n" }, { "answer_id": 365469, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "public static string GetUrlFor<T>(this HttpContextBase c, Expression<Func<T, object>> action)\n where T : Controller\n{\n return RouteTable.Routes.GetVirtualPath(\n new RequestContext(c, RouteTable.Routes.GetRouteData(c)), \n GetRouteValuesFor(action)).VirtualPath;\n}\n\npublic static RouteValueDictionary GetRouteValuesFor<T>(Expression<Func<T, object>> action) \n where T : Controller\n{\n var methodCallExpresion = ((MethodCallExpression) action.Body);\n var controllerTypeName = methodCallExpresion.Object.Type.Name;\n var routeValues = new RouteValueDictionary(new\n {\n controller = controllerTypeName.Remove(controllerTypeName.LastIndexOf(\"Controller\")), \n action = methodCallExpresion.Method.Name\n });\n var methodParameters = methodCallExpresion.Method.GetParameters();\n for (var i = 0; i < methodParameters.Length; i++)\n {\n var value = Expression.Lambda(methodCallExpresion.Arguments[i]).Compile().DynamicInvoke();\n var name = methodParameters[i].Name;\n routeValues.Add(name, value);\n }\n return routeValues;\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1388553/" ]
363,268
<p>I'm using the jQuery validation plugin to validate a form, and I'd like to remove the validation and submit the form if a certain link is clicked.</p> <p>I am submitting form with javascript like <code>jQuery('form#listing').submit()</code>, so I must remove the validation rules/function with javascript.</p> <p>The problem is that I can't figure out how to do this. I've tried things like <code>jQuery('form#listing').validate({});</code> and <code>jQuery('form#listing').validate = null</code>, but with no luck.</p>
[ { "answer_id": 363601, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 5, "selected": false, "text": "jQuery('form#listing').unbind('submit'); // remove all submit handlers of the form\n jQuery('form#listing').validate({\n onsubmit : false\n});\n .submit() jQuery('form#listing').unbind('submit').submit();\n" }, { "answer_id": 1055371, "author": "Jörn Zaefferer", "author_id": 2671, "author_profile": "https://Stackoverflow.com/users/2671", "pm_score": 7, "selected": true, "text": "$(\"#listing\")[0].submit();\n" }, { "answer_id": 1110307, "author": "kenitech", "author_id": 136946, "author_profile": "https://Stackoverflow.com/users/136946", "pm_score": 2, "selected": false, "text": "\n...\njQuery.extend(\n jQuery.fn, \n {\n removeValidator: function(){\n this.unbind();\n jQuery.removeData(this[0], 'validator'); \n }\n...\n" }, { "answer_id": 1110654, "author": "kenitech", "author_id": 136946, "author_profile": "https://Stackoverflow.com/users/136946", "pm_score": 3, "selected": false, "text": "var form = $('#my_form_id').get(0);\n$(form).removeData('validate');\n" }, { "answer_id": 9870127, "author": "Gaurav Jain", "author_id": 1199481, "author_profile": "https://Stackoverflow.com/users/1199481", "pm_score": 5, "selected": false, "text": "var form = $('#my_form_id').get(0);\n$.removeData(form,'validator');\n" }, { "answer_id": 11526791, "author": "Christophe Deliens", "author_id": 1340956, "author_profile": "https://Stackoverflow.com/users/1340956", "pm_score": 3, "selected": false, "text": "$('input, select, textarea').each(function() {\n $(this).rules('remove');\n});\n" }, { "answer_id": 12094652, "author": "alby", "author_id": 1620198, "author_profile": "https://Stackoverflow.com/users/1620198", "pm_score": 3, "selected": false, "text": "jQuery('#form').validate();\n jQuery('#form').validate().currentForm = '';\n jQuery('#form').validate().currentForm = jQuery('#form')[0];\n" }, { "answer_id": 17430020, "author": "user2543317", "author_id": 2543317, "author_profile": "https://Stackoverflow.com/users/2543317", "pm_score": 2, "selected": false, "text": "$('#myform').validate().settings.ignore = '.valid';\n$('input').addClass('valid');\n" }, { "answer_id": 41097446, "author": "Veena Lalwani", "author_id": 7284114, "author_profile": "https://Stackoverflow.com/users/7284114", "pm_score": 3, "selected": false, "text": "$(\"#formName\").validate().settings.ignore = \"*\";\n" }, { "answer_id": 73766699, "author": "Adel Mourad", "author_id": 1594274, "author_profile": "https://Stackoverflow.com/users/1594274", "pm_score": 0, "selected": false, "text": "function RemoveJQVRule(rulename, inputname) {\n $(`[name=\"${inputname}\"]`).rules('remove', rulename);\n $(`[name=\"${inputname}\"]`).removeAttr(`data-val-${rulename}`);\n\n // message span element\n $(`#${inputname.replace(/\\./img, '_')}-error`).html(\"\");\n $(`[data-valmsg-for=\"${inputname}\"]`).html(\"\");\n}\n RemoveJQVRule('required', 'Shipper.Contact.NationalId');\n RemoveJQVRule('maxlength-max', 'SomeInputName');\n RemoveJQVRule('regex', 'SomeInputName');\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6705/" ]
363,276
<p>How can I hide the div without using <code>display:none</code> or JavaScript?</p> <p>In my country, a lot of Blackberrys come with the CSS support disabled (the mobile companies here are not so good to developers). I have text that says</p> <pre><code>&lt;div class="BBwarn"&gt; please activate your css support and a link &lt;/div&gt; </code></pre> <p>I want to hide that once the user activates CSS support, but i can't use <code>display:none;</code> because it is only supported in BB firmware 4.6. It is a public site and I can't make all my visitors upgrade.</p> <p>Does anybody knows a solution to this? I hope the question is easier to understand now.</p> <p>Update: Thank you all for the answers but I can't use </p> <ul> <li>position:absolute</li> <li>overflow</li> </ul> <p>because they are available from Blackberry firmware 4.6 and up</p>
[ { "answer_id": 363290, "author": "krusty.ar", "author_id": 43981, "author_profile": "https://Stackoverflow.com/users/43981", "pm_score": 4, "selected": false, "text": "margin-left: -9999;" }, { "answer_id": 363321, "author": "cLFlaVA", "author_id": 45109, "author_profile": "https://Stackoverflow.com/users/45109", "pm_score": 2, "selected": false, "text": "visibility: hidden; div left-margin position absolute" }, { "answer_id": 363480, "author": "Daniel Schaffer", "author_id": 2596, "author_profile": "https://Stackoverflow.com/users/2596", "pm_score": 3, "selected": false, "text": "<div style=\"height:0;width:0;overflow:hidden;\">\n<!-- content here -->\n</div>\n" }, { "answer_id": 364460, "author": "John_", "author_id": 26081, "author_profile": "https://Stackoverflow.com/users/26081", "pm_score": 3, "selected": false, "text": "position: absolute;\nleft: -1000px;\n" }, { "answer_id": 369269, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 4, "selected": false, "text": " visibility: hidden;\n" }, { "answer_id": 369278, "author": "cLFlaVA", "author_id": 45109, "author_profile": "https://Stackoverflow.com/users/45109", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\"><!--\ndocument.open();\ndocument.writeln('<div class=\"BBwarn\">');\ndocument.writeln('please activate your css support and a link');\ndocument.writeln('</div>');\ndocument.close();\n//--></script>\n" }, { "answer_id": 369924, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 3, "selected": false, "text": "height: 0; \noverflow: hidden;\nvisibility: hidden; \ncolor: #fff; \nbackground: #fff; \n" }, { "answer_id": 382740, "author": "mercator", "author_id": 23263, "author_profile": "https://Stackoverflow.com/users/23263", "pm_score": 3, "selected": false, "text": "display: none display display: none display .BBwarn {\n display: none; /* for 4.6 and up */\n width: 0px; /* for 4.3 */\n height: 0px;\n}\n width height <button> <img> <input> alt" }, { "answer_id": 5418094, "author": "Jayme Tosi Neto", "author_id": 311829, "author_profile": "https://Stackoverflow.com/users/311829", "pm_score": 0, "selected": false, "text": "display\noverflow\nposition: absolute\nvisibility\nz-index\n .element\n{\n width: 100px;\n height: 100px;\n font-size: 12px;\n color: black;\n background-color: transparent;\n border: 1px solid black;\n}\n.element_hidden\n{\n width: 0px;\n height: 0px;\n font-size: 0px;\n color: white;\n background-color: white;\n border: none;\n}\n" }, { "answer_id": 34180261, "author": "Chaitanya Chauhan", "author_id": 2656795, "author_profile": "https://Stackoverflow.com/users/2656795", "pm_score": 1, "selected": false, "text": ".class{\nopacity:0; overflow:hidden; visibility: hidden; height:0;\n}\n color:transparent; background-color:transparent;\n" }, { "answer_id": 52218529, "author": "Abhilesh Srivastava", "author_id": 5858018, "author_profile": "https://Stackoverflow.com/users/5858018", "pm_score": 2, "selected": false, "text": "clip: rect(0,0,0,0);\n <div class=\"BBwarn\">\n please activate your css support and a link\n</div>\n .BBwarn{\n position: absolute;\n clip: rect(0,0,0,0);\n}\n" }, { "answer_id": 53722546, "author": "Praveen", "author_id": 8224095, "author_profile": "https://Stackoverflow.com/users/8224095", "pm_score": 0, "selected": false, "text": ". BBwarn{\n transform : scale(0,0);\n}\n" }, { "answer_id": 53882084, "author": "Ronak Bokaria", "author_id": 5118013, "author_profile": "https://Stackoverflow.com/users/5118013", "pm_score": 0, "selected": false, "text": "font-size: 0px;\n" }, { "answer_id": 57777420, "author": "Jamil Ahmed", "author_id": 2912116, "author_profile": "https://Stackoverflow.com/users/2912116", "pm_score": 0, "selected": false, "text": "color font-size .alert1 {\n color: #fff; //3.8 or later\n \n}\n\n.alert2 {\n font-size: 0; //3.8 or later\n} <b>Alert1</b>\n<div class=\"alert1\">\nplease activate your css support and a link\n</div>\n\n<b>Alert2</b>\n<div class=\"alert2\">\nplease activate your css support and a link\n</div>" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45759/" ]
363,285
<p>I go to <a href="https://mywebsite/MyApp/Myservice.svc" rel="noreferrer">https://mywebsite/MyApp/Myservice.svc</a> and get the following error:</p> <p>(The link works if I use http:// )</p> <p>"<em>The service '/MyApp/MyService.svc' cannot be activated due to an exception during compilation. The exception message is: Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http]..</em>"</p> <p><strong>EDIT:</strong> So if I change <code>address=""</code> to <code>address="https:// ..."</code> then I get this error instead:</p> <p>"<em>Error: The protocol 'https' is not supported..... The ChannelDispatcher at '<a href="https://.../Annotation.svc" rel="noreferrer">https://.../Annotation.svc</a>' with contract(s) '"Annotation"' is unable to open its IChannelListener.</em>"</p> <p>Here's what my <code>Web.Config</code> looks like:</p> <pre><code>&lt;services&gt; &lt;service behaviorConfiguration="AnnotationWCF.AnnotationBehavior" name="AnnotationWCF.Annotation"&gt; &lt;endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Annotation" contract="AnnotationWCF.Annotation" /&gt; &lt;endpoint address="" binding="basicHttpBinding" bindingConfiguration="SecureTransport" contract="AnnotationWCF.Annotation" /&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;/service&gt; </code></pre> <p></p> <pre><code>&lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="BasicHttpBinding_Annotation" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"&gt; &lt;readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /&gt; &lt;/binding&gt; &lt;binding name="SecureTransport" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"&gt; &lt;security mode="Transport"&gt; &lt;transport clientCredentialType="None"/&gt; &lt;/security&gt; &lt;readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; </code></pre>
[ { "answer_id": 364296, "author": "Sixto Saez", "author_id": 9711, "author_profile": "https://Stackoverflow.com/users/9711", "pm_score": 2, "selected": false, "text": "<service type=\"HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null\">\n <endpoint\n address=\"http://computer:8080/Hello\"\n contract=\"HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null\"\n binding=\"basicHttpBinding\"\n bindingConfiguration=\"shortTimeout\"\n </endpoint>\n <endpoint\n address=\"http://computer:8080/Hello\"\n contract=\"HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null\"\n binding=\"basicHttpBinding\"\n bindingConfiguration=\"Secure\"\n </endpoint>\n</service>\n<bindings>\n <basicHttpBinding \n name=\"shortTimeout\"\n timeout=\"00:00:00:01\" \n />\n <basicHttpBinding \n name=\"Secure\">\n <Security mode=\"Transport\" />\n </basicHttpBinding>\n</bindings>\n" }, { "answer_id": 458765, "author": "Mike Blandford", "author_id": 28643, "author_profile": "https://Stackoverflow.com/users/28643", "pm_score": 5, "selected": true, "text": "<endpoint address=\"\" listenUri=\"http://[LOAD_BALANCER_ADDRESS]\" ... />\n" }, { "answer_id": 6133332, "author": "MacGyver", "author_id": 640205, "author_profile": "https://Stackoverflow.com/users/640205", "pm_score": 5, "selected": false, "text": "<services>\n <service behaviorConfiguration=\"ServiceBehavior\" name=\"LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService\">\n <endpoint behaviorConfiguration=\"AspNetAjaxBehavior\" binding=\"webHttpBinding\" bindingConfiguration=\"webBinding\" \n contract=\"LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService\" />\n <endpoint address=\"mex\" binding=\"mexHttpsBinding\" contract=\"IMetadataExchange\" />\n </service>\n" }, { "answer_id": 9102972, "author": "atconway", "author_id": 410937, "author_profile": "https://Stackoverflow.com/users/410937", "pm_score": 0, "selected": false, "text": " <webHttpBinding>\n <binding name=\"MyWCFServiceEndpoint\">\n <security mode=\"Transport\" />\n </binding>\n </webHttpBinding>\n" }, { "answer_id": 10024621, "author": "Sandeep Polavarapu", "author_id": 322022, "author_profile": "https://Stackoverflow.com/users/322022", "pm_score": 1, "selected": false, "text": "<bindings>\n <webHttpBinding>\n <binding name=\"webHttpSecure\">\n <security mode=\"Transport\">\n <transport clientCredentialType=\"Windows\" ></transport>\n </security>\n </binding>\n </webHttpBinding>\n</bindings>\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28643/" ]
363,286
<p>I have used a jQuery multiple file upload control [ MultiFile from fyneworks <a href="http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Overview" rel="nofollow noreferrer">http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Overview</a> ] to collect some filenames but can't work out how to upload them on the server. </p> <p>The standard asp:FileUpload control only seems to allow single files and I don't want to use the swfupload control, just plain old aspx.</p>
[ { "answer_id": 363289, "author": "Steve Davies", "author_id": 24209, "author_profile": "https://Stackoverflow.com/users/24209", "pm_score": 3, "selected": false, "text": "HttpFileCollection hfc = Request.Files;\nfor (int i = 0; i < hfc.Count; i++)\n{\n HttpPostedFile hpf = hfc[i];\n if (hpf.ContentLength > 0)\n { \n hpf.SaveAs(Server.MapPath(\"Uploads\") + \"\\\\\" + System.IO.Path.GetFileName(hpf.FileName));\n }\n} \n" }, { "answer_id": 1790129, "author": "soe", "author_id": 217810, "author_profile": "https://Stackoverflow.com/users/217810", "pm_score": 1, "selected": false, "text": " HttpPostedFile upload = (HttpPostedFile)uploads[i];\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24209/" ]
363,295
<p>I'm trying to follow code-to-interface on a project. Should I be creating an interface first then implementing that interface for entity classes? I'm thinking this might be taking the interface first approach too far and entities should be ignored. This is what I mean...</p> <pre><code>public interface Address { public String getStreet(); public void setStreet(String street); } @Entity public class AddressImpl implements Address { private String street; public String getStreet(){ return this.street; } public void setStreet(String street){ this.street = street; } } @Entity public class OfficeImpl /* implements Office */ { private Address location; public Address getLocation(){ return this.location; } public void setLocation(Address location){ this.location = location; } } public class Driver { public static void main(String[] args) { Office work = new OfficeImpl(); Address workAddress = new AddressImpl(); workAddress.setStreet("Main St."); work.setLocation(workAddress); } } </code></pre>
[ { "answer_id": 363354, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 1, "selected": false, "text": "interface IFlaggable {\n bool IsFlagged ...\n string Reason ...\n}\n\nclass ForumPost implements IFlaggable { }\n\nclass PrivateMessage implements IFlaggable { }\n" }, { "answer_id": 363374, "author": "Esko", "author_id": 44523, "author_profile": "https://Stackoverflow.com/users/44523", "pm_score": 0, "selected": false, "text": "Reflector r = new Reflector(new DataBean( [ values given through constructor ] ));\nlong someNumber = r.get(\"method\", Long.class);\n" }, { "answer_id": 363385, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "public interface IEntity\n{\n int EntityId { get; set; }\n bool FindById(int id);\n bool Create(object [] values);\n bool Delete(int id);\n //etc.\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1294/" ]
363,302
<p>I'm trying to display a picture in an openGL environment. The picture's origninal dimensions are 3648x2432, and I want to display it with a 256x384 image. The problem is, 384 is not a power of 2, and when I try to display it, it looks stretched. How can I fix that?</p>
[ { "answer_id": 363378, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "GL_ARB_texture_non_power_of_two" }, { "answer_id": 363419, "author": "Jay Conrod", "author_id": 1891, "author_profile": "https://Stackoverflow.com/users/1891", "pm_score": 0, "selected": false, "text": "ARB_texture_rectangle GL_TEXTURE_RECTANGLE_ARB GL_TEXTURE_2D" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45762/" ]
363,320
<p>I've seen the designer code, and I have seen code which builds the ObjectDataSource in the code-behind, however both methods communicate directly with the database via either text commands or stored procs. This seems like unnecessary code duplication to me since my data access layer has a method already which returns a datatable with the data I need for this report. </p> <p>How can I programmatically build and link the ODS to my data access layer's method?</p> <p>EDIT: </p> <p>Thanks to everyone who answered. This was very poorly phrased on my part. There was too much that I did not understand when I wrote this question originally. What I should have asked is: </p> <p>How do I programmatically bind a .Net Reporting Services Report (*.rdlc) to a method in my Data Access Layer instead of an ADO.Net DataSet.</p> <p>See my answer below. </p>
[ { "answer_id": 364455, "author": "chriscena", "author_id": 32671, "author_profile": "https://Stackoverflow.com/users/32671", "pm_score": 0, "selected": false, "text": "<asp:ObjectDataSource ID=\"ObjectDataSource1\" runat=\"server\" \nSelectMethod=\"[InsertYourMethodHere]\" TypeName=\"[InsertYourDALClassHere]\">\n<SelectParameters>\n[Add Your Parameters Here]\n</SelectParameters>\n</asp:ObjectDataSource>\n" }, { "answer_id": 372541, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 3, "selected": true, "text": "<rsweb:ReportViewer ID=\"ReportViewer1\" runat=\"server\" Font-Names=\"Verdana\"\n Font-Size=\"8pt\" Height=\"655px\" Width=\"980px\">\n <ServerReport ReportServerUrl=\"\" />\n <LocalReport>\n\n </LocalReport>\n</rsweb:ReportViewer>\n ReportViewer1.ProcessingMode = ProcessingMode.Local\nDim report As LocalReport = ReportViewer1.LocalReport\nreport.ReportPath = \"<your report path>\"\nreport.DataSources.Clear()\n\nDim rds As New ReportDataSource()\nrds.Name = \"<dataset name>_<stored proc name>\"\nrds.Value = <your DAL method ()>\n\nreport.DataSources.Add(rds)\nreport.Refresh()\n" }, { "answer_id": 33101343, "author": "Siniša Bencetić", "author_id": 4453711, "author_profile": "https://Stackoverflow.com/users/4453711", "pm_score": 1, "selected": false, "text": "//Create object data source\nObjectDataSource objDataSource = new ObjectDataSource();\nobjDataSource.TypeName = \"Data.Models.Reports.MyRepository\";\nobjDataSource.SelectMethod = \"GetMyReport\";\n//Add parameters if any ...\nobjDataSource.SelectParameters.Add(\"Param1\", \"\");\n ReportDataSource rptDataSource = new ReportDataSource(\"DataSet1\",objDataSource);\nreportViewer.LocalReport.DataSources.Add(rptDataSource);\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149/" ]
363,324
<p>I have the following code, which will not work. The javascript gives no errors and appears to load fine. but clicking on a link will do nothing. An example of a link is:</p> <pre><code>&lt;a href="#" onclick="updateByQuery('Layer3', "Ed Hardy");"&gt;Link 1&lt;/a&gt;&lt;li&gt;Link 2&lt;/li&gt; </code></pre> <p>and the code:</p> <pre><code>var xmlHttp var layername var url function update(layer, url) { var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere if(xmlHttp==null) { alert("Your browser is not supported?"); } xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById(layer).innerHTML=xmlHttp.responseText; } else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") { document.getElementById(layer).innerHTML="loading"; } //etc } xmlHttp.open("GET",url,true); xmlHttp.send(null); } function updateByPk(layer, pk) { url = "get_auction.php?cmd=GetAuctionData&amp;pk="+pk+"&amp;sid="+Math.random(); update(layer, url); } function updateByQuery(layer, query) { url = "get_records.php?cmd=GetRecordSet&amp;query="+query+"&amp;sid="+Math.random(); update(layer, url); } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); }catch (e) { try { xmlHttp =new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } return xmlHttp; } function makewindows(){ child1 = window.open ("about:blank"); child1.document.write(&lt;?php echo htmlspecialchars(json_encode($row2["ARTICLE_DESC"]), ENT_QUOTES); ?&gt;); child1.document.close(); } </code></pre>
[ { "answer_id": 363345, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 3, "selected": true, "text": "<a href=\"#\" onclick=\"updateByQuery('Layer3', 'Ed Hardy');\">Link 1</a><li>Link 2</li>\n" }, { "answer_id": 363390, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "var xmlHttp\nvar layername\nvar url\n\nxmlHttp.onreadystatechange = function() {\n if(xmlHttp.readyState==4 || xmlHttp.readyState==\"complete\") {\n document.getElementById(layer).innerHTML=xmlHttp.responseText;\n } else if (xmlHttp.readyState==1 || xmlHttp.readyState==\"loading\") {\n document.getElementById(layer).innerHTML=\"loading\";\n }\n\n //etc\n }\n try\n {\n xmlHttp=new XMLHttpRequest();\n }catch (e)\n {\n\n try\n {\n xmlHttp =new ActiveXObject(\"Microsoft.XMLHTTP\");\n } \n catch (e) {}\n\n }\n" }, { "answer_id": 363395, "author": "cLFlaVA", "author_id": 45109, "author_profile": "https://Stackoverflow.com/users/45109", "pm_score": 0, "selected": false, "text": "child1.document.write(<?php echo htmlspecialchars(json_encode($row2[\"ARTICLE_DESC\"]), ENT_QUOTES); ?>);\n child1.document.write(\"<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>\");\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
363,325
<p>I would like to parse a document using SAX, and create a subdocument from some of the elements, while processing others purely with SAX. So, given this document:</p> <pre><code> &lt;DOC&gt; &lt;small&gt; &lt;element /&gt; &lt;/small&gt; &lt;entries&gt; &lt;!-- thousands here --&gt; &lt;/entries&gt; &lt;/DOC&gt; </code></pre> <p>I would like to parse the DOC and DOC/entries elements using the SAX ContentHandler, but when I hit <code>&lt;small&gt;</code> I want to create a new document containing just the <code>&lt;small&gt;</code> and its children.</p> <p>Is there an easy way to do this, or do I have to build the DOM myself, by hand?</p>
[ { "answer_id": 363636, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": true, "text": "ContentHandler <small> ContentHandler <small> TransformerHandler DOMResult TransformerHandler startElement setDocumentLocator startDocument TransformerHandler <small> TransformerHandler ContentHandler </small> endDocument TransformerHandler TransformerHandler <small />" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23309/" ]
363,326
<p>What is the best way to get a value from a ICollection? We know the Collection is empty apart from that. </p>
[ { "answer_id": 363386, "author": "Chris", "author_id": 44360, "author_profile": "https://Stackoverflow.com/users/44360", "pm_score": 5, "selected": false, "text": "foreach(object o in collection) {\n return o;\n}\n IEnumerator en = collection.GetEnumerator();\nen.MoveNext();\nreturn en.Current;\n IList iList = collection as IList;\nif (iList != null) {\n // Implements IList, so can use indexer\n return iList[0];\n}\n// Use the slower way\nforeach (object o in collection) {\n return o;\n}\n" }, { "answer_id": 363434, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 3, "selected": false, "text": "ICollection IEnumerable List<string> l = new List<string>();\nl.Add(\"astring\");\n\nICollection col1 = (ICollection)l;\nICollection<string> col2 = (ICollection<string>)l;\n\n//example 1\nIEnumerator e1 = col1.GetEnumerator();\nif (e1.MoveNext())\n Console.WriteLine(e1.Current);\n\n//example 2\nif (col2.Count != 0)\n Console.WriteLine(col2.Single());\n" }, { "answer_id": 363474, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "var foo = myICollection.OfType<YourType>().FirstOrDefault();\n// or use a query\nvar bar = (from x in myICollection.OfType<YourType>() where x.SomeProperty == someValue select x)\n .FirstOrDefault();\n" }, { "answer_id": 21689066, "author": "mehrdad seyrafi", "author_id": 1494051, "author_profile": "https://Stackoverflow.com/users/1494051", "pm_score": 3, "selected": false, "text": "collection.ToArray()[i]\n" }, { "answer_id": 49596764, "author": "JAD", "author_id": 6822618, "author_profile": "https://Stackoverflow.com/users/6822618", "pm_score": 0, "selected": false, "text": "Single() ICollection<T> T InvalidOperationException" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
363,336
<p>This is driving me nuts. I am using some 3rd-party code in a Windows .lib that, in debug mode, is causing an error similar to the following:</p> <pre><code>Run-Time Check Failure #2 - Stack around the variable 'foo' was corrupted. </code></pre> <p>The error is thrown when either the object goes out of scope or is deleted. Simply allocating one of these objects and then deleting it will throw the error. I therefore think the problem is either in one of the many constructors/destructors but despite stepping through every line of code I cannot find the problem.</p> <p>However, this only happens when creating one of these objects in a static library. If I create one in my EXE application, the error does not appear. The 3rd-party code itself lives in a static lib. For example, this fails:</p> <pre><code>**3RDPARTY.LIB** class Foo : public Base { ... }; **MY.LIB** void Test() { Foo* foo = new Foo; delete foo; // CRASH! } **MY.EXE** void Func() { Test(); } </code></pre> <p>But this will work:</p> <pre><code>**3RDPARTY.LIB** class Foo : public Base { ... }; **MY.EXE** void Func() { Foo* foo = new Foo; delete foo; // NO ERROR } </code></pre> <p>So, cutting out the 'middle' .lib file makes the problem go away and it is this weridness that is driving me mad. The EXE and 2 libs all use the same CRT library. There are no errors linking. The 3rd-party code uses inheritance and there are 5 base classes. I've commented out as much code as I can whilst still getting it to build and I just can't see what's up.</p> <p>So if anyone knows why code in a .lib would act differently to the same code in a .exe, I would love to hear it. Ditto any tips for tracking down memory overwrites! I am using Visual Studio 2008.</p>
[ { "answer_id": 363365, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 0, "selected": false, "text": "operator delete" }, { "answer_id": 368431, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 3, "selected": true, "text": "_WIN32_WINNT 0x0501 0x0600 sspi.h SecurityFunctionTable #if OSVER(NTDDI_VERSION) > NTDDI_WIN2K\n // Fields below this are available in OSes after w2k\n SET_CONTEXT_ATTRIBUTES_FN_W SetContextAttributesW;\n#endif // greater thean 2K\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
363,341
<p>As someone in the world of <a href="http://en.wikipedia.org/wiki/High-performance_computing" rel="noreferrer">HPC</a> who came from the world of enterprise web development, I'm always curious to see how developers back in the "real world" are taking advantage of parallel computing. This is much more relevant now that <a href="http://www.gotw.ca/publications/concurrency-ddj.htm" rel="noreferrer">all chips are going multicore</a>, and it'll be even more relevant when there are thousands of cores on a chip instead of just a few.</p> <p>My questions are: </p> <ol> <li>How does this affect your software roadmap?</li> <li>I'm particularly interested in real stories about how multicore is affecting different software domains, so specify what kind of development you do in your answer (<em>e.g.</em> server side, client-side apps, scientific computing, etc).</li> <li>What are you doing with your existing code to take advantage of multicore machines, and what challenges have you faced? Are you using <a href="http://www.openmp.org/" rel="noreferrer">OpenMP</a>, <a href="http://www.erlang.org/" rel="noreferrer">Erlang</a>, <a href="http://www.haskell.org/" rel="noreferrer">Haskell</a>, <a href="http://en.wikipedia.org/wiki/CUDA" rel="noreferrer">CUDA</a>, <a href="http://www.threadingbuildingblocks.org/" rel="noreferrer">TBB</a>, <a href="http://upc.lbl.gov/" rel="noreferrer">UPC</a> or something else?</li> <li>What do you plan to do as concurrency levels continue to increase, and how will you deal with hundreds or thousands of cores?</li> <li>If your domain <em>doesn't</em> easily benefit from parallel computation, then explaining why is interesting, too.</li> </ol> <p>Finally, I've framed this as a multicore question, but feel free to talk about other types of parallel computing. If you're porting part of your app to use <a href="http://labs.google.com/papers/mapreduce.html" rel="noreferrer">MapReduce</a>, or if <a href="http://www.open-mpi.org/" rel="noreferrer">MPI</a> on large clusters is the paradigm for you, then definitely mention that, too.</p> <p><strong>Update:</strong> If you do answer #5, mention whether you think things will change if there get to be more cores (100, 1000, etc) than you can feed with available memory bandwidth (seeing as how bandwidth is getting smaller and smaller per core). Can you still use the remaining cores for your application?</p>
[ { "answer_id": 363475, "author": "Dmitri Nesteruk", "author_id": 9476, "author_profile": "https://Stackoverflow.com/users/9476", "pm_score": 3, "selected": false, "text": "for Parallel.For" }, { "answer_id": 366657, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 3, "selected": false, "text": "make gmake -j\n -j" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9122/" ]
363,351
<p>I'm curious as I begin to adopt more of the boost idioms and what appears to be best practices I wonder at what point does my c++ even remotely look like the c++ of yesteryear, often found in typical examples and in the minds of those who've not been introduced to "Modern C++"?</p>
[ { "answer_id": 363408, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "boost::shared_ptr<int> ptr(new int);\n" }, { "answer_id": 363472, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 3, "selected": false, "text": "shared_ptr boost::scoped_ptr boost::scoped_ptr<SomeType> my_object(new SomeType);\nsome_function(my_object.get());\n some_function void some_function(SomeType* some_obj)\n{\n assert (some_obj);\n some_obj->whatever();\n}\n" }, { "answer_id": 363476, "author": "Cristián Romo", "author_id": 1256, "author_profile": "https://Stackoverflow.com/users/1256", "pm_score": 2, "selected": false, "text": "delete" }, { "answer_id": 363509, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 2, "selected": false, "text": "unique_ptr" }, { "answer_id": 364123, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 0, "selected": false, "text": "std::list<> boost::graph<>" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44996/" ]
363,356
<p>I have a HTML table issue that I'd like to understand better.</p> <p>Let's assume that I have a 3 row HTML</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td style="text-align:right;"&gt;A1&lt;/td&gt; &lt;td&gt;A2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="text-align:right;"&gt;B1&lt;/td&gt; &lt;td&gt;B2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt;A very loooooooong string here&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>With a very long text, the contents in the first 2 rows appear like they are nearly centered. However, if I move the whole "A very long string" <code>&lt;td&gt;</code> into a separate <code>&lt;table&gt;</code> inside the row, I see that the other content doesn't center. Why is the display different when the <code>&lt;td&gt;</code> content is inside another table?</p>
[ { "answer_id": 363375, "author": "cLFlaVA", "author_id": 45109, "author_profile": "https://Stackoverflow.com/users/45109", "pm_score": 0, "selected": false, "text": "<table border=\"1\">\n <tr>\n <td style=\"text-align:right;\">A1</td>\n <td>A2</td>\n </tr>\n <tr>\n <td style=\"text-align:right;\">B1</td>\n <td>B2</td>\n </tr>\n <tr>\n <td colspan=\"2\">\n <table border=\"1\"><tr>\n <td>A very loooooooong string here</td>\n </tr></table>\n </td>\n </tr>\n</table>\n" }, { "answer_id": 363402, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<table>\n <tr>\n <td style=\"text-align:right;\">A1</td>\n <td>A2</td>\n </tr>\n <tr>\n <td style=\"text-align:right;\">B1</td>\n <td>B2</td>\n </tr>\n <tr>\n <td colspan=\"2\"><table><tr><td>A very loooooooong string here</td></tr></table></td>\n </tr>\n</table>\n" }, { "answer_id": 363428, "author": "James Piggot", "author_id": 28213, "author_profile": "https://Stackoverflow.com/users/28213", "pm_score": -1, "selected": false, "text": "<table>\n <tr>\n <td style=\"text-align:right;\">A1</td>\n <td>A2</td>\n </tr>\n <tr>\n <td style=\"text-align:right;\">B1</td>\n <td>B2</td>\n </tr>\n <tr>\n <table><td colspan=\"2\">A very loooooooong string here</td></table>\n </tr>\n</table>\n" }, { "answer_id": 604609, "author": "random", "author_id": 9314, "author_profile": "https://Stackoverflow.com/users/9314", "pm_score": 1, "selected": false, "text": "<table>\n <tr>\n <td style=\"text-align:right;\">A1</td>\n <td>A2</td>\n </tr>\n <tr>\n <td style=\"text-align:right;\">B1</td>\n <td>B2</td>\n </tr>\n</table>\n <table>\n <tr>\n <td colspan=\"2\">A very loooooooong string here</td>\n </tr>\n</table>\n border=\"1\"" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11541/" ]
363,370
<p>I'm writing a database application that connects to SQL server. I'd like to implement a similar connection dialog box like the one in SQL Management Studio. I've already found a way to get the list of databases on a server, but I'd really like to get the list of available servers on the network so end users won't have to type in the name/IP of the server.</p>
[ { "answer_id": 363406, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": true, "text": "CREATE PROCEDURE dbo.ListLocalServers \nAS \nBEGIN \n SET NOCOUNT ON \n\n CREATE TABLE #servers(sname VARCHAR(255)) \n\n INSERT #servers EXEC master..XP_CMDShell 'OSQL -L' \n -- play with ISQL -L too, results differ slightly \n\n DELETE #servers WHERE sname='Servers:' \n\n SELECT LTRIM(sname) FROM #servers WHERE sname != 'NULL' \n\n DROP TABLE #servers \nEND\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5906/" ]
363,377
<p>I have a bit of code that I need to run in a different thread than the GUI as it currently causes the form to freeze whilst the code runs (10 seconds or so). </p> <p>Assume I have never created a new thread before; what's a simple/basic example of how to do this in C# and using .NET Framework 2.0 or later? </p>
[ { "answer_id": 363407, "author": "FallenAvatar", "author_id": 36965, "author_profile": "https://Stackoverflow.com/users/36965", "pm_score": 6, "selected": false, "text": "using System.Threading;\n static void Main( string[] args )\n{\n Thread t = new Thread( NewThread );\n t.Start();\n}\n\nstatic void NewThread()\n{\n //code goes here\n}\n" }, { "answer_id": 363409, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 7, "selected": false, "text": "System.Threading.ThreadPool.QueueUserWorkItem(delegate {\n DoSomethingThatDoesntInvolveAControl();\n}, null);\n" }, { "answer_id": 363413, "author": "Redbaron", "author_id": 41, "author_profile": "https://Stackoverflow.com/users/41", "pm_score": 3, "selected": false, "text": "Thread myThread= new Thread(nameOfFunction); workerThread.Start();" }, { "answer_id": 363424, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 1, "selected": false, "text": "// following declaration of delegate ,,,\npublic delegate long GetEnergyUsageDelegate(DateTime lastRunTime, \n DateTime procDateTime);\n\n// following inside of some client method \nGetEnergyUsageDelegate nrgDel = GetEnergyUsage; \nIAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);\nwhile (!aR.IsCompleted) Thread.Sleep(500);\nint usageCnt = nrgDel.EndInvoke(aR);\n" }, { "answer_id": 363553, "author": "IgorK", "author_id": 44647, "author_profile": "https://Stackoverflow.com/users/44647", "pm_score": 0, "selected": false, "text": "CheckAccess() BeginInvoke" }, { "answer_id": 481099, "author": "Matt Davison", "author_id": 1995476, "author_profile": "https://Stackoverflow.com/users/1995476", "pm_score": 2, "selected": false, "text": "// following declaration of delegate ,,,\npublic delegate long GetEnergyUsageDelegate(DateTime lastRunTime, \n DateTime procDateTime);\n\n// following inside of some client method\nGetEnergyUsageDelegate nrgDel = GetEnergyUsage;\nIAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);\nwhile (!aR.IsCompleted) Thread.Sleep(500);\nint usageCnt = nrgDel.EndInvoke(aR);\n nrgDel.EndInvoke(nrgDel.BeginInvoke(lastRuntime,procDT,null,null));\n ar.AsyncWaitHandle.WaitOne();\n nrgDel.BeginInvoke(lastRuntime,procDT,(ar)=> {ar.EndInvoke(ar);},null);\n" }, { "answer_id": 481146, "author": "user50612", "author_id": 50612, "author_profile": "https://Stackoverflow.com/users/50612", "pm_score": 2, "selected": false, "text": "public static void DoWork()\n{\n // do some work\n}\n\npublic static void StartWorker()\n{\n Thread worker = new Thread(DoWork);\n worker.IsBackground = true;\n worker.SetApartmentState(System.Threading.ApartmentState.STA);\n worker.Start()\n}\n" }, { "answer_id": 482210, "author": "Gant", "author_id": 12460, "author_profile": "https://Stackoverflow.com/users/12460", "pm_score": 8, "selected": false, "text": "BackgroundWorker using System.ComponentModel;\n...\n private void button1_Click(object sender, EventArgs e)\n {\n BackgroundWorker bw = new BackgroundWorker();\n\n // this allows our worker to report progress during work\n bw.WorkerReportsProgress = true;\n\n // what to do in the background thread\n bw.DoWork += new DoWorkEventHandler(\n delegate(object o, DoWorkEventArgs args)\n {\n BackgroundWorker b = o as BackgroundWorker;\n\n // do some simple processing for 10 seconds\n for (int i = 1; i <= 10; i++)\n {\n // report the progress in percent\n b.ReportProgress(i * 10);\n Thread.Sleep(1000);\n }\n\n });\n\n // what to do when progress changed (update the progress bar for example)\n bw.ProgressChanged += new ProgressChangedEventHandler(\n delegate(object o, ProgressChangedEventArgs args)\n {\n label1.Text = string.Format(\"{0}% Completed\", args.ProgressPercentage);\n });\n\n // what to do when worker completes its task (notify the user)\n bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(\n delegate(object o, RunWorkerCompletedEventArgs args)\n {\n label1.Text = \"Finished!\";\n });\n\n bw.RunWorkerAsync();\n }\n ProgressChanged RunWorkerCompleted DoWork InvalidOperationException" }, { "answer_id": 1239662, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "var someValue;\n\nThread thread = new Thread(delegate()\n { \n //Do somthing and set your value\n someValue = \"Hello World\";\n });\n\nthread.Start();\n\nwhile (thread.IsAlive)\n Application.DoEvents();\n" }, { "answer_id": 13611139, "author": "Ed Power", "author_id": 150058, "author_profile": "https://Stackoverflow.com/users/150058", "pm_score": 9, "selected": false, "text": "using System.Threading;\nnew Thread(() => \n{\n Thread.CurrentThread.IsBackground = true; \n /* run your code here */ \n Console.WriteLine(\"Hello, world\"); \n}).Start();\n" }, { "answer_id": 31778592, "author": "Spongebob Comrade", "author_id": 970420, "author_profile": "https://Stackoverflow.com/users/970420", "pm_score": 6, "selected": false, "text": "Task.Run(()=>{\n//Here is a new thread\n});\n" }, { "answer_id": 40060324, "author": "Ammar Alyasry", "author_id": 5056044, "author_profile": "https://Stackoverflow.com/users/5056044", "pm_score": 3, "selected": false, "text": " public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n }\n Thread t, t2, t3;\n private void Form1_Load(object sender, EventArgs e)\n {\n\n CheckForIllegalCrossThreadCalls = false;\n\n t = new Thread(birinicBar); //evry thread workes with a new progressBar\n\n\n t2 = new Thread(ikinciBar);\n\n\n t3 = new Thread(ucuncuBar);\n\n }\n\n public void birinicBar() //to make progressBar work\n {\n for (int i = 0; i < 100; i++) {\n progressBar1.Value++;\n Thread.Sleep(100); // this progressBar gonna work faster\n }\n }\n\n public void ikinciBar()\n {\n for (int i = 0; i < 100; i++)\n {\n progressBar2.Value++;\n Thread.Sleep(200);\n }\n\n\n }\n\n public void ucuncuBar()\n {\n for (int i = 0; i < 100; i++)\n {\n progressBar3.Value++;\n Thread.Sleep(300);\n }\n }\n\n private void button1_Click(object sender, EventArgs e) //that button to start the threads\n {\n t.Start();\n t2.Start(); t3.Start();\n\n }\n\n private void button4_Click(object sender, EventArgs e)//that button to stup the threads with the progressBar\n {\n t.Suspend();\n t2.Suspend();\n t3.Suspend();\n }\n\n private void button2_Click(object sender, EventArgs e)// that is for contuniue after stuping\n {\n t.Resume();\n t2.Resume();\n t3.Resume();\n }\n\n private void button3_Click(object sender, EventArgs e) // finally with that button you can remove all of the threads\n {\n t.Abort();\n t2.Abort();\n t3.Abort();\n }\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
363,425
<p>If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:</p> <blockquote> <p>HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA.............................................................................................................................................</p> </blockquote> <p>I've tried just using <code>wordwrap()</code> in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks.</p> <p>There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE.</p> <p>How do you solve this problem?</p>
[ { "answer_id": 363443, "author": "Tim Knight", "author_id": 43043, "author_profile": "https://Stackoverflow.com/users/43043", "pm_score": 3, "selected": false, "text": "#post{\n width: 500px;\n overflow: scroll;\n}\n auto scroll" }, { "answer_id": 363454, "author": "cLFlaVA", "author_id": 45109, "author_profile": "https://Stackoverflow.com/users/45109", "pm_score": 4, "selected": false, "text": "overflow: auto overflow: auto overflow: scroll auto scroll" }, { "answer_id": 1694133, "author": "Ers", "author_id": 205743, "author_profile": "https://Stackoverflow.com/users/205743", "pm_score": 0, "selected": false, "text": "public static string WrapWords(string text, int maxLength)\n {\n string[] words = text.Split(' ');\n for (int i = 0; i < words.Length; i++)\n {\n if (words[i].Length > maxLength) //long word\n {\n words[i] = words[i].Insert(maxLength, \" \");\n //still long ?\n words[i]=WrapWords(words[i], maxLength);\n }\n }\n text = string.Join(\" \", words);\n return (text);\n }\n" }, { "answer_id": 3958576, "author": "Marcin", "author_id": 193400, "author_profile": "https://Stackoverflow.com/users/193400", "pm_score": 7, "selected": false, "text": "word-wrap:break-word\n" }, { "answer_id": 7363652, "author": "Moritz", "author_id": 937033, "author_profile": "https://Stackoverflow.com/users/937033", "pm_score": -1, "selected": false, "text": "<?php\n $v = \"reallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglink\";\n $v2 = wordwrap($v, 12, \"<br/>\", true);\n?>\n<html>\n <head>\n <title>test</title>\n </head>\n <body>\n <table width=\"300\" border=\"1\">\n <tr height=\"30\">\n <td colspan=\"3\" align=\"center\" valign=\"top\">test</td>\n </tr>\n <tr>\n <td width=\"100\"><a href=\"<?php echo $v; ?>\"><?php echo $v2; ?></a></td>\n <td width=\"100\">&nbsp;</td>\n <td width=\"100\">&nbsp;</td>\n </tr>\n </table>\n </body>\n</html>\n" }, { "answer_id": 7544786, "author": "Fernando Costas - Mercadosweb", "author_id": 963487, "author_profile": "https://Stackoverflow.com/users/963487", "pm_score": 5, "selected": false, "text": "div {\n white-space: pre; /* CSS 2.0 */\n white-space: pre-wrap; /* CSS 2.1 */\n white-space: pre-line; /* CSS 3.0 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: -o-pre-wrap; /* Opera 7 */\n white-space: -moz-pre-wrap; /* Mozilla */\n white-space: -hp-pre-wrap; /* HP Printers */\n word-wrap: break-word; /* IE 5+ */\n}\n" }, { "answer_id": 14008329, "author": "Wylie", "author_id": 610632, "author_profile": "https://Stackoverflow.com/users/610632", "pm_score": 3, "selected": false, "text": "<wbr> &#8203; <wbr> N" }, { "answer_id": 18625234, "author": "Cesar", "author_id": 857291, "author_profile": "https://Stackoverflow.com/users/857291", "pm_score": 0, "selected": false, "text": "//the function:\nBreakLargeWords = function (str)\n{\n BreakLargeWord = function (word)\n {\n var brokenWords = [];\n var wpatt = /\\w{15}|\\w/igm;\n while (wmatch = wpatt.exec(word))\n {\n var brokenWord = wmatch[0];\n brokenWords.push(brokenWord);\n if (brokenWord.length >= 15) brokenWords.push(\"&shy;\");\n }\n return brokenWords.join(\"\");\n }\n\n var match;\n var word = \"\";\n var words = [];\n var patt = /\\W/igm;\n var prevPos = 0;\n while (match = patt.exec(str))\n {\n var pos = match.index;\n var len = pos - prevPos;\n word = str.substr(prevPos, len);\n\n if (word.length > 15) word = BreakLargeWord(word);\n\n words.push(word);\n words.push(match[0]);\n prevPos = pos + 1;\n }\n word = str.substr(prevPos);\n if (word.length > 15) word = BreakLargeWord(word);\n words.push(word);\n var text = words.join(\"\");\n return text;\n}\n\n//how to use\nvar bigText = \"Why is this text this big? Lets do a wrap <b>here</b>! aaaaaaaaaaaaa-bbbbb-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\";\nvar goodText = BreakLargeWords(bigText);\n" }, { "answer_id": 44710585, "author": "Suresh", "author_id": 5597275, "author_profile": "https://Stackoverflow.com/users/5597275", "pm_score": 0, "selected": false, "text": "&#8203; let longWordWithOutSpace = 'pneumonoultramicroscopicsilicovolcanoconiosis';\n// add &#8203; between every character to make it wrap\nlongWordWithOutSpace.split('').join('&#8203;');\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497/" ]
363,453
<p>I have an application that has several objects (about 50 so far, but growing). There is only one instance of each of these objects in the app and these instances get shared among components.</p> <p>What I've done is derive all of the objects from a base BrokeredObject class:</p> <pre><code>class BrokeredObject { virtual int GetInterfaceId() = 0; }; </code></pre> <p>And each object type returns a unique ID. These IDs are maintained in a header file.</p> <p>I then have an ObjectBroker "factory". When someone needs an object, then call GetObjectByID(). The boker looks in an STL list to see if the object already exists, if it does, it returns it. If not, it creates it, puts it in the list and returns it. All well and good.</p> <pre><code>BrokeredObject *GetObjectByID(int id) { BrokeredObject *pObject; ObjectMap::iterator = m_objectList.find(id); // etc. if(found) return pObject; // not found, so create switch(id) { case 0: pObject = new TypeA; break; case 1: pObject = new TypeB; break; // etc. // I loathe this list } // add it to the list return pObject; } </code></pre> <p>What I find painful is maintaining this list of IDs and having to have each class implement it. I have at least made my consumer's lives slightly easier by having each type hold info about it's own ID like this:</p> <pre><code>class TypeA : public BrokeredObject { static int get_InterfaceID() { return IID_TYPEA; } int GetInterfaceID() { return get_InterfaceID(); } }; </code></pre> <p>So I can get an object like this:</p> <pre><code>GetObjectByID(TypeA::get_InterfaceID()); </code></pre> <p>Intead of having to actually know what the ID mapping is but I still am not thrilled with the maintenance and the potential for errors. It seems that if I know the type, why should I also have to know the ID?</p> <p>What I long for is something like this in C#:</p> <pre><code>BrokeredObject GetOrCreateObject&lt;T&gt;() where T : BrokeredObject { return new T(); } </code></pre> <p>Where the ObjectBroker would create the object based on the <em>type</em> passed in.</p> <p>Has C# spoiled me and it's just a fact of life that C++ can't do this or is there a way to achieve this that I'm not seeing?</p>
[ { "answer_id": 363517, "author": "Boyan", "author_id": 38106, "author_profile": "https://Stackoverflow.com/users/38106", "pm_score": 2, "selected": false, "text": "virtual BrokeredObject& GetInstance()=0;\n" }, { "answer_id": 363543, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "template<typename T>\nBrokeredObject * GetOrCreateObject() {\n return new T();\n}\n TypeA::getInstance() enum MingletonKind {\n SINGLETON,\n MULTITON\n};\n\n// Singleton\ntemplate<typename D, MingletonKind>\nstruct Mingleton {\n static boost::shared_ptr<D> getOrCreate() {\n static D d;\n return boost::shared_ptr<D>(&d, NoopDel());\n }\n\n struct NoopDel {\n void operator()(D const*) const { /* do nothing */ }\n };\n};\n\n// Multiton\ntemplate<typename D>\nstruct Mingleton<D, MULTITON> {\n static boost::shared_ptr<D> getOrCreate() {\n return boost::shared_ptr<D>(new D);\n }\n};\n\nclass ImASingle : public Mingleton<ImASingle, SINGLETON> {\npublic:\n void testCall() { }\n // Indeed, we have to have a private constructor to prevent\n // others to create instances of us.\nprivate:\n ImASingle() { /* ... */ }\n friend class Mingleton<ImASingle, SINGLETON>;\n};\n\nclass ImAMulti : public Mingleton<ImAMulti, MULTITON> {\npublic:\n void testCall() { }\n // ...\n};\n\nint main() {\n // both do what we expect.\n ImAMulti::getOrCreate()->testCall();\n ImASingle::getOrCreate()->testCall();\n}\n SomeClass::getOrCreate()" }, { "answer_id": 363548, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 2, "selected": false, "text": "template <class Type>\nclass BrokeredObject\n{\nprotected:\n static Type *theInstance;\n\npublic:\n static Type *getOrCreate()\n {\n if (!theInstance) {\n theInstance = new Type();\n }\n\n return theInstance;\n }\n\n static void free()\n {\n delete theInstance;\n }\n\n};\n\nclass TestObject : public BrokeredObject<TestObject>\n{\npublic:\n TestObject()\n {}\n\n};\n\n\nint\nmain()\n{\n TestObject *obj = TestObject::getOrCreate();\n}\n" }, { "answer_id": 363657, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "template <class Type>\nclass BrokeredObject\n{\n public:\n static Type& getInstance()\n {\n static Type theInstance;\n\n return theInstance;\n }\n}; \n\nclass TestObject\n{\n public:\n TestObject()\n {}\n};\n\n\nint main()\n{\n TestObject& obj =BrokeredObject<TestObject>::getInstance();\n}\n" }, { "answer_id": 364479, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 1, "selected": false, "text": "BrokeredObject* p = GetObjectByID(TypeA::get_InterfaceID()) TypeA* p = new TypeA TypeA o template <class T>\nBrokeredObject* CreateObject()\n{\n return new T();\n}\n\ntypedef int type_identity;\ntypedef std::map<type_identity, BrokeredObject* (*)()> registry;\nregistry r;\n\nclass TypeA : public BrokeredObject\n{\npublic:\n static const type_identity identity;\n};\n\nclass TypeB : public BrokeredObject\n{\npublic:\n static const type_identity identity;\n};\n\nr[TypeA::identity] = &CreateObject<TypeA>;\nr[TypeB::identity] = &CreateObject<TypeB>;\n type_info typedef const type_info* type_identity;\ntypedef std::map<type_identity, BrokeredObject* (*)()> registry;\nregistry r;\n\nr[&typeid(TypeA)] = &CreateObject<TypeA>;\nr[&typeid(TypeB)] = &CreateObject<TypeB>;\n" }, { "answer_id": 364635, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 3, "selected": false, "text": "template <class T>\nclass StaticRegistry\n{\npublic:\n typedef std::list<T*> Container;\n\n static StaticRegistry<T>& GetInstance()\n {\n if (Instance == 0)\n {\n Instance = new StaticRegistry<T>;\n }\n return *Instance;\n }\n\n void Register(T* item)\n {\n Items.push_back(item);\n }\n\n void Deregister(T* item)\n {\n Items.remove(item);\n if (Items.empty())\n {\n delete this;\n Instance = 0;\n }\n }\n\n typedef typename Container::const_iterator const_iterator;\n\n const_iterator begin() const\n {\n return Items.begin();\n }\n\n const_iterator end() const\n {\n return Items.end();\n }\n\nprotected:\n StaticRegistry() {}\n ~StaticRegistry() {}\n\nprivate:\n Container Items;\n\n static StaticRegistry<T>* Instance;\n};\n\ntemplate <class T>\nStaticRegistry<T>* StaticRegistry<T>::Instance = 0;\n class BrokeredObjectBuilderBase {\npublic:\n BrokeredObjectBuilderBase() { StaticRegistry<BrokeredObjectBuilderBase>::GetInstance().Register(this); }\n virtual ~BrokeredObjectBuilderBase() { StaticRegistry<BrokeredObjectBuilderBase>::GetInstance().Deregister(this); }\n\n virtual int GetInterfaceId() = 0;\n virtual BrokeredObject* MakeBrokeredObject() = 0;\n};\n\n\ntemplate<class T>\nclass BrokeredObjectBuilder : public BrokeredObjectBuilderBase {\npublic:\n BrokeredObjectBuilder(unsigned long interface_id) : m_InterfaceId(interface_id) { } \n virtual int GetInterfaceId() { return m_InterfaceId; }\n virtual T* MakeBrokeredObject() { return new T; }\nprivate:\n unsigned long m_InterfaceId;\n};\n\n\nclass TypeA : public BrokeredObject\n{\n ...\n};\n\n// Create a global variable for the builder of TypeA so that it's \n// included in the BrokeredObjectBuilderRegistry\nBrokeredObjectBuilder<TypeA> TypeABuilder(TypeAUserInterfaceId);\n\ntypedef StaticRegistry<BrokeredObjectBuilderBase> BrokeredObjectBuilderRegistry;\n\nBrokeredObject *GetObjectByID(int id)\n{\n BrokeredObject *pObject(0);\n ObjectMap::iterator = m_objectList.find(id);\n // etc.\n if(found) return pObject;\n\n // not found, so create\n BrokeredObjectBuilderRegistry& registry(BrokeredObjectBuilderRegistry::GetInstance());\n for(BrokeredObjectBuilderRegistry::const_iterator it = registry.begin(), e = registry.end(); it != e; ++it)\n {\n if(it->GetInterfaceId() == id)\n {\n pObject = it->MakeBrokeredObject();\n break;\n }\n }\n\n if(0 == pObject)\n {\n // userinterface id not found, handle this here\n ...\n } \n\n // add it to the list\n return pObject;\n}\n" }, { "answer_id": 403171, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 1, "selected": true, "text": "class INewTransModule\n{\n public:\n virtual bool Init() { return true; }\n virtual bool Shutdown() { return true; }\n};\n\ntemplate <typename T>\nstruct BrokeredObject\n{\npublic:\n inline static T* GetInstance()\n {\n static T t;\n return &t;\n }\n};\n\ntemplate <> \nstruct BrokeredObject<INewTransModule>\n{\npublic:\n inline static INewTransModule* GetInstance()\n {\n static INewTransModule t;\n // do stuff after creation\n ASSERT(t.Init());\n return &t;\n }\n};\n\nclass OBJECTBROKER_API ObjectBroker\n{\n public: \n // these calls do configuration-based creations\n static ITraceTool *GetTraceTool();\n static IEeprom *GetEeprom();\n // etc\n};\n class EepromImpl: public BrokeredObject<EepromImpl>, public CEeprom\n{\n};\n\nclass SimEepromImpl: public BrokeredObject<SimEepromImpl>, public CSimEeprom\n{\n};\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13154/" ]
363,465
<p>So I totally buy into the basic tenents of ASP.NET, testability, SoC, HTML control...it's awesome. However being new to it I have a huge hang up with the markup. I know it comes from my hatred of classic ASP, and I can't help but feel like I've entered the twilight zone when <a href="http://www.flickr.com/photos/webjedi/3103009542/" rel="noreferrer">I see this</a>.</p> <p>I don't know what the alternative is (can I use server controls, databinding etc...?)</p>
[ { "answer_id": 363485, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": 5, "selected": true, "text": "ViewData.Model.myProperty (MyClasst)ViewData[\"foo\"].myProperty public static string RSSRepeater<T>(this HtmlHelper html, IEnumerable<T> rss) where T : IRSSable\n {\n StringBuilder result = new StringBuilder();\n\n if (rss.Count() > 0)\n {\n foreach (IRSSable item in rss)\n {\n result.Append(\"<item>\").Append(item.GetRSSItem().InnerXml).Append(\"</item>\");\n }\n }\n\n return result.ToString();\n }\n <%=Html.RSSRepeater(mydata)%>" }, { "answer_id": 363529, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "if" }, { "answer_id": 477155, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 0, "selected": false, "text": "<%-- comment --%> <%-- Go through each testimonial --%>\n <% foreach (var testimonial in ViewData.Model.Testimonials) { %>\n\n <div class=\"testimonialFrame\">\n <div class=\"testimonialHeader\"><%= testimonial.summaryText %></div>\n\n\n <%-- Show video if available --%>\n <% if (string.IsNullOrEmpty(testimonial.Video.FullURL) == false) { %>\n\n <div style=\"padding-top:12px\">\n <% Html.RenderAction(\"YouTubeControl\", \"Application\", new { youTubeId = testimonial.Video.FullURL }); %>\n </div>\n\n <% } %>\n\n <div class=\"roundedBox\" style=\"margin-top:15px\">\n <div id=\"txtTestimonialText\" class=\"testimonialText paddedBox\"><%= testimonial.TestimonialText %></div>\n </div>\n\n <div class=\"testimonialFooter\"><%= testimonial.name %></div>\n </div>\n\n <% } %>\n" }, { "answer_id": 477161, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 0, "selected": false, "text": " <%-- render section --%>\n <% RenderTextSection(section); %>\n htmlControl.RenderControl(new HtmlTextWriter(Response.Output));\n protected void RenderTextSection(ProductSectionInfo item)\n\n {\n HtmlGenericControl sectionTextDiv = new HtmlGenericControl(\"div\");\n\n bool previousHasBulletPoint = false;\n System.Web.UI.HtmlControls.HtmlControl currentContainer = sectionTextDiv;\n\n foreach (var txt in item.DescriptionItems)\n {\n if (!previousHasBulletPoint && txt.bp)\n {\n // start bulleted section\n currentContainer = new HtmlGenericControl(\"UL\");\n sectionTextDiv.Controls.Add(currentContainer);\n }\n else if (previousHasBulletPoint && !txt.bp)\n {\n // exit bulleted section\n currentContainer = sectionTextDiv;\n }\n\n if (txt.bp)\n {\n currentContainer.Controls.Add(new HtmlGenericControl(\"LI\")\n {\n InnerHtml = txt.t\n });\n }\n else\n {\n currentContainer.Controls.Add(new HtmlGenericControl()\n {\n InnerHtml = txt.t\n });\n }\n\n previousHasBulletPoint = txt.bp;\n }\n\n sectionTextDiv.RenderControl(new HtmlTextWriter(Response.Output));\n }\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975/" ]
363,491
<p>I have this PHP code</p> <pre><code>echo '&lt;a href="#" onclick="updateByQuery(\'Layer3\', ' . json_encode($query) . ');"&gt;Link 1&lt;/a&gt;'; </code></pre> <p>which generates a link like this:</p> <pre><code>&lt;a href="#" onclick="updateByQuery('Layer3', "Ed Hardy");"&gt;Link 1&lt;/a&gt;&lt;li&gt;Link 2&lt;/li&gt; </code></pre> <p>Causing the javascript to not be called. How would I make it generate single quotes around the result of $query, in this case ed hardy?</p>
[ { "answer_id": 363502, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "echo \"<a href='#' onclick='updateByQuery(\\\"Layer3\\\", \" . json_encode($query) . \");'>Link 1</a>\";\n" }, { "answer_id": 363505, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "echo '<a href=\"#\" onclick=\"updateByQuery(\\'Layer3\\', ' . htmlentities(json_encode($query)) . ');\">Link 1</a>';\n htmlspecialchars" }, { "answer_id": 363597, "author": "cLFlaVA", "author_id": 45109, "author_profile": "https://Stackoverflow.com/users/45109", "pm_score": 1, "selected": false, "text": "echo \"<a href='#' onclick='updateByQuery(\\\"Layer3\\\", \\\"\" . json_encode($query) . \"\\\");'>Link 1</a>\";\n <a href='#' onclick='updateByQuery(\"Layer3\", \"Ed Hardy\");'>Link 1</a>\n" }, { "answer_id": 367191, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "echo '\n<a href=\"#\" id=\"link_1\">Link 1</a>\n<script>document.getElementById(\"link_1\").onclick =\n function() { updateByQuery(\"Layer3\", '.json_encode($query).'); }\n</script>\n';\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
363,503
<pre><code>$(document).ready(function(){ $(".txtDate").datepicker({ showOn: "both", buttonImage: "library/ui/datepicker/img/calendar2.gif", dateFormat: "yy/mm/dd", buttonImageOnly: true }); //added this checkbox click for something I given earlier $("#Table input").click(function() { if ($(this).attr("checked") == true) { $(this).parent().parent().addClass("highlight"); } else { $(this).parent().parent().removeClass("highlight"); } }); }); </code></pre> <p>I have a checkbox control for each row that I add dynamically in code behind</p> <pre><code>for( int i=0; i&lt; data.count;i++){ HtmlTableCell CheckCell = new HtmlTableCell(); CheckBox Check = new CheckBox(); CheckCell.Controls.Add(Check); row.Cells.Add(CheckCell); Table.Rows.Add(row); } </code></pre> <p>table id with markup is here:</p> <pre><code>&lt;table id="Table" runat="server" width="100%" cellspacing="5" border="1"&gt; &lt;colgroup width="3%"&gt;&lt;/colgroup&gt; &lt;colgroup width="15%"&gt;&lt;/colgroup&gt; &lt;colgroup width="20%"&gt;&lt;/colgroup&gt; &lt;colgroup width="15%"&gt;&lt;/colgroup&gt; &lt;colgroup width="47%"&gt;&lt;/colgroup&gt; &lt;thead&gt; &lt;tr&gt; &lt;th id="CheckBox" runat="server"&gt;&lt;input type="checkbox" id="CheckBox1" name="CheckBox" runat="server" /&gt;&lt;/th&gt; &lt;th id="Type" runat="server"&gt;&lt;/th&gt; &lt;th id="Category" runat="server"&gt;&lt;/th&gt; &lt;th id="DateTime" runat="server"&gt;&lt;/th&gt; &lt;th id="Description" runat="server"&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
[ { "answer_id": 363540, "author": "cLFlaVA", "author_id": 45109, "author_profile": "https://Stackoverflow.com/users/45109", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html>\n<head>\n <title>Untitled</title>\n <script type=\"text/javascript\" src=\"shared-scripts/jquery-1.2.4b.js\"></script>\n <style type=\"text/css\">\n .highlight {\n background-color: yellow;\n }\n </style>\n\n <script type=\"text/javascript\">\n <!--\n $(document).ready(function(){\n $(\"#Table input\").click(function() {\n if ($(this).attr(\"checked\") == true) {\n $(this).parent().parent().addClass(\"highlight\");\n } else {\n $(this).parent().parent().removeClass(\"highlight\");\n }\n });\n });\n //-->\n </script>\n</head>\n\n<body>\n<form name=\"f\">\n<table id=\"Table\" border=\"1\"><tr>\n <td><input type=\"checkbox\" name=\"cb1\" id=\"cb1\" value=\"y\" /></td>\n <td>Click me</td>\n</tr><tr>\n <td><input type=\"checkbox\" name=\"cb2\" id=\"cb2\" value=\"y\" /></td>\n <td>Click me</td>\n</tr><tr>\n <td><input type=\"checkbox\" name=\"cb3\" id=\"cb3\" value=\"y\" /></td>\n <td>Click me</td>\n</tr></table>\n</form>\n</body>\n</html>\n" }, { "answer_id": 363552, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": " $('#Table INPUT').click(function() {\n $(this).parent().parent().toggleClass('highlight');\n });\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39809/" ]
363,504
<p>I want to have a abstract view for any type of UI (web or window). In order to do that I must use Interface (IView ) in which I can only apply just rules about view. In fact, I want to set a some basic comple function to provide to its inheritances.</p> <p>So in this way, I must use abstract class. The problem is</p> <p>1) Interface only have rules 2) The view (web form or window form) can't inherit any more since that's already inherited from window or web form</p> <p>How can I do that? Many thanks</p>
[ { "answer_id": 363611, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "public interface IView\n{\n void Foo();\n}\n\npublic abstract class BasePage : Page, IView\n{\n //honor the interface\n //but pass implementation responsibility to inheriting classes\n public abstract void Foo();\n\n //concrete method\n public void Bar()\n {\n //do concrete work\n }\n}\n\npublic class ConcretePage : BasePage\n{\n //implement Foo\n public override void Foo() { }\n}\n" }, { "answer_id": 363654, "author": "Andrew Hare", "author_id": 34211, "author_profile": "https://Stackoverflow.com/users/34211", "pm_score": 4, "selected": true, "text": "using System;\n\nabstract class Pet { }\n\nclass Dog : Pet, IPet\n{\n public String Name { get; set; }\n public Int32 Age { get; set; }\n}\n\nclass Cat : Pet, IPet\n{\n public String Name { get; set; }\n public Int32 Age { get; set; }\n}\n\ninterface IPet\n{\n String Name { get; set; }\n Int32 Age { get; set; }\n}\n\nstatic class PetUtils\n{\n public static void Print(this IPet pet)\n {\n Console.WriteLine(pet.Name + \" is \" + pet.Age);\n }\n}\n PetUtils.Print this public static void Print(this IPet pet)" }, { "answer_id": 363752, "author": "mtt", "author_id": 45771, "author_profile": "https://Stackoverflow.com/users/45771", "pm_score": 0, "selected": false, "text": "Inherits BaseController\n\nDim model As M\nDim view As V\nPublic Sub New()\n model = New M\n view.Controller = Me\n model.Controller = Me\nEnd Sub\nPublic Overridable Function GetModel() As M\n Return model\nEnd Function\nPublic Overridable Function GetView() As V\n Return view\nEnd Function \n Inherits System.Windows.Forms.Form\nImplements IView\nDim c As BaseController\n\nPublic Function GetController() As BaseController\n Return c\nEnd Function\n\nFriend WriteOnly Property Controller() As BaseController Implements IView.Controller\n Set(ByVal value As BaseController)\n c = value\n End Set\nEnd Property\n Public Class BaseWeb\nInherits System.Web.UI.Page\nImplements IView\n\nDim c As BaseController \n\nPublic Function GetController() As BaseController\n Return c\nEnd Function\n\nFriend WriteOnly Property Controller() As BaseController Implements IView.Controller\n Set(ByVal value As BaseController)\n c = value\n End Set\nEnd Property\n WriteOnly Property Controller() As BaseController\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45771/" ]
363,528
<p><strong>Question:</strong> How can I process a form using jQuery and the $.ajax request so that the data is passed to a script which writes it to a database?</p> <p><strong>Problem:</strong> I have a simple email signup form that when processed, adds the email along with the current date to a table in a MySQL database. Processing the form without jQuery works as intended, adding the email and date. With jQuery, the form submits successfully and returns the success message. However, no data is added to the database.</p> <p>Any insight would be greatly appreciated! </p> <pre><code> &lt;!-- PROCESS.PHP --&gt; &lt;?php // DB info $dbhost = '#'; $dbuser = '#'; $dbpass = '#'; $dbname = '#'; // Open connection to db $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); // Form variables $email = $_POST['email']; $submitted = $_POST['submitted']; // Clean up function cleanData($str) { $str = trim($str); $str = strip_tags($str); $str = strtolower($str); return $str; } $email = cleanData($email); $error = ""; if(isset($submitted)) { if($email == '') { $error .= '&lt;p class="error"&gt;Please enter your email address.&lt;/p&gt;' . "\n"; } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", $email)) { $error .= '&lt;p class="error"&gt;Please enter a valid email address.&lt;/p&gt;' . "\n"; } if(!$error){ echo '&lt;p id="signup-success-nojs"&gt;You have successfully subscribed!&lt;/p&gt;'; // Add to database $add_email = "INSERT INTO subscribers (email,date) VALUES ('$email',CURDATE())"; mysql_query($add_email) or die(mysql_error()); }else{ echo $error; } } ?&gt; &lt;!-- SAMPLE.PHP --&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Sample&lt;/title&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ // Email Signup $("form#newsletter").submit(function() { var dataStr = $("#newsletter").serialize(); alert(dataStr); $.ajax({ type: "POST", url: "process.php", data: dataStr, success: function(del){ $('form#newsletter').hide(); $('#signup-success').fadeIn(); } }); return false; }); }); &lt;/script&gt; &lt;style type="text/css"&gt; #email { margin-right:2px; padding:5px; width:145px; border-top:1px solid #ccc; border-left:1px solid #ccc; border-right:1px solid #eee; border-bottom:1px solid #eee; font-size:14px; color:#9e9e9e; } #signup-success { margin-bottom:20px; padding-bottom:10px; background:url(../img/css/divider-dots.gif) repeat-x 0 100%; display:none; } #signup-success p, #signup-success-nojs { padding:5px; background:#fff; border:1px solid #dedede; text-align:center; font-weight:bold; color:#3d7da5; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include('process.php'); ?&gt; &lt;form id="newsletter" class="divider" name="newsletter" method="post" action=""&gt; &lt;fieldset&gt; &lt;input id="email" type="text" name="email" /&gt; &lt;input id="submit-button" type="image" src="&lt;?php echo $base_url; ?&gt;/assets/img/css/signup.gif" alt=" SIGNUP " /&gt; &lt;input id="submitted" type="hidden" name="submitted" value="true" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;div id="signup-success"&gt;&lt;p&gt;You have successfully subscribed!&lt;/p&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 363602, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "data : {param: value, param2: value2}\n" }, { "answer_id": 7568003, "author": "sumi", "author_id": 917929, "author_profile": "https://Stackoverflow.com/users/917929", "pm_score": 0, "selected": false, "text": "jQuery('#newsletter').formSerialize();\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
363,565
<p>I'm looking for any examples anyone might have seen of how to effectively present a list of items (about 1500 in total) so that multiple items can be selected.</p> <p>I've seen a couple of similar questions where the answer suggests an auto-complete, which works to select a single item, but that doesn't allow users to select multiple items.</p> <p>Any suggestions, or especially pointers to web apps that might have a potential solution, would be most appreciated!</p>
[ { "answer_id": 363604, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 1, "selected": false, "text": "div" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4782/" ]
363,569
<p>If you use an <code>EnumSet</code> to store conventional binary values (1,2,4 etc), then when there are less than 64 items, I am led to believe that this is stored as a bit vector and is represented efficiently as a long. Is there a simple way to get the value of this long. I want a quick and simple way to store the contents of the set in either a file or database.</p> <p>If I was doing this the old way, I'd just use a long, and do the bit twidling myself, despite all the issues of typesafety etc.</p>
[ { "answer_id": 363612, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 1, "selected": false, "text": "EnumSet Serializable ObjectOutputStream" }, { "answer_id": 363741, "author": "Dave Ray", "author_id": 40310, "author_profile": "https://Stackoverflow.com/users/40310", "pm_score": 3, "selected": false, "text": "public static <T extends Enum<T>> long enumSetToLong(EnumSet<T> set)\n{\n long r = 0;\n for(T value : set)\n {\n r |= 1L << value.ordinal();\n }\n return r;\n}\n" }, { "answer_id": 20611224, "author": "Alex", "author_id": 902859, "author_profile": "https://Stackoverflow.com/users/902859", "pm_score": 0, "selected": false, "text": "BitSet enum BitSet BitSet" }, { "answer_id": 23314435, "author": "Claude Martin", "author_id": 2123025, "author_profile": "https://Stackoverflow.com/users/2123025", "pm_score": 2, "selected": false, "text": " static enum MyEnum implements EnumBitSetHelper<MyEnum> { A, B, C }\n public static void main(final String[] args) {\n final EnumBitSet<MyEnum> set = EnumBitSet.of(MyEnum.A, MyEnum.C);\n long bitmask = set.toLong(); // = 3\n }\n" }, { "answer_id": 25269748, "author": "Christian", "author_id": 178597, "author_profile": "https://Stackoverflow.com/users/178597", "pm_score": 2, "selected": false, "text": "public static <T extends Enum<T>, U extends Enum<?>> byte toByte(EnumSet<T> set, Class<U> type) {\n byte b = 0;\n\n if(type.getEnumConstants().length > 8) {\n throw new RuntimeException(\"enum set doesn't fit in one byte\");\n }\n\n for(Enum<?> e: type.getEnumConstants()) {\n if(set.contains(e)) {\n b |= 1 << e.ordinal();\n }\n }\n\n return b;\n}\n\npublic static <E extends Enum<E>> EnumSet<E> toSet(byte b, Class<E> type) {\n E[] enums = type.getEnumConstants();\n EnumSet<E> enumSet = EnumSet.noneOf(type);\n\n for(int bit = 0; bit < 8; bit++) {\n if((b & 1 << bit) > 0) {\n enumSet.add(enums[bit]);\n }\n }\n\n return enumSet;\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3898/" ]
363,570
<p>I have a update method in my data layer such this:</p> <pre><code>public clacc datalayerSec_User private objUIData as new UIData Public Function Update(ByVal objUser As SEC_USER) As Boolean Try objUIData.SEC_USERs.Attach(objUser) objUIData.Refresh(RefreshMode.KeepCurrentValues, objUser) objUIData.SubmitChanges(ConflictMode.ContinueOnConflict) Return True Catch ex As Exception Throw ex End Try End Function end class </code></pre> <p>And I write this code to update my data:</p> <pre><code>Dim tmpUser As New UI_Class.BAL.Security.cls_SEC_USER Dim tblUser = tmpUser.GetAll.SingleOrDefault(Function(x) x.DS_OPENID = pOpenID) tblUser.DT_LAST_LOGIN = DateTime.Now tmpUser.Update(tblUser) </code></pre> <p>When I run it, I have this error message: Cannot attach an entity that already exists.</p> <p>How can it be fixed?</p>
[ { "answer_id": 365141, "author": "Egil Hansen", "author_id": 32809, "author_profile": "https://Stackoverflow.com/users/32809", "pm_score": 3, "selected": true, "text": "class cls_SEC_USER\n{\n private _UIData = new UIData();\n\n public User SingleOrDefault(int x)\n {\n return _UIData.Users.SingleOrDefault(y => y.UserId == x);\n }\n\n public void Update(User u)\n {\n _UIData.SubmitChanges();\n }\n}\n\n// ..........\n\ncls_SEC_USER tmpUser = new cls_SEC_USER(); \nUser u = tmpUser.SingleOrDefault(4);\n\nif(u != null)\n{\n u.DT_LAST_LOGIN = DateTime.Now;\n tmpUser.Update(u);\n}\n" } ]
2008/12/12
[ "https://Stackoverflow.com/questions/363570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439507/" ]