qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
225,073
<p>I am about to write junit tests for a XML parsing Java class that outputs directly to an OutputStream. For example <code>xmlWriter.writeString("foo");</code> would produce something like <code>&lt;aTag&gt;foo&lt;/aTag&gt;</code> to be written to the outputstream held inside the XmlWriter instance. The question is how to test this behaviour. One solution would of course be to let the OutputStream be a FileOutputStream and then read the results by opening the written file, but it isn't very elegant. </p>
[ { "answer_id": 225857, "author": "eljenso", "author_id": 30316, "author_profile": "https://Stackoverflow.com/users/30316", "pm_score": 2, "selected": false, "text": "StringWriter StringWriter toString() OutputStream ByteArrayOutputStream toString() public void testSomething()\n{\n Writer sw = new StringWriter();\n XmlWriter xw = new XmlWriter(sw);\n ...\n xw.writeString(\"foo\");\n ...\n assertEquals(\"...<aTag>foo</aTag>...\", sw.toString());\n}\n" }, { "answer_id": 39474680, "author": "Dherik", "author_id": 2387977, "author_profile": "https://Stackoverflow.com/users/2387977", "pm_score": 2, "selected": false, "text": "ByteArrayOutputStream baos = new ByteArrayOutputStream();\n// pass the baos to be writed with \"value\", for this example\nbyte[] byteArray = baos.toByteArray();\nAssert.assertEquals(\"value\", new String(byteArray));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22012/" ]
225,078
<p>I have an application that grabs video from multiple webcams, does some image processing, and displays the result on the screen. I'd like to be able to stream the video output on to the web - preferably to some kind of distribution service rather than connecting to clients directly myself.</p> <p>So my questions are:</p> <ul> <li>Do such streaming distribution services exist? I'm thinking of something like ShoutCAST relays, but for video. I'm aware of ustream.tv, but I think they just take a direct webcam connection rather than allow you to send any stream.</li> <li>If so, is there a standard protocol for doing this?</li> <li>If so, is there a free library implementation of this protocol for Win32?</li> </ul> <p>Ideally I'd just like to throw a frame of video in DIB format at a SendToServer(bitmap) function, and have it compress, send, and distribute it for me ;) </p>
[ { "answer_id": 225857, "author": "eljenso", "author_id": 30316, "author_profile": "https://Stackoverflow.com/users/30316", "pm_score": 2, "selected": false, "text": "StringWriter StringWriter toString() OutputStream ByteArrayOutputStream toString() public void testSomething()\n{\n Writer sw = new StringWriter();\n XmlWriter xw = new XmlWriter(sw);\n ...\n xw.writeString(\"foo\");\n ...\n assertEquals(\"...<aTag>foo</aTag>...\", sw.toString());\n}\n" }, { "answer_id": 39474680, "author": "Dherik", "author_id": 2387977, "author_profile": "https://Stackoverflow.com/users/2387977", "pm_score": 2, "selected": false, "text": "ByteArrayOutputStream baos = new ByteArrayOutputStream();\n// pass the baos to be writed with \"value\", for this example\nbyte[] byteArray = baos.toByteArray();\nAssert.assertEquals(\"value\", new String(byteArray));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17440/" ]
225,080
<p>I'm trying to configure an ejabberd installation, using LDAP authentication, but I just can't login, even with the admin user. This is part of my ejabberd.cfg file:</p> <pre><code>%... {auth_method, ldap}. {ldap_servers, ["server2000.tek2000.local"]}. {ldap_port,389}. {ldap_uidattr, "uid"}. {ldap_base, "dc=server2000,dc=tek2000,dc=com"}. {ldap_rootdn, "tempadm@tek2000.local"}. {ldap_password, "secret"}. %... </code></pre> <p>What am I missing?</p> <p>I must say that, with OpenFire, I can connect using this credentials/configuration.</p> <p>I'm using Spark as my client application.</p> <p>Thanks</p>
[ { "answer_id": 225857, "author": "eljenso", "author_id": 30316, "author_profile": "https://Stackoverflow.com/users/30316", "pm_score": 2, "selected": false, "text": "StringWriter StringWriter toString() OutputStream ByteArrayOutputStream toString() public void testSomething()\n{\n Writer sw = new StringWriter();\n XmlWriter xw = new XmlWriter(sw);\n ...\n xw.writeString(\"foo\");\n ...\n assertEquals(\"...<aTag>foo</aTag>...\", sw.toString());\n}\n" }, { "answer_id": 39474680, "author": "Dherik", "author_id": 2387977, "author_profile": "https://Stackoverflow.com/users/2387977", "pm_score": 2, "selected": false, "text": "ByteArrayOutputStream baos = new ByteArrayOutputStream();\n// pass the baos to be writed with \"value\", for this example\nbyte[] byteArray = baos.toByteArray();\nAssert.assertEquals(\"value\", new String(byteArray));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019426/" ]
225,086
<p>Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format</p> <pre><code>Sun, 06 Nov 1994 08:49:37 GMT </code></pre> <p>Using <code>strftime</code> does not work, since the strings are locale-dependant. Do I have to build the string by hand?</p>
[ { "answer_id": 225101, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 2, "selected": false, "text": ">>> locale.setlocale(locale.LC_TIME, 'en_US')\n'en_US'\n>>> datetime.datetime.now().strftime(locale.nl_langinfo(locale.D_T_FMT))\n'Wed 22 Oct 2008 06:05:39 AM '\n" }, { "answer_id": 225106, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 8, "selected": true, "text": "from wsgiref.handlers import format_date_time\nfrom datetime import datetime\nfrom time import mktime\n\nnow = datetime.now()\nstamp = mktime(now.timetuple())\nprint format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:40 GMT\n from email.utils import formatdate\nfrom datetime import datetime\nfrom time import mktime\n\nnow = datetime.now()\nstamp = mktime(now.timetuple())\nprint formatdate(\n timeval = stamp,\n localtime = False,\n usegmt = True\n) #--> Wed, 22 Oct 2008 10:55:46 GMT\n import locale, datetime\n\nlocale.setlocale(locale.LC_TIME, 'en_US')\ndatetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')\n from datetime import datetime\nfrom babel.dates import format_datetime\n\nnow = datetime.utcnow()\nformat = 'EEE, dd LLL yyyy hh:mm:ss'\nprint format_datetime(now, format, locale='en') + ' GMT'\n def httpdate(dt):\n \"\"\"Return a string representation of a date according to RFC 1123\n (HTTP/1.1).\n\n The supplied date must be in UTC.\n\n \"\"\"\n weekday = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"][dt.weekday()]\n month = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\",\n \"Oct\", \"Nov\", \"Dec\"][dt.month - 1]\n return \"%s, %02d %s %04d %02d:%02d:%02d GMT\" % (weekday, dt.day, month,\n dt.year, dt.hour, dt.minute, dt.second)\n" }, { "answer_id": 225177, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 6, "selected": false, "text": "from email.utils import formatdate\nprint formatdate(timeval=None, localtime=False, usegmt=True)\n Wed, 22 Oct 2008 10:32:33 GMT\n" }, { "answer_id": 225191, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 1, "selected": false, "text": "def httpdate(dt):\n \"\"\"Return a string representation of a date according to RFC 1123\n (HTTP/1.1).\n\n The supplied date must be in UTC.\n\n \"\"\"\n weekday = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"][dt.weekday()]\n month = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\",\n \"Oct\", \"Nov\", \"Dec\"][dt.month - 1]\n return \"%s, %02d %s %04d %02d:%02d:%02d GMT\" % (weekday, dt.day, month,\n dt.year, dt.hour, dt.minute, dt.second)\n" }, { "answer_id": 37191167, "author": "Antoine Pinsard", "author_id": 1529346, "author_profile": "https://Stackoverflow.com/users/1529346", "pm_score": 4, "selected": false, "text": "django.utils.http.http_date(epoch_seconds) from django.utils.http import http_date\n\nsome_datetime = some_object.last_update\nresponse['Last-Modified'] = http_date(some_datetime.timestamp())\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7779/" ]
225,088
<p>I'm trying to figure out the best way to store user uploaded files in a file system. The files range from personal files to wiki files. Of course, the DB will point to those files by someway which I have yet to figure out. </p> <p>Basic Requirements:</p> <ul> <li>Fairy Decent Security so People Can't Guess Filenames (Picture001.jpg, Picture002.jpg, Music001.mp3 is a big no no)</li> <li>Easily Backed Up &amp; Mirrorable (I prefer a way so I don't have to copy the entire HDD every single time I want to backup. I like the idea of backing up just the newest items but I'm flexible with the options here.)</li> <li>Scalable to millions of files on multiple servers if needed.</li> </ul>
[ { "answer_id": 225098, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 1, "selected": false, "text": "/2\n/2/2f/\n/2/2f/2fd/\n/2/2f/2fd/2fd4e1c67a2d28fced849ee1bb76e7391b93eb12\n" }, { "answer_id": 225112, "author": "KristoferA", "author_id": 11241, "author_profile": "https://Stackoverflow.com/users/11241", "pm_score": 2, "selected": false, "text": "using System;\nusing System.IO;\nusing System.Xml.Serialization;\n\n/// <summary>\n/// Class for generating storage structure and file names for document storage.\n/// Copyright (c) 2008, Huagati Systems Co.,Ltd. \n/// </summary>\n\npublic class DocumentStorage\n{\n private static StorageDirectory _StorageDirectory = null;\n\n public static string GetNewUNCPath()\n {\n string storageDirectory = GetStorageDirectory();\n if (!storageDirectory.EndsWith(\"\\\\\"))\n {\n storageDirectory += \"\\\\\";\n }\n return storageDirectory + GuidEx.NewSeqGuid().ToString() + \".data\";\n }\n\n public static void SaveDocumentInfo(string documentPath, Document documentInfo)\n {\n //the filestream object don't like NTFS streams so this is disabled for now...\n return;\n\n //stores a document object in a separate \"docinfo\" stream attached to the file it belongs to\n //XmlSerializer ser = new XmlSerializer(typeof(Document));\n //string infoStream = documentPath + \":docinfo\";\n //FileStream fs = new FileStream(infoStream, FileMode.Create);\n //ser.Serialize(fs, documentInfo);\n //fs.Flush();\n //fs.Close();\n }\n\n private static string GetStorageDirectory()\n {\n string storageRoot = ConfigSettings.DocumentStorageRoot;\n if (!storageRoot.EndsWith(\"\\\\\"))\n {\n storageRoot += \"\\\\\";\n }\n\n //get storage directory if not set\n if (_StorageDirectory == null)\n {\n _StorageDirectory = new StorageDirectory();\n lock (_StorageDirectory)\n {\n string path = ConfigSettings.ReadSettingString(\"CurrentDocumentStoragePath\");\n if (path == null)\n {\n //no storage tree created yet, create first set of subfolders\n path = CreateStorageDirectory(storageRoot, 1);\n _StorageDirectory.FullPath = path.Substring(storageRoot.Length);\n ConfigSettings.WriteSettingString(\"CurrentDocumentStoragePath\", _StorageDirectory.FullPath);\n }\n else\n {\n _StorageDirectory.FullPath = path;\n }\n }\n }\n\n int fileCount = (new DirectoryInfo(storageRoot + _StorageDirectory.FullPath)).GetFiles().Length;\n if (fileCount > ConfigSettings.FolderContentLimitFiles)\n {\n //if the directory has exceeded number of files per directory, create a new one...\n lock (_StorageDirectory)\n {\n string path = GetNewStorageFolder(storageRoot + _StorageDirectory.FullPath, ConfigSettings.DocumentStorageDepth);\n _StorageDirectory.FullPath = path.Substring(storageRoot.Length);\n ConfigSettings.WriteSettingString(\"CurrentDocumentStoragePath\", _StorageDirectory.FullPath);\n }\n }\n\n return storageRoot + _StorageDirectory.FullPath;\n }\n\n private static string GetNewStorageFolder(string currentPath, int currentDepth)\n {\n string parentFolder = currentPath.Substring(0, currentPath.LastIndexOf(\"\\\\\"));\n int parentFolderFolderCount = (new DirectoryInfo(parentFolder)).GetDirectories().Length;\n if (parentFolderFolderCount < ConfigSettings.FolderContentLimitFolders)\n {\n return CreateStorageDirectory(parentFolder, currentDepth);\n }\n else\n {\n return GetNewStorageFolder(parentFolder, currentDepth - 1);\n }\n }\n\n private static string CreateStorageDirectory(string currentDir, int currentDepth)\n {\n string storageDirectory = null;\n string directoryName = GuidEx.NewSeqGuid().ToString();\n if (!currentDir.EndsWith(\"\\\\\"))\n {\n currentDir += \"\\\\\";\n }\n Directory.CreateDirectory(currentDir + directoryName);\n\n if (currentDepth < ConfigSettings.DocumentStorageDepth)\n {\n storageDirectory = CreateStorageDirectory(currentDir + directoryName, currentDepth + 1);\n }\n else\n {\n storageDirectory = currentDir + directoryName;\n }\n return storageDirectory;\n }\n\n private class StorageDirectory\n {\n public string DirectoryName { get; set; }\n public StorageDirectory ParentDirectory { get; set; }\n public string FullPath\n {\n get\n {\n if (ParentDirectory != null)\n {\n return ParentDirectory.FullPath + \"\\\\\" + DirectoryName;\n }\n else\n {\n return DirectoryName;\n }\n }\n set\n {\n if (value.Contains(\"\\\\\"))\n {\n DirectoryName = value.Substring(value.LastIndexOf(\"\\\\\") + 1);\n ParentDirectory = new StorageDirectory { FullPath = value.Substring(0, value.LastIndexOf(\"\\\\\")) };\n }\n else\n {\n DirectoryName = value;\n }\n }\n }\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
225,089
<p>Why can't we initialize members inside a structure ?</p> <p>example:</p> <pre><code>struct s { int i = 10; }; </code></pre>
[ { "answer_id": 225092, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 5, "selected": false, "text": "struct structs struct s {\n int i;\n\n s(): i(10)\n {\n }\n};\n struct s {\n int i;\n};\n\n...\n\nstruct s s_instance = { 10 };\n struct s {\n int i;\n};\n\n...\n\nstruct s s_instance = {\n .i = 10,\n};\n struct s s_instance = {\n i: 10,\n};\n" }, { "answer_id": 225100, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "c++ c struct class public private static const struct struct bad {\n static int answer = 42; // Error! not const\n const char* question = \"what is life?\"; // Error! not const or integral\n};\n\nstruct good {\n static const int answer = 42; // OK\n const char* question;\n good() \n : question(\"what is life?\") // initialization list\n { }\n};\n\nstruct pod { // plain old data\n int answer;\n const char* question;\n};\npod p = { 42, \"what is life?\" };\n" }, { "answer_id": 226228, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": false, "text": "struct s { int i=10; };\n } ; struct s { int i; } t = { 10 };\n struct s { int i; } t = { .i = 10 };\n" }, { "answer_id": 35995008, "author": "Anup Raj Dubey", "author_id": 6062241, "author_profile": "https://Stackoverflow.com/users/6062241", "pm_score": 2, "selected": false, "text": "int a = 10;\n" }, { "answer_id": 37550773, "author": "Turtlesoft", "author_id": 6405633, "author_profile": "https://Stackoverflow.com/users/6405633", "pm_score": 4, "selected": false, "text": "struct s {\n int i = 10;\n};\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21599/" ]
225,096
<p>I'm starting to look into the whole world of RJS and Prototype/jQuery in Rails and am a little bit confused. There seems to be no clear line of where to use one or the other.</p> <p>Say I wanted one of the "Active, Hot, Week" tabs like the ones here on SO. When pressing one of them, I want to remove a CSS class (like "active-tab") from the one I was on and add it to the one I clicked on. Then I also want to reload the div containing the items and put in the new items into it.</p> <p>Seems the class-changing thing would be easiest to do in pure javascript, say put the code in application.js and then updating the div with the content would obviously be easiest in RJS. But what <em>should</em> one do?</p>
[ { "answer_id": 225306, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 2, "selected": true, "text": "page.replace(dom_id, :partial => @page_content);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9191/" ]
225,103
<p>I'm writing a MUD engine and I've just started on the game object model, which needs to be extensible.</p> <p>I need help mainly because what I've done feels messy, but I can't think of a another solution that works better.</p> <p>I have a class called <code>MudObject</code>, and another class called <code>Container</code>, A container can contain multiple <code>MudObjects</code>, but is a <code>MudObject</code> itself, however <code>MudObject</code>s need to know what they are contained in.</p> <p>So they look something like this:</p> <pre><code>public abstract class MudObject { Container containedBy; } public abstract class Container : MudObject { List&lt;MudObject&gt; Contains; } </code></pre> <p><em>(please note these are just example and some qualifiers and access modifiers, properties and such are missed off)</em></p> <p>Now just this in itself seems messy, but lets add something else to the mix:</p> <p><code>Item</code> is a <code>MudObject</code> that all visual items (such as weapons) will be inherited from, however some of these need to be containers too (like chests). But theres no such as multiple inheritance in c#, So it comes down to interfaces, the best choice would be to make the container an interface (as far as I can see) However there was a reason I didn't want it to be, that being that adding an <code>MudObject</code> to a container will cause the container to update the <code>MudObject</code>s <code>.containedBy</code> value.</p> <p>Any ideas that would make this work, or am I falling into the trap of making things too complicated?<br> If so what else could you suggest?</p>
[ { "answer_id": 225120, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "List<MudObject> public class MudObjectList : List<MudObject>\n public void new Add(MudObject obj)\n{\n obj.ContainedBy = this;\n base.Add(obj);\n}\n null MudObject Container MudObject public abstract class MudObject\n{\n MudObject ContainedBy { get; set; }\n MudObjectList Contains { get; set; }\n}\n" }, { "answer_id": 225124, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 0, "selected": false, "text": "public abstract class MudObject\n{\n MudObject containedBy;\n List<MudObject> contains;\n}\n" }, { "answer_id": 225125, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "public interface IMudObject\n{\n IMudObject Container { get; set; }\n /* etc */\n}\n\npublic class MudContainer<T> : Collection<T>, IMudObject\n where T : IMudObject\n{\n\n public IMudObject Container { get; set; }\n\n protected override void ClearItems()\n {\n foreach (T item in this)\n {\n RemoveAsContainer(item);\n }\n base.ClearItems();\n }\n\n protected override void InsertItem(int index, T item)\n {\n SetAsContainer(item);\n base.InsertItem(index, item);\n }\n\n protected override void RemoveItem(int index)\n {\n RemoveAsContainer(this[index]);\n base.RemoveItem(index); \n }\n protected override void SetItem(int index, T item)\n {\n RemoveAsContainer(this[index]);\n SetAsContainer(item);\n base.SetItem(index, item);\n }\n\n void RemoveAsContainer(T item)\n {\n if (item != null && ReferenceEquals(item.Container, this))\n {\n item.Container = null;\n }\n }\n void SetAsContainer(T item)\n {\n if (item.Container != null)\n {\n throw new InvalidOperationException(\"Already owned!\");\n }\n item.Container = this;\n }\n}\n" }, { "answer_id": 225127, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 2, "selected": false, "text": "public abstract class MudObject\n{ \n MudObject containedBy; //technically Parent\n List<MudObject> Contains; //children\n}\n" }, { "answer_id": 225182, "author": "Sekhat", "author_id": 1610, "author_profile": "https://Stackoverflow.com/users/1610", "pm_score": 0, "selected": false, "text": "public class Container<T> where T : MudObject\n{\n List<T> Contains;\n MudObject containerOwner;\n\n public Container(MudObject owner)\n {\n containerOwner = owner;\n }\n // Other methods to handle parent association\n}\n\npublic interface IMudContainer<T> where T : MudObject\n{\n Container<T> Contains { get; }\n}\n\npublic class MudObjectThatContainsStuff : IMudContainer\n{\n public MudObjectThatContainsStuff()\n {\n Contains = new Container<MudObject>(this);\n }\n\n public Contains { get; }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610/" ]
225,114
<pre><code>&lt;td title="this is a really long line that I'm going to truncate"&gt;this is a really long line that I'm going to trunc ...&lt;/td&gt; </code></pre> <p>Is this the correct way to do it?</p>
[ { "answer_id": 225165, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 2, "selected": false, "text": "title td <td>\n <span title=\"this is a really long line that I'm going to truncate\">this is a really long line that I'm going to trunc ...</span>\n</td>\n" }, { "answer_id": 225166, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 0, "selected": false, "text": "title TD ABBR SPAN" }, { "answer_id": 225269, "author": "Jeremy Holt", "author_id": 30046, "author_profile": "https://Stackoverflow.com/users/30046", "pm_score": 0, "selected": false, "text": "<title=\"long line of text\\nanotherlong line of text\" />\n <br/>" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21559/" ]
225,130
<p>I'm tryint to post to a ADO.NET Data Service but the parameters seems to get lost along the way.</p> <p>I got something like:</p> <pre><code>[WebInvoke(Method="POST")] public int MyMethod(int foo, string bar) {...} </code></pre> <p>and I make an ajax-call using prototype.js as:</p> <pre><code>var args = {foo: 4, bar: "'test'"}; new Ajax.Requst(baseurl + 'MyMethod', method: 'POST', parameters: args, onSuccess: jadda, onFailure: jidda } </code></pre> <p>If I replace "method: 'POST'" with "method: 'GET'" and "WebInvoke(Method="POST")" with "WebGet" everything works but now (using post) all I get is:</p> <blockquote> <p>Bad Request - Error in query syntax.</p> </blockquote> <p>from the service.</p> <p>The only fix (that I don't want to use) is to send all parameters in the URL even when I perform a post. Any ideas are welcome. </p>
[ { "answer_id": 225164, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 0, "selected": false, "text": "<foo>1</foo>\n<bar>abc</bar>\n <Request>\n <foo>1</foo>\n <bar>abc</bar>\n</Request>\n" }, { "answer_id": 225388, "author": "finnsson", "author_id": 24044, "author_profile": "https://Stackoverflow.com/users/24044", "pm_score": 0, "selected": false, "text": "var args = {Request: {foo: 3, bar: \"'test'\"}}\n ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped\n" }, { "answer_id": 364513, "author": "John Foster", "author_id": 45859, "author_profile": "https://Stackoverflow.com/users/45859", "pm_score": 3, "selected": true, "text": " new Ajax.Request(baseurl + 'MyMethod', {\n method: 'POST',\n postBody: '{\"foo\":4, \"bar\":\"test\"}',\n encoding: \"UTF-8\",\n contentType: \"application/json;\",\n onSuccess: function(result) {\n alert(result.responseJSON.d); \n },\n onFailure: function() {\n alert(\"Error\");\n }\n });\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24044/" ]
225,149
<p>Guys, I’ve been writing code for 15+ years, but managed to avoid “Web Development” until 3 months ago.</p> <p>I have inherited a legacy Asp.net application (started in .net 1.1, we’re now on .Net 2.0), it’s the administration tool for our product.</p> <p>In several places the admin tool simply maintains long lists of values.</p> <p>The list (could be 200+ items) appear in a GridView (Page A), user clicks an edit button for an item, this brings them to an edit page for the item (Page B) where they can change the value (or values, an item in the list may be associated with several values e.g. name and address and preferred colour, breed of cat . . .)</p> <p>Currently when the user presses “Save” on Page B, we redirect back to Page A. The page opens at the top of the list, this annoys the user as often several items in sequence will need to be configured together, and the user needs to 1. Remember which item they just edited, 2. scroll down to that item</p> <p>What I want to do is have the list bring the user back to the item they just edited, as often several items in sequence will need to be configured together.</p> <p><strong>Fastest Gun Stop</strong> . . . and keep reading</p> <ol> <li>Suggestions on the lines of “regroup the items so there are fewer in the list” will be considered unhelpful</li> <li>Valid points that .Net 3.5 does this automatically, will be considered unhelpful by me (but post them anyway, it may help some other poor fool)</li> <li>I think I could do this by posting the Id of the edited item when re-loading Page A, and scrolling the grid to this point, however <strong>My Question is</strong> . . .</li> </ol> <p>Is there a feature to do this that I don’t know about (and what is it) and/or<br> What is the accepted way of doing this?</p> <p>Thanks in advance B. Worrier</p>
[ { "answer_id": 225215, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 3, "selected": true, "text": "<a name=\"#175\"></a>\n Response.Redirect(\"PageA.aspx#175\");\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18797/" ]
225,150
<p>One of my projects use the MyISAM engine in MySQL, but I'm considering changing it to InnoDB as I need transaction support here and there.</p> <ul> <li>What should I look at or consider before doing this? </li> <li>Can I just change the engine, or should the data be prepared for it?</li> </ul>
[ { "answer_id": 226422, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 2, "selected": false, "text": "select count(*) from MyTable" }, { "answer_id": 228948, "author": "Laurynas Pečiūra", "author_id": 30693, "author_profile": "https://Stackoverflow.com/users/30693", "pm_score": 3, "selected": false, "text": "innodb_file_per_table=1 innodb_buffer_pool_size vm.swappiness innodb_flush_method=O_DIRECT mysqlbackup --single-transaction --skip-lock-tables" }, { "answer_id": 242348, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 1, "selected": false, "text": "innodb_file_trx_commit=1" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
225,194
<p>I'm relatively new to Threading in Java and I've noticed that everytime I use Thread.sleep() I have to catch InterrupetdException.</p> <p>What kind of behaviour causes this, and in simple applications where I have a monitor thread can I just Ignore the exception?</p>
[ { "answer_id": 225310, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 3, "selected": false, "text": "interrupt() Thread" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
225,207
<p>What is the best practice to solve a Java VM crash if the follow conditions are true:</p> <ul> <li>No own or third party native code. 100% pure java</li> <li>The same program run on many other system without any problems.</li> </ul> <p>PS: With VM crash I means that the VM write a dump file like hs_err_pid1234.log and terminate.</p>
[ { "answer_id": 225406, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 2, "selected": false, "text": "OS OS SMB NFS malloc" }, { "answer_id": 225951, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "hs_err" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12631/" ]
225,210
<p>We have a collection of photo images sizing a few hundred gigs. A large number of the photos are visually duplicates, but with differing filesizes, resolution, compression etc. </p> <p>Is it possible to use any specific image processing methods to search out and remove these duplicate images?</p>
[ { "answer_id": 225534, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 0, "selected": false, "text": "SELECT id FROM photos where id='uploaded_image_id' image_a image_b" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23393/" ]
225,233
<p>No I'm not being a wise guy ...</p> <p>For those fortunate enough to not know the My class: It's something that was <strong>added in VB 2005 (and doesn't exist in C#) and is best described as a 'speeddial for the .net framework'.</strong> Supposed to make life easier for newbies who won't read which framework classes they should be using</p> <pre><code>Dim contents As String contents = My.Computer.FileSystem.ReadAllText("c:\mytextfile.txt") </code></pre> <p>Instead of this:</p> <pre><code>Dim contents As String contents = IO.File.ReadAllText("c:\mytextfile.txt") </code></pre> <p>My Question: <strong>Where is the MSDN documentation page for which speeddial button maps to what.. ?</strong><br> By choosing the name of the feature as My - they've just made searching a whole lot more fun that it needs to be. I need to code in C# and can't bear the fun of translating the training/how-to office prog videos which exclusively deal in VB.</p> <p>More on this from the Dans</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/magazine/cc163972.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc163972.aspx</a></li> <li><a href="http://blogs.msdn.com/danielfe/archive/2005/06/14/429092.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/danielfe/archive/2005/06/14/429092.aspx</a></li> </ul> <p>Juval Lowy ported My as That in C# as an interim solution. Don't ask me why...</p>
[ { "answer_id": 225261, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "My My.Application Microsoft.VisualBasic.ApplicationServices.ApplicationBase My.Computer Microsoft.VisualBasic.Devices.ServerComputer My.User Microsoft.VisualBasic.ApplicationServices.User My.Settings RootNamespace.Properties.Settings My.Resources RootNamespace.Properties.Resources" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
225,263
<p>Lets say I have a single object of type Car which I want to render as HTML:</p> <pre><code>class Car { public int Wheels { get; set; } public string Model { get; set; } } </code></pre> <p>I don't want to use the ASP.NET Repeater or ListView controls to bind because it seems too verbose. I just have the one object. But I still want to be able to use the databinding syntax so I won't have to use Labels or Literals. Something like:</p> <pre><code>&lt;div&gt; Wheels: &lt;%# (int)Eval("Wheels") %&gt;&lt;br /&gt; Model: &lt;%# (string)Eval("Model") %&gt; &lt;/div&gt; </code></pre> <p>Does anybody know about a control out there that does just that?</p> <p>And I am not ready to switch to ASP.NET MVC just yet.</p> <hr> <p>Unfortunately, the DetailsView control doesn't satisfy my needs because it doesn't seem to support the template-style syntax that I am after. It, too, needs to be bound to a DataSource object of a kind.</p> <p>I liked better the solution Maxim and Torkel suggested. I will try to go for that.</p>
[ { "answer_id": 225278, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 6, "selected": true, "text": "public Car CurrentCar { get; set; }\n <div>\n Wheels: <%= CurrentCar.Wheels %><br />\n Model: <%= CurrentCar.Model %>\n</div>\n" }, { "answer_id": 225297, "author": "Torkel", "author_id": 24425, "author_profile": "https://Stackoverflow.com/users/24425", "pm_score": 3, "selected": false, "text": "<div>\n Wheels: <%= Car.Wheels %>\n Wheels: <%= Car.Models %>\n</div>\n" }, { "answer_id": 225416, "author": "JacobE", "author_id": 30056, "author_profile": "https://Stackoverflow.com/users/30056", "pm_score": 0, "selected": false, "text": "<asp:Label ID=\"Label1\" Text=\"Probably a truck\" Visible='<%# CurrentCart.Wheels > 4 %>' runat=\"server\" />\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30056/" ]
225,266
<p>vi treats dash <code>-</code> and space <code>&nbsp;</code> as word separators for commands such as <code>dw</code> and <code>cw</code>.</p> <p>Is there a way to add underscore <code>_</code> as well?</p> <p>I quite often want to change part of a variable name containing underscores, such as changing <code>src_branch</code> to <code>dest_branch</code>. I end up counting characters and using <code>s</code> (like <code>3sdest</code>), but it would be much easier to use <code>cw</code> (like <code>cwdest</code>).</p>
[ { "answer_id": 225340, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 1, "selected": false, "text": "cf_dest_ ct_ f 'iskeyword' :help iskeyword" }, { "answer_id": 225361, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 6, "selected": true, "text": "iskeyword :he iskeyword ct_" }, { "answer_id": 729922, "author": "kbosak", "author_id": 87565, "author_profile": "https://Stackoverflow.com/users/87565", "pm_score": 0, "selected": false, "text": "set iskeyword=!-~,^*,^45,^124,^34,192-255,^_\n" }, { "answer_id": 1034221, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "_ :set iskeyword-=_ \n :help iskeyword" }, { "answer_id": 10589399, "author": "Anton Styagun", "author_id": 625742, "author_profile": "https://Stackoverflow.com/users/625742", "pm_score": 3, "selected": false, "text": ",b ,e ,w b e w c,edest\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11928/" ]
225,275
<p>I installed a windows service using installUtil.exe. </p> <p>After updating the code I used installUtil.exe again to install the service w/o uninstalling the original version first.</p> <p>When I now try to uninstall the service, installUtil.exe completes the uninstall successfully, but the service still appears. </p> <p>If I try to change its properties, I receive the message 'service is marked for deletion'. </p> <p>How can I force the deletion (preferrably w/o restarting the server)?</p>
[ { "answer_id": 232434, "author": "Aaron Weiker", "author_id": 30664, "author_profile": "https://Stackoverflow.com/users/30664", "pm_score": 4, "selected": false, "text": "sc delete sericeName\n" }, { "answer_id": 1540460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "sc delete <Service_Name>\n" }, { "answer_id": 6292700, "author": "johan", "author_id": 671203, "author_profile": "https://Stackoverflow.com/users/671203", "pm_score": 7, "selected": false, "text": "sc.exe queryex <SERVICE_NAME>\n taskkill /pid <SERVICE_PID> /f\n" }, { "answer_id": 14829578, "author": "incomplete", "author_id": 1117447, "author_profile": "https://Stackoverflow.com/users/1117447", "pm_score": 3, "selected": false, "text": "sc delete serviceName" }, { "answer_id": 16718964, "author": "Gabor Balazs", "author_id": 2414439, "author_profile": "https://Stackoverflow.com/users/2414439", "pm_score": 0, "selected": false, "text": "BOOL WINAPI CloseServiceHandle(\n SC_HANDLE hSCObject\n);\n" }, { "answer_id": 21983566, "author": "marco", "author_id": 2399370, "author_profile": "https://Stackoverflow.com/users/2399370", "pm_score": 1, "selected": false, "text": "REM Stop the service first\nnet stop My-Socket-Server\n\nREM Same as installutil.exe, just implemented in the service\nMy.Socket.Server.exe /u\n\n:loop1\n REM Easy way to wait for 5 seconds\n ping 192.0.2.2 -n 1 -w 5000 > nul\n sc delete My-Socket-Server\n echo %date% %time%: Trying to delete service.\n if errorlevel 1072 goto :loop1\n\nREM Just for output purposes, typically I get that the service does not exist\nsc query My-Socket-Server\n\nREM Installing the new service, same as installutil.exe but in code\nMy.Socket.Server.exe /i\n\nREM Start the new service\nnet start My-Socket-Server\n" }, { "answer_id": 40620237, "author": "Fernando Gonzalez Sanchez", "author_id": 1001395, "author_profile": "https://Stackoverflow.com/users/1001395", "pm_score": 2, "selected": false, "text": "HKLM\\SYSTEM\\CurrentControlSet\\Services" }, { "answer_id": 42149501, "author": "dragon788", "author_id": 3794873, "author_profile": "https://Stackoverflow.com/users/3794873", "pm_score": 0, "selected": false, "text": "$ServiceName = 'MyNaughtyService'\n$ServiceName | Stop-Service -ErrorAction SilentlyContinue\n# We tried nicely, now KILL!!!\n$ServiceNamePID = Get-Service | Where { $_.Name -eq $ServiceName} # If it was hung($_.Status -eq 'StopPending' -or $_.Status -eq 'Stopping') -and\n$ServicePID = (Get-WmiObject Win32_Service | Where {$_.Name -eq $ServiceNamePID.Name}).ProcessID\nStop-Process $ServicePID -Force\n" }, { "answer_id": 42322348, "author": "expirat001", "author_id": 1182880, "author_profile": "https://Stackoverflow.com/users/1182880", "pm_score": 3, "selected": false, "text": "$a = Get-WmiObject Win32_Service | Where-Object {$_.Name -eq 'psexesvc'}\n$a.Delete()\n" }, { "answer_id": 60721802, "author": "Richard", "author_id": 273605, "author_profile": "https://Stackoverflow.com/users/273605", "pm_score": 3, "selected": false, "text": "sc delete \"ServiceName\"\n sc.exe delete \"ServiceName\"\n" }, { "answer_id": 69087749, "author": "Alper Ebicoglu", "author_id": 1767482, "author_profile": "https://Stackoverflow.com/users/1767482", "pm_score": 2, "selected": false, "text": "net stop \"MyWindowsService\"\ntaskkill /F /IM mmc.exe\nsc delete \"MyWindowsService\"\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
225,277
<p>I want to call my .NET code from unmanaged C++. My process entrypoint is .NET based, so I don't have to worry about hosting the CLR. I know it can be done using COM wrappers for .NET objects, but I would like to access individual static methods of managed classes, so COM isn't my shortest/easiest route.</p>
[ { "answer_id": 225476, "author": "Aamir", "author_id": 30341, "author_profile": "https://Stackoverflow.com/users/30341", "pm_score": 1, "selected": false, "text": "/clr #using <Mydll.dll>\n MyNameSpace::MyClass^ obj = new MyNameSpace::MyClass();\n" }, { "answer_id": 6795543, "author": "MajesticRa", "author_id": 548894, "author_profile": "https://Stackoverflow.com/users/548894", "pm_score": 5, "selected": false, "text": "class Test\n{\n [DllExport(\"add\", CallingConvention = CallingConvention.StdCall)]\n public static int Add(int left, int right)\n {\n return left + right;\n } \n}\n extern \"C\" int add(int, int);\n\n int main()\n {\n int z = add(5,10);\n printf(\"The solution is found!!! Z is %i\",z);\n return 0;\n }\n The solution is found!!! Z is 15\n" }, { "answer_id": 68692560, "author": "Tom", "author_id": 5480147, "author_profile": "https://Stackoverflow.com/users/5480147", "pm_score": 1, "selected": false, "text": "public YahooAPI()\n{\n new Thread(() =>\n {\n Thread.CurrentThread.IsBackground = true;\n ShowForm();\n }).Start();\n}\n\nprivate static Form1 form = null;\npublic static void ShowForm()\n{\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n form = new Form1();\n Application.Run(form);\n}\n\npublic void SendValues(bool[] values)\n{\n if (form != null && form.ready) ...\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30324/" ]
225,283
<p>I have an application, written in C++ using MFC and Stingray libraries. The application works with a wide variety of large data types, which are all currently serialized based on MFC Document/View serialize derived functionality. I have also added options for XML serialization based on the Stingray libraries, which implements DOM via the Microsoft XML SDK. While easy to implement the performance is terrible, to the extent that it is unusable on anything other than very small documents.</p> <p>What other XML serialization tools would you folks recommend for this scenario. I don't want DOM, as it seems to be a memory hog, and I'm already dealing with large in memory data. Ideally, i'd like a streaming parser that is fast, and easy to use with MFC. My current front runner is <a href="http://expat.sourceforge.net/" rel="nofollow noreferrer">expat</a> which is fast and simple, but would require a lot of class by class serialization code to be added. Any other efficient and easier to implement alternatives out there that people would recommend?</p>
[ { "answer_id": 43092831, "author": "Pierre", "author_id": 282901, "author_profile": "https://Stackoverflow.com/users/282901", "pm_score": 1, "selected": false, "text": "<tag attribute=\"value\"/>\n <tag attribute=\"value\"> </tag>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22564/" ]
225,291
<p>I have been using git to keep two copies of my project in sync, one is my local box, the other the test server. This is an issue which occurs when I log onto our remote development server using ssh;</p> <pre><code>git clone me@me.mydevbox.com:/home/chris/myproject Initialized empty Git repository in /tmp/myproject/.git/ Password: bash: git-upload-pack: command not found fatal: The remote end hung up unexpectedly fetch-pack from 'me@me.mydevbox.com:/home/chris/myproject' failed. </code></pre> <p>(the file-names have been changed to protect the guilty... !) </p> <p>Both boxes run Solaris 10 AMD. I have done some digging, if I add <code>--upload-pack=$(which git-upload-pack)</code> the command works, (and proves that <code>$PATH</code> contains the path to 'git-upload-pack' as per the RTFM solution) but this is really annoying, plus 'git push' doesn't work, because I don't think there is a <code>--unpack=</code> option. </p> <p>Incidentally, all the git commands work fine from my local box, it is the same version of the software (1.5.4.2), installed on the same NFS mount at <code>/usr/local/bin</code>. </p> <p>Can anybody help?</p>
[ { "answer_id": 225315, "author": "Matt Curtis", "author_id": 17221, "author_profile": "https://Stackoverflow.com/users/17221", "pm_score": 8, "selected": true, "text": "git-upload-pack /usr/bin ssh you@remotemachine echo \\$PATH\n git-upload-pack .bashrc .zshenv .cshrc PATH which git-upload-pack /usr/bin/git-upload-pack /usr/bin PATH" }, { "answer_id": 412921, "author": "Skeletron", "author_id": 51616, "author_profile": "https://Stackoverflow.com/users/51616", "pm_score": 3, "selected": false, "text": "/usr/local/bin/ssh_session #!/bin/bash\nexport SSH_SESSION=1\nif [ -z \"$SSH_ORIGINAL_COMMAND\" ] ; then\n export SSH_LOGIN=1\n exec login -fp \"$USER\"\nelse\n export SSH_LOGIN=\n [ -r /etc/profile ] && source /etc/profile\n [ -r ~/.profile ] && source ~/.profile\n eval exec \"$SSH_ORIGINAL_COMMAND\"\nfi\n chmod +x /usr/local/bin/ssh_session /etc/sshd_config" }, { "answer_id": 550145, "author": "Andy", "author_id": 66542, "author_profile": "https://Stackoverflow.com/users/66542", "pm_score": 5, "selected": false, "text": "# Fix it with symlinks in /usr/bin\n$ cd /usr/bin/\n$ sudo ln -s /[path/to/git]/bin/git* .\n" }, { "answer_id": 1647238, "author": "Brian Hawkins", "author_id": 112699, "author_profile": "https://Stackoverflow.com/users/112699", "pm_score": 6, "selected": false, "text": "git clone -u /home/you/bin/git-upload-pack you@machine:code\n" }, { "answer_id": 2276525, "author": "tom", "author_id": 274764, "author_profile": "https://Stackoverflow.com/users/274764", "pm_score": 4, "selected": false, "text": "#PermitUserEnvironment no\n PermitUserEnvironment yes\n PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/git/bin\n PATH=$PATH:/usr/local/git/bin\n" }, { "answer_id": 6495787, "author": "Garrett", "author_id": 243434, "author_profile": "https://Stackoverflow.com/users/243434", "pm_score": 6, "selected": false, "text": "--upload-pack --receive-pack git config remote.origin.uploadpack /path/to/git-upload-pack\ngit config remote.origin.receivepack /path/to/git-receive-pack\n .git/config [remote \"origin\"]\n uploadpack = /path/to/git-upload-pack\n receivepack = /path/to/git-receive-pack\n clone -u git push git mypush [alias]\n myclone = clone --upload-pack /path/to/git-upload-pack\n myfetch = fetch --upload-pack /path/to/git-upload-pack\n mypull = pull --upload-pack /path/to/git-upload-pack\n mypush = push --receive-pack /path/to/git-receive-pack\n" }, { "answer_id": 7558586, "author": "Dennis", "author_id": 605890, "author_profile": "https://Stackoverflow.com/users/605890", "pm_score": 1, "selected": false, "text": "export PATH=/opt/git/bin:$PATH\n # If not running interactively, don't do anything\n[ -z \"$PS1\" ] && return\n" }, { "answer_id": 15719508, "author": "Yeison", "author_id": 707107, "author_profile": "https://Stackoverflow.com/users/707107", "pm_score": 0, "selected": false, "text": "git-upload-pack" }, { "answer_id": 57731220, "author": "felixc", "author_id": 3554727, "author_profile": "https://Stackoverflow.com/users/3554727", "pm_score": 1, "selected": false, "text": "git config remote.origin.uploadpack //path/to/git-upload-pack\ngit config remote.origin.receivepack //path/to/git-receive-pack\n" }, { "answer_id": 62334743, "author": "truefusion", "author_id": 4020848, "author_profile": "https://Stackoverflow.com/users/4020848", "pm_score": 1, "selected": false, "text": "sudo apt-get install git\n" }, { "answer_id": 72233199, "author": "Snekse", "author_id": 378151, "author_profile": "https://Stackoverflow.com/users/378151", "pm_score": 0, "selected": false, "text": "public internal" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24508/" ]
225,309
<p>Today i stumbled upon an interesting performance problem with a stored procedure running on Sql Server 2005 SP2 in a db running on compatible level of 80 (SQL2000).</p> <p>The proc runs about 8 Minutes and the execution plan shows the usage of an index with an actual row count of 1.339.241.423 which is about factor 1000 higher than the "real" actual rowcount of the table itself which is 1.144.640 as shown correctly by estimated row count. So the actual row count given by the query plan optimizer is definitly wrong!</p> <p><img src="https://i.stack.imgur.com/kESKH.png" alt="alt text"></p> <p>Interestingly enough, when i copy the procs parameter values inside the proc to local variables and than use the local variables in the actual query, everything works fine - the proc runs 18 seconds and the execution plan shows the right actual row count.</p> <p><strong>EDIT:</strong> As suggested by TrickyNixon, this seems to be a sign of the parameter sniffing problem. But actually, i get in both cases exact the same execution plan. Same indices are beeing used in the same order. The only difference i see is the way to high actual row count on the PK_ED_Transitions index when directly using the parametervalues.</p> <p>I have done dbcc dbreindex and UPDATE STATISTICS already without any success. dbcc show_statistics shows good data for the index, too.</p> <p>The proc is created WITH RECOMPILE so every time it runs a new execution plan is getting compiled.</p> <p>To be more specific - this one runs fast:</p> <pre><code>CREATE Proc [dbo].[myProc]( @Param datetime ) WITH RECOMPILE as set nocount on declare @local datetime set @local = @Param select some columns from table1 where column = @local group by some other columns </code></pre> <p>And this version runs terribly slow, but produces exactly the same execution plan (besides the too high actual row count on an used index):</p> <pre><code>CREATE Proc [dbo].[myProc]( @Param datetime ) WITH RECOMPILE as set nocount on select some columns from table1 where column = @Param group by some other columns </code></pre> <p>Any ideas? Anybody out there who knows where Sql Server gets the actual row count value from when calculating query plans?</p> <p><strong>Update</strong>: I tried the query on another server woth copat mode set to 90 (Sql2005). Its the same behavior. I think i will open up an ms support call, because this looks to me like a bug.</p>
[ { "answer_id": 225401, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "UPDATE STATISTICS" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25727/" ]
225,327
<p>Currently I am working with a <strong>custom</strong> regular expression validator <em>(unfortunately)</em>.</p> <p>I am trying to set the Regex pattern using a server side inline script like this:</p> <pre><code>ValidationExpression="&lt;%= RegExStrings.SomePattern %&gt;" </code></pre> <p>However, the script is not resolving to server side code. Instead it is being interpreted literally and I end up with something like this in the rendered markup:</p> <pre><code>ctl00_DefaultContent_regexValidatorInvitation.validationexpression = "&lt;%= RegExStrings.SomePattern %&gt;"; </code></pre> <p>Any clues as to why this is not resolving properly?</p>
[ { "answer_id": 225343, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 0, "selected": false, "text": "RegExValidator1.ValidationExpression = RegExStrings.SomePattern;\n" }, { "answer_id": 487844, "author": "MarkD", "author_id": 59773, "author_profile": "https://Stackoverflow.com/users/59773", "pm_score": 2, "selected": false, "text": "<%@ Page language=\"c#\" AutoEventWireup=\"true\" %>\n<html>\n <body >\n <form id=\"Form1\" method=\"post\" runat=\"server\" action=\"?<%=Request.QueryString%>\">\n Query String value: <%=Request.QueryString %>\n <br />\n <input type=submit />\n </form>\n </body>\n</html>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11702/" ]
225,330
<p>I'm writing a tool to report information about .NET applications deployed across environments and regions within my client's systems.</p> <p>I'd like to read the values of assembly attributes in these assemblies.</p> <p>This can be achieved using <code>Assembly.ReflectionOnlyLoad</code>, however even this approach keeps the assembly loaded. The issue here is that I cannot load two assemblies that have the same name from different paths, so naturally I can't compare the same application deployed in different systems.</p> <p>At this point I'm assuming the solution will involve using temporary <code>AppDomain</code>s.</p> <p>Can someone detail how to load an assembly into another <code>AppDomain</code>, read the attributes from it and then unload the <code>AppDomain</code>?</p> <p>This needs to work for assemblies on the file system as well as those at URL addresses.</p>
[ { "answer_id": 225355, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 7, "selected": true, "text": "public void TempLoadAssembly()\n{\n AppDomain tempDomain = AppDomain.CreateDomain(\"TemporaryAppDomain\");\n tempDomain.DoCallBack(LoaderCallback);\n AppDomain.Unload(tempDomain);\n}\n\nprivate void LoaderCallback()\n{\n Assembly.ReflectionOnlyLoad(\"YourAssembly\");\n // Do your stuff here\n}\n" }, { "answer_id": 733467, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 3, "selected": false, "text": "System.Diagnostics.FileVersionInfo var info = FileVersionInfo.GetVersionInfo(path);\n FileVersionInfo public string Comments { get; }\npublic string CompanyName { get; }\npublic int FileBuildPart { get; }\npublic string FileDescription { get; }\npublic int FileMajorPart { get; }\npublic int FileMinorPart { get; }\npublic string FileName { get; }\npublic int FilePrivatePart { get; }\npublic string FileVersion { get; }\npublic string InternalName { get; }\npublic bool IsDebug { get; }\npublic bool IsPatched { get; }\npublic bool IsPreRelease { get; }\npublic bool IsPrivateBuild { get; }\npublic bool IsSpecialBuild { get; }\npublic string Language { get; }\npublic string LegalCopyright { get; }\npublic string LegalTrademarks { get; }\npublic string OriginalFilename { get; }\npublic string PrivateBuild { get; }\npublic int ProductBuildPart { get; }\npublic int ProductMajorPart { get; }\npublic int ProductMinorPart { get; }\npublic string ProductName { get; }\npublic int ProductPrivatePart { get; }\npublic string ProductVersion { get; }\npublic string SpecialBuild { get; }\n" }, { "answer_id": 37970043, "author": "Artiom", "author_id": 797249, "author_profile": "https://Stackoverflow.com/users/797249", "pm_score": 3, "selected": false, "text": "var settings = new AppDomainSetup\n{\n ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,\n};\nvar childDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString(), null, settings);\n\n var handle = Activator.CreateInstance(childDomain,\n typeof(ReferenceLoader).Assembly.FullName,\n typeof(ReferenceLoader).FullName,\n false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.CurrentCulture, new object[0]);\n\n\nvar loader = (ReferenceLoader)handle.Unwrap();\n\n//This operation is executed in the new AppDomain\nvar paths = loader.LoadReferences(assemblyPath);\n\n\nAppDomain.Unload(childDomain);\n public class ReferenceLoader : MarshalByRefObject\n{\n public string[] LoadReferences(string assemblyPath)\n {\n var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyPath);\n var paths = assembly.GetReferencedAssemblies().Select(x => x.FullName).ToArray();\n return paths;\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24874/" ]
225,337
<p>What regex pattern would need I to pass to <code>java.lang.String.split()</code> to split a String into an Array of substrings using all whitespace characters (<code>' '</code>, <code>'\t'</code>, <code>'\n'</code>, etc.) as delimiters?</p>
[ { "answer_id": 225354, "author": "glenatron", "author_id": 15394, "author_profile": "https://Stackoverflow.com/users/15394", "pm_score": 7, "selected": false, "text": "\\w \\W \\s \\S \\d \\D" }, { "answer_id": 225360, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 11, "selected": true, "text": "myString.split(\"\\\\s+\");\n \"Hello[space character][tab character]World\"\n \"Hello\" \"World\" [space] [tab] \"\\s\" \"\\\\s\" \\\\s [ \\\\t\\\\n\\\\x0B\\\\f\\\\r]" }, { "answer_id": 9274100, "author": "Rishabh", "author_id": 1208677, "author_profile": "https://Stackoverflow.com/users/1208677", "pm_score": 1, "selected": false, "text": "myString.split(/[\\s\\W]+/)\n" }, { "answer_id": 9525071, "author": "Mike Manard", "author_id": 835445, "author_profile": "https://Stackoverflow.com/users/835445", "pm_score": 6, "selected": false, "text": "myString.split(/\\s+/g)\n" }, { "answer_id": 20314841, "author": "Felix Scheffer", "author_id": 569040, "author_profile": "https://Stackoverflow.com/users/569040", "pm_score": 3, "selected": false, "text": "StringUtils.split(\"abc def\")\n" }, { "answer_id": 25607143, "author": "RajeshVijayakumar", "author_id": 1369752, "author_profile": "https://Stackoverflow.com/users/1369752", "pm_score": 1, "selected": false, "text": " String textStr[] = yourString.split(\"\\\\r?\\\\n\");\n String textStr[] = yourString.split(\"\\\\s+\");\n" }, { "answer_id": 25736267, "author": "jake_astub", "author_id": 2569695, "author_profile": "https://Stackoverflow.com/users/2569695", "pm_score": 4, "selected": false, "text": "String[] elements = s.split(\"[\\\\s\\\\xA0]+\"); //include uniCode non-breaking\n" }, { "answer_id": 29585829, "author": "Olivia Liao", "author_id": 4083888, "author_profile": "https://Stackoverflow.com/users/4083888", "pm_score": 1, "selected": false, "text": "String str = \"Hello World\";\nString res[] = str.split(\"\\\\s+\");\n" }, { "answer_id": 36340734, "author": "Arrow", "author_id": 6120088, "author_profile": "https://Stackoverflow.com/users/6120088", "pm_score": 3, "selected": false, "text": "String string = \"Ram is going to school\";\nString[] arrayOfString = string.split(\"\\\\s+\");\n" }, { "answer_id": 40220586, "author": "Risith Ravisara", "author_id": 5951926, "author_profile": "https://Stackoverflow.com/users/5951926", "pm_score": -1, "selected": false, "text": " import java.util.*;\nclass Demo{\n public static void main(String args[]){\n Scanner input = new Scanner(System.in);\n System.out.print(\"Input String : \");\n String s1 = input.nextLine(); \n String[] tokens = s1.split(\"[\\\\s\\\\xA0]+\"); \n System.out.println(tokens.length); \n for(String s : tokens){\n System.out.println(s);\n\n } \n }\n}\n" }, { "answer_id": 63441506, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": false, "text": "s.split(\"(?U)\\\\s+\")\n ^^^^\n (?U) Pattern.UNICODE_CHARACTER_CLASS \\s s.split(\"(?U)(?<=\\\\s)(?=\\\\S)|(?<=\\\\S)(?=\\\\s)\")\n String s = \"Hello\\t World\\u00A0»\";\nSystem.out.println(Arrays.toString(s.split(\"(?U)\\\\s+\"))); // => [Hello, World, »]\nSystem.out.println(Arrays.toString(s.split(\"(?U)(?<=\\\\s)(?=\\\\S)|(?<=\\\\S)(?=\\\\s)\")));\n// => [Hello, , World, , »]\n" }, { "answer_id": 65836075, "author": "SKL", "author_id": 11638492, "author_profile": "https://Stackoverflow.com/users/11638492", "pm_score": 2, "selected": false, "text": "[0-9] [^0-9] [ \\t\\n\\x0B\\f\\r] [^\\s] [\\n\\x0B\\f\\r\\x85\\u2028\\u2029] [^\\v] [a-zA-Z_0-9] [^\\w] \\s [ ] [ ] String theString = \"Java<a space><a tab>Programming\"\nString []allParts = theString.split(\"\\\\s+\");\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30323/" ]
225,357
<p>I have to develop a system to <strong>monitor</strong> the <strong>generation/transmission</strong> of reports.</p> <ul> <li>System data will be stored in database tables (Sybase)</li> <li>Reports will be generated with different schedules ("mon-fri 10pm", "sat 5am", "1st day of the month", etc.)</li> <li>System will just monitor that the reports were created. It will not create the reports itself.</li> <li>System will notify appropriate personnel when a report did not finish.</li> <li>System will maintain a log of all generated reports</li> </ul> <p>Anyone know of a good(tried and proven) table(s) design for storing the task shedules?. I already have an idea, but I don't want reinvent the wheel.</p>
[ { "answer_id": 225354, "author": "glenatron", "author_id": 15394, "author_profile": "https://Stackoverflow.com/users/15394", "pm_score": 7, "selected": false, "text": "\\w \\W \\s \\S \\d \\D" }, { "answer_id": 225360, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 11, "selected": true, "text": "myString.split(\"\\\\s+\");\n \"Hello[space character][tab character]World\"\n \"Hello\" \"World\" [space] [tab] \"\\s\" \"\\\\s\" \\\\s [ \\\\t\\\\n\\\\x0B\\\\f\\\\r]" }, { "answer_id": 9274100, "author": "Rishabh", "author_id": 1208677, "author_profile": "https://Stackoverflow.com/users/1208677", "pm_score": 1, "selected": false, "text": "myString.split(/[\\s\\W]+/)\n" }, { "answer_id": 9525071, "author": "Mike Manard", "author_id": 835445, "author_profile": "https://Stackoverflow.com/users/835445", "pm_score": 6, "selected": false, "text": "myString.split(/\\s+/g)\n" }, { "answer_id": 20314841, "author": "Felix Scheffer", "author_id": 569040, "author_profile": "https://Stackoverflow.com/users/569040", "pm_score": 3, "selected": false, "text": "StringUtils.split(\"abc def\")\n" }, { "answer_id": 25607143, "author": "RajeshVijayakumar", "author_id": 1369752, "author_profile": "https://Stackoverflow.com/users/1369752", "pm_score": 1, "selected": false, "text": " String textStr[] = yourString.split(\"\\\\r?\\\\n\");\n String textStr[] = yourString.split(\"\\\\s+\");\n" }, { "answer_id": 25736267, "author": "jake_astub", "author_id": 2569695, "author_profile": "https://Stackoverflow.com/users/2569695", "pm_score": 4, "selected": false, "text": "String[] elements = s.split(\"[\\\\s\\\\xA0]+\"); //include uniCode non-breaking\n" }, { "answer_id": 29585829, "author": "Olivia Liao", "author_id": 4083888, "author_profile": "https://Stackoverflow.com/users/4083888", "pm_score": 1, "selected": false, "text": "String str = \"Hello World\";\nString res[] = str.split(\"\\\\s+\");\n" }, { "answer_id": 36340734, "author": "Arrow", "author_id": 6120088, "author_profile": "https://Stackoverflow.com/users/6120088", "pm_score": 3, "selected": false, "text": "String string = \"Ram is going to school\";\nString[] arrayOfString = string.split(\"\\\\s+\");\n" }, { "answer_id": 40220586, "author": "Risith Ravisara", "author_id": 5951926, "author_profile": "https://Stackoverflow.com/users/5951926", "pm_score": -1, "selected": false, "text": " import java.util.*;\nclass Demo{\n public static void main(String args[]){\n Scanner input = new Scanner(System.in);\n System.out.print(\"Input String : \");\n String s1 = input.nextLine(); \n String[] tokens = s1.split(\"[\\\\s\\\\xA0]+\"); \n System.out.println(tokens.length); \n for(String s : tokens){\n System.out.println(s);\n\n } \n }\n}\n" }, { "answer_id": 63441506, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": false, "text": "s.split(\"(?U)\\\\s+\")\n ^^^^\n (?U) Pattern.UNICODE_CHARACTER_CLASS \\s s.split(\"(?U)(?<=\\\\s)(?=\\\\S)|(?<=\\\\S)(?=\\\\s)\")\n String s = \"Hello\\t World\\u00A0»\";\nSystem.out.println(Arrays.toString(s.split(\"(?U)\\\\s+\"))); // => [Hello, World, »]\nSystem.out.println(Arrays.toString(s.split(\"(?U)(?<=\\\\s)(?=\\\\S)|(?<=\\\\S)(?=\\\\s)\")));\n// => [Hello, , World, , »]\n" }, { "answer_id": 65836075, "author": "SKL", "author_id": 11638492, "author_profile": "https://Stackoverflow.com/users/11638492", "pm_score": 2, "selected": false, "text": "[0-9] [^0-9] [ \\t\\n\\x0B\\f\\r] [^\\s] [\\n\\x0B\\f\\r\\x85\\u2028\\u2029] [^\\v] [a-zA-Z_0-9] [^\\w] \\s [ ] [ ] String theString = \"Java<a space><a tab>Programming\"\nString []allParts = theString.split(\"\\\\s+\");\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15884/" ]
225,362
<p>I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492'). </p> <p>In other words, I need to add correct amount of leading zeros to the number.</p> <pre><code>int n = 999; string str = some_function(n,6); //str = '000999' </code></pre> <p>Is there a function like this in C++?</p>
[ { "answer_id": 225372, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 2, "selected": false, "text": "int n = 999;\nchar buffer[256]; sprintf(buffer, \"%06d\", n);\nstring str(buffer);\n" }, { "answer_id": 225389, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 4, "selected": false, "text": "char str[7];\nsnprintf (str, 7, \"%06d\", n);\n" }, { "answer_id": 225435, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 7, "selected": true, "text": "#include <sstream>\n#include <iomanip>\n\nstd::stringstream ss;\nss << std::setw(10) << std::setfill('0') << i;\nstd::string s = ss.str();\n" }, { "answer_id": 225536, "author": "sep", "author_id": 30333, "author_profile": "https://Stackoverflow.com/users/30333", "pm_score": 2, "selected": false, "text": "inline string some_function(int n, int len)\n{\n string result(len--, '0');\n for (int val=(n<0)?-n:n; len>=0&&val!=0; --len,val/=10)\n result[len]='0'+val%10;\n if (len>=0&&n<0) result[0]='-';\n return result;\n}\n" }, { "answer_id": 226719, "author": "Len Holgate", "author_id": 7925, "author_profile": "https://Stackoverflow.com/users/7925", "pm_score": 4, "selected": false, "text": "stringstream sprintf sprintf stringstream" }, { "answer_id": 51307984, "author": "lubgr", "author_id": 9593596, "author_profile": "https://Stackoverflow.com/users/9593596", "pm_score": 2, "selected": false, "text": "#include <fmt/format.h>\n\nint n = 999;\n\nconst auto str = fmt::format(\"{:0>{}}\", n, 6);\n fmt::format(\"{:0>6}\", n) #include <absl/strings/str_format.h>\n\nint n = 999;\n\nconst auto str = absl::StrFormat(\"%0*d\", 6, n);\n abs::StrFormat(\"%06d\", n) #include <boost/format.hpp>\n\nint n = 999;\n\nconst auto str = boost::str(boost::format(\"%06d\") % n);\n % const std::string fmt = \"%0\" + std::to_string(6) + \"d\"; std::stringstream std::*printf" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26276/" ]
225,367
<p>Yes, I know you could use regular objects as associative arrays in JavaScript, but I'd like to use something closer to java's Map's implementation (HashMap, LinkedHashMap etc). Something that could have any kind of data used as key. Are there any good hash(code/table) in JavaScript implementation out there?</p>
[ { "answer_id": 225403, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 6, "selected": true, "text": "function HashMap () {\n var obj = [];\n return obj;\n}\n\nvar myHashMap = HashMap();\n function HashMap() {\n var obj = [];\n obj.size = function () {\n return this.length;\n };\n obj.isEmpty = function () {\n return this.length === 0;\n };\n obj.containsKey = function (key) {\n for (var i = 0; i < this.length; i++) {\n if (this[i].key === key) {\n return i;\n }\n }\n return -1;\n };\n obj.get = function (key) {\n var index = this.containsKey(key);\n if (index > -1) {\n return this[index].value;\n }\n };\n obj.put = function (key, value) {\n if (this.containsKey(key) !== -1) {\n return this.get(key);\n }\n this.push({'key': key, 'value': value});\n };\n obj.clear = function () {\n this = null; // Just kidding...\n };\n return obj;\n}\n var map = [{}, 'string', 4, {}];\n" }, { "answer_id": 225589, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 0, "selected": false, "text": "var ObjectMap = function()\n{\n this._keys = [];\n this._values = [];\n};\n\nObjectMap.prototype.clear = function()\n{\n this._keys = [];\n this._values = [];\n};\n\nObjectMap.prototype.get = function(key)\n{\n var index = this._indexOf(key, this._keys);\n if (index != -1)\n {\n return this._values[index];\n }\n return undefined;\n};\n\nObjectMap.prototype.hasKey = function(key)\n{\n return (this._indexOf(key, this._keys) != -1);\n};\n\nObjectMap.prototype.hasValue = function(value)\n{\n return (this._indexOf(value, this._values) != -1);\n};\n\nObjectMap.prototype.put = function(key, value)\n{\n var index = this._indexOf(key, this._keys);\n if (index == -1)\n {\n index = this._keys.length;\n }\n\n this._keys[index] = key;\n this._values[index] = value;\n};\n\nObjectMap.prototype.remove = function(key)\n{\n var index = this._indexOf(key, this._keys);\n if (index != -1)\n {\n this._keys.splice(index, 1);\n this._values.splice(index, 1);\n }\n};\n\nObjectMap.prototype.size = function()\n{\n return this._keys.length;\n};\n\nObjectMap.prototype._indexOf = function(item, list)\n{\n for (var i = 0, l = list.length; i < l; i++)\n {\n if (this._equals(list[i], item))\n {\n return i;\n }\n }\n return -1;\n};\n\nObjectMap.prototype._equals = function(a, b)\n{\n if (a === b)\n {\n return true;\n }\n\n // Custom objects can implement an equals method\n if (typeof a.equals == \"function\" &&\n typeof b.equals == \"function\")\n {\n return a.equals(b);\n }\n\n // Arrays are equal if they're the same length and their contents are equal\n if (a instanceof Array && b instanceof Array)\n {\n if (a.length != b.length)\n {\n return false;\n }\n\n for (var i = 0, l = a.length; i < l; i++)\n {\n if (!this._equals(a[i], b[i]))\n {\n return false;\n }\n }\n\n return true;\n }\n\n // Checking object properties - objects are equal if they have all the same\n // properties and they're all equal.\n var seenProperties = {};\n for (var prop in a)\n {\n if (a.hasOwnProperty(prop))\n {\n if (!b.hasOwnProperty(prop))\n {\n return false;\n }\n\n if (!this._equals(a[prop], b[prop]))\n {\n return false;\n }\n\n seenProperties[prop] = true;\n }\n }\n\n for (var prop in b)\n {\n if (!(prop in seenProperties) && b.hasOwnProperty(prop))\n {\n if (!a.hasOwnProperty(prop))\n {\n return false;\n }\n\n if (!this._equals(b[prop], a[prop]))\n {\n return false;\n }\n }\n }\n\n return true;\n};\n >>> var map = new ObjectMap();\n>>> var o = {a: 1, b: [1,2], c: true};\n>>> map.put(o, \"buns\");\n>>> map.get(o)\n\"buns\"\n>>> map.get({a: 1, b: [1,2], c: true});\n\"buns\"\n>>> map.get({a: 1, b: [1,2], c: true, d:\"hi\"});\n>>> var a = [1,2,3];\n>>> map.put(a, \"cheese\");\n>>> map.get(a);\n\"cheese\"\n>>> map.get([1,2,3]);\n\"cheese\"\n>>> map.get([1,2,3,4]);\n>>> var d = new Date();\n>>> map.put(d, \"toast\");\n>>> map.get(d);\n\"toast\"\n>>> map.get(new Date(d.valueOf()));\n\"toast\"\n >>> function TestObject(a) { this.a = a; };\n>>> var t = new TestObject(\"sandwich\");\n>>> map.put(t, \"butter\");\n>>> map.get({a: \"sandwich\"})\n\"butter\"\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12540/" ]
225,371
<p>How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?</p> <pre><code>$A = array(1,2,3,4,5,6,7,8); $B = array(1,2,3,4); $C = array_intersect($A,$B); //equals (1,2,3,4) $A = array_diff($A,$B); //equals (5,6,7,8) </code></pre> <p>Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.</p>
[ { "answer_id": 225678, "author": "rg88", "author_id": 11252, "author_profile": "https://Stackoverflow.com/users/11252", "pm_score": 6, "selected": true, "text": "array_diff array_intersect $arr_1 = array_diff($arr_1, $arr_2);\n$arr_2 = array_diff($arr_2, $arr_1);\n" }, { "answer_id": 31980965, "author": "Ashfaq Hussain", "author_id": 5030989, "author_profile": "https://Stackoverflow.com/users/5030989", "pm_score": -1, "selected": false, "text": "$a = array(0=>'a',1=>'x',2=>'c',3=>'y',4=>'w');\n$b = array(1=>'a',6=>'b',2=>'y',3=>'z');\n$c = array_intersect($a, $b);\n\n$result = array_diff($a, $c);\nprint_r($result);\n" }, { "answer_id": 39369882, "author": "Kalpesh Bhaliya", "author_id": 6804657, "author_profile": "https://Stackoverflow.com/users/6804657", "pm_score": 3, "selected": false, "text": "$clean1 = array_diff($array1, $array2); \n$clean2 = array_diff($array2, $array1); \n$final_output = array_merge($clean1, $clean2);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1149/" ]
225,375
<p>I'm developing a Java application using Eclipse. My project has two source directories that are both built and then some files are copied into the output folder. From the output directory I then run my application and all works well.</p> <p>However, I keep having these warnings:</p> <p><a href="http://www.freeimagehosting.net/uploads/128c1af93f.png">Snapshot from Problems tab in Eclipse http://www.freeimagehosting.net/uploads/128c1af93f.png</a></p> <p>Anyone know how to get rid of these warnings? Maybe by excluding some files, maybe based on the .svn extension or filename, from the build process? If so, how would I go about excluding those?</p>
[ { "answer_id": 225417, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 6, "selected": true, "text": "**/.svn/" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3379/" ]
225,394
<p>I have a List of strings that is regenerated every 5 seconds. I want to create a Context Menu and set its items dynamically using this list. The problem is that I don't have even a clue how to do that and manage the Click action for every item generated (which should use the same method with different parameter DoSomething("item_name")).</p> <p>How should I do this?</p> <p>Thanks for your time. Best regards.</p>
[ { "answer_id": 225514, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 5, "selected": true, "text": "myContextMenuStrip.Items.Clear();\n myContextMenuStrip.Items.Add(myString);\n private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)\n{\n DoSomething(e.ClickedItem.Text);\n}\n" }, { "answer_id": 41850885, "author": "tomloprod", "author_id": 4359029, "author_profile": "https://Stackoverflow.com/users/4359029", "pm_score": 1, "selected": false, "text": "ToolStripMenuItem //////////// Create a new \"ToolStripMenuItem\" object:\nToolStripMenuItem newMenuItem= new ToolStripMenuItem();\n\n//////////// Set a name, for identification purposes:\nnewMenuItem.Name = \"nameOfMenuItem\";\n\n//////////// Sets the text that will appear in the new context menu option:\nnewMenuItem.Text = \"This is another option!\";\n\n//////////// Add this new item to your context menu:\nmyContextMenuStrip.Items.Add(newMenuItem);\n ItemClicked myContextMenuStrip private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)\n{\n ToolStripItem item = e.ClickedItem;\n\n //////////// This will show \"nameOfMenuItem\":\n MessageBox.Show(item.Name, \"And the clicked option is...\");\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
225,413
<p>In vs2008, how can I (possibly with a macro) assign a shortcut key to collapse to definitons but leave regions expanded (they must expand if collapsed)?</p> <p><strong>EDIT:</strong> I hate regions but my co-workers does not (: So I want this to avoid the regions used by them.</p> <p>I read jeff's post. Ctrl M + O is what I really want to do, if there were not regions.</p>
[ { "answer_id": 1805597, "author": "JMD", "author_id": 56793, "author_profile": "https://Stackoverflow.com/users/56793", "pm_score": 4, "selected": true, "text": "Ctrl+Shift+R Ctrl+H #region //#region Alt+A Ctrl+H #endregion //#endregion Alt+A Ctrl+Shift+R Alt+F8 Ctrl+Shift+R Ctrl+H //#region #region Alt+A Ctrl+H //#endregion #endregion Alt+A Ctrl+Shift+R Alt+F8 Directives Alt+/ Assign Alt+Shift+/ Assign Alt+/ Ctrl+M+O Alt+Shift+/ //#region #//endregion" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
225,432
<p>With VS2005, I want to create a DLL and automatically export all symbols without adding <code>__declspec(dllexport)</code> everywhere, and without hand-creating <code>.def</code> files. Is there a way to do this?</p>
[ { "answer_id": 225457, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": -1, "selected": false, "text": "__declspec(dllexport) __declspec(dllimport)" }, { "answer_id": 32284832, "author": "Maks", "author_id": 3001953, "author_profile": "https://Stackoverflow.com/users/3001953", "pm_score": 7, "selected": true, "text": "// ProjectExport.h\n\n#ifndef __PROJECT_EXPORT_H\n#define __PROJECT_EXPORT_H\n\n#ifdef USEPROJECTLIBRARY\n#ifdef PROJECTLIBRARY_EXPORTS \n#define PROJECTAPI __declspec(dllexport)\n#else\n#define PROJECTAPI __declspec(dllimport)\n#endif\n#else\n#define PROJECTAPI\n#endif\n\n#endif\n #include \"ProjectExport.h\"\n\nnamespace hello {\n class PROJECTAPI Hello {} \n}\n #include \"ProjectExport.h\"\n\nPROJECTAPI void HelloWorld();\n extern \"C\" __declspec(dllexport) void HelloWorld();\n extern \"C\" void HelloWorld();\n EXPORTS \n_HelloWorld\n cmake_minimum_required(VERSION 2.6)\nproject(cmake_export_all)\n\nset(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)\n\nset(dir ${CMAKE_CURRENT_SOURCE_DIR})\nset(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"${dir}/bin\")\n\nset(SOURCE_EXE main.cpp)\n\ninclude_directories(foo)\n\nadd_executable(main ${SOURCE_EXE})\n\nadd_subdirectory(foo)\n\ntarget_link_libraries(main foo)\n #include \"foo.h\"\n\nint main() {\n HelloWorld();\n\n return 0;\n}\n project(foo)\n\nset(SOURCE_LIB foo.cpp)\n\nadd_library(foo SHARED ${SOURCE_LIB})\n void HelloWorld();\n #include <iostream>\n\nvoid HelloWorld() {\n std::cout << \"Hello World!\" << std::endl;\n}\n DUMPBIN /SYMBOLS example.obj > log.txt\n" }, { "answer_id": 49891803, "author": "Sergey", "author_id": 246605, "author_profile": "https://Stackoverflow.com/users/246605", "pm_score": 2, "selected": false, "text": "dumpbin /SYMBOLS $(Platform)\\$(Configuration)\\mdb.obj | findstr /R \"().*External.*mdb_.*\" > $(Platform)\\$(Configuration)\\mdb_symbols\n(echo EXPORTS & for /F \"usebackq tokens=2 delims==|\" %%E in (`type $(Platform)\\$(Configuration)\\mdb_symbols`) do @echo %%E) > $(Platform)\\$(Configuration)\\lmdb.def\n" }, { "answer_id": 54067711, "author": "jww", "author_id": 608639, "author_profile": "https://Stackoverflow.com/users/608639", "pm_score": 4, "selected": false, "text": "dump2def dump2def vcvarsall.bat cl.exe lib.exe link.exe nmake.exe static.lib dynamic.dll import.lib declspec(dllimport) AR = lib.exe\nARFLAGS = /nologo\n\nCXX_SRCS = a.cpp b.cpp c.cpp ...\nLIB_OBJS = a.obj b.obj c.obj ...\n\nstatic.lib: $(LIB_OBJS)\n $(AR) $(ARFLAGS) $(LIB_OBJS) /out:$@\n dumpbin.exe /LINKERMEMEBER *.dump dynamic.dump:\n dumpbin /LINKERMEMBER static.lib > dynamic.dump\n dump2def.exe *.dump *.def dump2def.exe dynamic.def: static.lib dynamic.dump\n dump2def.exe dynamic.dump dynamic.def\n LD = link.exe\nLDFLAGS = /OPT:REF /MACHINE:X64\nLDLIBS = kernel32.lib\n\ndynamic.dll: $(LIB_OBJS) dynamic.def\n $(LD) $(LDFLAGS) /DLL /DEF:dynamic.def /IGNORE:4102 $(LIB_OBJS) $(LDLIBS) /out:$@\n /IGNORE:4102 dynamic.def : warning LNK4102: export of deleting destructor 'public: virtual v\noid * __ptr64 __cdecl std::exception::`scalar deleting destructor'(unsigned int)\n __ptr64'; image may not run correctly\n dynamic.dll dynamic.lib dynamic.exp > cls && nmake /f test.nmake dynamic.dll\n...\nCreating library dynamic.lib and object dynamic.exp\n C:\\Users\\Test\\testdll>dir *.lib *.dll *.def *.exp\n Volume in drive C is Windows\n Volume Serial Number is CC36-23BE\n\n Directory of C:\\Users\\Test\\testdll\n\n01/06/2019 08:33 PM 71,501,578 static.lib\n01/06/2019 08:33 PM 11,532,052 dynamic.lib\n\n Directory of C:\\Users\\Test\\testdll\n\n01/06/2019 08:35 PM 5,143,552 dynamic.dll\n\n Directory of C:\\Users\\Test\\testdll\n\n01/06/2019 08:33 PM 1,923,070 dynamic.def\n\n Directory of C:\\Users\\Test\\testdll\n\n01/06/2019 08:35 PM 6,937,789 dynamic.exp\n 5 File(s) 97,038,041 bytes\n 0 Dir(s) 139,871,186,944 bytes free\n all: test.exe\n\ntest.exe: pch.pch static.lib $(TEST_OBJS)\n $(LD) $(LDFLAGS) $(TEST_OBJS) static.lib $(LDLIBS) /out:$@\n\nstatic.lib: $(LIB_OBJS)\n $(AR) $(ARFLAGS) $(LIB_OBJS) /out:$@\n\ndynamic.map:\n $(LD) $(LDFLAGS) /DLL /MAP /MAPINFO:EXPORTS $(LIB_OBJS) $(LDLIBS) /out:dynamic.dll\n\ndynamic.dump:\n dumpbin.exe /LINKERMEMBER static.lib /OUT:dynamic.dump\n\ndynamic.def: static.lib dynamic.dump\n dump2def.exe dynamic.dump\n\ndynamic.dll: $(LIB_OBJS) dynamic.def\n $(LD) $(LDFLAGS) /DLL /DEF:dynamic.def /IGNORE:4102 $(LIB_OBJS) $(LDLIBS) /out:$@\n\nclean:\n $(RM) /F /Q pch.pch $(LIB_OBJS) pch.obj static.lib $(TEST_OBJS) test.exe *.pdb\n dump2def.exe #include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <set>\n\ntypedef std::set<std::string> SymbolMap;\n\nvoid PrintHelpAndExit(int code)\n{\n std::cout << \"dump2def - create a module definitions file from a dumpbin file\" << std::endl;\n std::cout << \" Written and placed in public domain by Jeffrey Walton\" << std::endl;\n std::cout << std::endl;\n\n std::cout << \"Usage: \" << std::endl;\n\n std::cout << \" dump2def <infile>\" << std::endl;\n std::cout << \" - Create a def file from <infile> and write it to a file with\" << std::endl;\n std::cout << \" the same name as <infile> but using the .def extension\" << std::endl;\n\n std::cout << \" dump2def <infile> <outfile>\" << std::endl;\n std::cout << \" - Create a def file from <infile> and write it to <outfile>\" << std::endl;\n\n std::exit(code);\n}\n\nint main(int argc, char* argv[])\n{\n // ******************** Handle Options ******************** //\n\n // Convenience item\n std::vector<std::string> opts;\n for (size_t i=0; i<argc; ++i)\n opts.push_back(argv[i]);\n\n // Look for help\n std::string opt = opts.size() < 3 ? \"\" : opts[1].substr(0,2);\n if (opt == \"/h\" || opt == \"-h\" || opt == \"/?\" || opt == \"-?\")\n PrintHelpAndExit(0);\n\n // Add <outfile> as needed\n if (opts.size() == 2)\n {\n std::string outfile = opts[1];\n std::string::size_type pos = outfile.length() < 5 ? std::string::npos : outfile.length() - 5;\n if (pos == std::string::npos || outfile.substr(pos) != \".dump\")\n PrintHelpAndExit(1);\n\n outfile.replace(pos, 5, \".def\");\n opts.push_back(outfile);\n }\n\n // Check or exit\n if (opts.size() != 3)\n PrintHelpAndExit(1);\n\n // ******************** Read MAP file ******************** //\n\n SymbolMap symbols;\n\n try\n {\n std::ifstream infile(opts[1].c_str());\n std::string::size_type pos;\n std::string line;\n\n // Find start of the symbol table\n while (std::getline(infile, line))\n {\n pos = line.find(\"public symbols\");\n if (pos == std::string::npos) { continue; } \n\n // Eat the whitespace after the table heading\n infile >> std::ws;\n break;\n }\n\n while (std::getline(infile, line))\n {\n // End of table\n if (line.empty()) { break; }\n\n std::istringstream iss(line);\n std::string address, symbol;\n iss >> address >> symbol;\n\n symbols.insert(symbol);\n }\n }\n catch (const std::exception& ex)\n {\n std::cerr << \"Unexpected exception:\" << std::endl;\n std::cerr << ex.what() << std::endl;\n std::cerr << std::endl;\n\n PrintHelpAndExit(1);\n }\n\n // ******************** Write DEF file ******************** //\n\n try\n {\n std::ofstream outfile(opts[2].c_str());\n\n // Library name, cryptopp.dll\n std::string name = opts[2];\n std::string::size_type pos = name.find_last_of(\".\");\n\n if (pos != std::string::npos)\n name.erase(pos);\n\n outfile << \"LIBRARY \" << name << std::endl;\n outfile << \"DESCRIPTION \\\"Crypto++ Library\\\"\" << std::endl; \n outfile << \"EXPORTS\" << std::endl;\n outfile << std::endl;\n\n outfile << \"\\t;; \" << symbols.size() << \" symbols\" << std::endl;\n\n // Symbols from our object files\n SymbolMap::const_iterator it = symbols.begin();\n for ( ; it != symbols.end(); ++it)\n outfile << \"\\t\" << *it << std::endl;\n }\n catch (const std::exception& ex)\n {\n std::cerr << \"Unexpected exception:\" << std::endl;\n std::cerr << ex.what() << std::endl;\n std::cerr << std::endl;\n\n PrintHelpAndExit(1);\n } \n\n return 0;\n}\n" }, { "answer_id": 58958294, "author": "Alexander Samoylov", "author_id": 4807875, "author_profile": "https://Stackoverflow.com/users/4807875", "pm_score": 1, "selected": false, "text": "import sys, os\nfunctions = []\nstartPoint = False\n# Exclude standard API like sprintf to avoid multiple definition link error\nexcluded_functions = [ 'sprintf', 'snprintf', 'sscanf', 'fprintf' ]\n\nif len(sys.argv) < 2:\n print('Usage: %s <Input .dump file> <Output .def file>.' % sys.argv[0])\n print('Example: %s myStaticLib.dump exports.def' % sys.argv[0])\n sys.exit(1)\nprint('%s: Processing %s to %s' % (sys.argv[0], sys.argv[1], sys.argv[2]))\n\nfin = open(sys.argv[1], 'r')\nlines = fin.readlines()\nfin.close()\n\n# Reading\nfor l in lines:\n l_str = l.strip()\n if (startPoint == True) and (l_str == 'Summary'): # end point\n break\n if (startPoint == False) and (\"public symbols\" in l_str):\n startPoint = True\n continue\n if (startPoint == True) and l_str is not '':\n funcName = l_str.split(' ')[-1]\n if funcName not in excluded_functions:\n functions.append(\" \" + funcName)\n# Writing\nfout = open(sys.argv[2], 'w')\nfout.write('EXPORTS\\n')\nfor f in functions:\n fout.write('%s\\n' % f)\nfout.close()\n dumpbin /LINKERMEMBER:1 myStaticLib.lib > myExports.dump\npython dump2def.py myExports.dump myExports.def\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14443/" ]
225,458
<p>I'm using the <a href="http://sql.codeproject.com/KB/database/CsvReader.aspx" rel="nofollow noreferrer">CsvReader</a> library in my Windows Forms application, which is coded in horribly messy VB (I've recently taken over the project.)</p> <p>I'm currently capable of reading semi-colon separated files without quoting, but I'm having a problem: most of the input has quoted fields, but includes unescaped quote characters within the fields.</p> <p>I cannot change the input, so I must tackle it somehow. One solution would be to entirely disable quoting -- but I'm not quite sure how to do that...</p> <p>Any help would be appreciated! </p>
[ { "answer_id": 225782, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 0, "selected": false, "text": "File.ReadAllLines(filename) string.Split" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20321/" ]
225,471
<p>I have an <code>ActiveRecord</code> model, <code>Foo</code>, which has a <code>name</code> field. I'd like users to be able to search by name, but I'd like the search to ignore case and any accents. Thus, I'm also storing a <code>canonical_name</code> field against which to search:</p> <pre><code>class Foo validates_presence_of :name before_validate :set_canonical_name private def set_canonical_name self.canonical_name ||= canonicalize(self.name) if self.name end def canonicalize(x) x.downcase. # something here end end </code></pre> <p>I need to fill in the "something here" to replace the accented characters. Is there anything better than</p> <pre><code>x.downcase.gsub(/[àáâãäå]/,'a').gsub(/æ/,'ae').gsub(/ç/, 'c').gsub(/[èéêë]/,'e').... </code></pre> <p>And, for that matter, since I'm not on Ruby 1.9, I can't put those Unicode literals in my code. The actual regular expressions will look much uglier.</p>
[ { "answer_id": 292598, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 7, "selected": true, "text": ">> \"àáâãäå\".mb_chars.normalize(:kd).gsub(/[^\\x00-\\x7F]/n,'').downcase.to_s\n=> \"aaaaaa\"\n" }, { "answer_id": 474053, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "canonical_text original_text original_text canonical_text register_replacement([0x008A].pack('U'), 'S')\n" }, { "answer_id": 7160536, "author": "Mark Wilden", "author_id": 535425, "author_profile": "https://Stackoverflow.com/users/535425", "pm_score": 7, "selected": false, "text": "ActiveSupport::Inflector.transliterate >> ActiveSupport::Inflector.transliterate(\"àáâãäå\").to_s\n=> \"aaaaaa\"" }, { "answer_id": 8870902, "author": "Cheng", "author_id": 115005, "author_profile": "https://Stackoverflow.com/users/115005", "pm_score": 3, "selected": false, "text": "irb -ractive_support/all\n> \"àáâãäå\".mb_chars.normalize(:kd).gsub(/\\p{Mn}/, '')\naaaaaa\n # coding: utf-8\n normalize(:kd) gsub" }, { "answer_id": 12354036, "author": "fguillen", "author_id": 316700, "author_profile": "https://Stackoverflow.com/users/316700", "pm_score": 4, "selected": false, "text": "# coding: utf-8\nstring.tr(\n \"ÀÁÂÃÄÅàáâãäåĀāĂ㥹ÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňʼnŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž\",\n \"AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz\"\n)\n" }, { "answer_id": 12493448, "author": "eoghan.ocarragain", "author_id": 1036021, "author_profile": "https://Stackoverflow.com/users/1036021", "pm_score": 0, "selected": false, "text": "require 'unf'\nfoo.to_nfd.gsub(/[^\\x00-\\x7F]/n,'').downcase\n" }, { "answer_id": 16273726, "author": "Sudhir Jonathan", "author_id": 73831, "author_profile": "https://Stackoverflow.com/users/73831", "pm_score": 2, "selected": false, "text": "\"anything\".parameterize.underscore.humanize.downcase\n parameterize \"anything\".parameterize(\" \") \"anything\".parameterize(separator: \" \")" }, { "answer_id": 17809800, "author": "Dorian", "author_id": 407213, "author_profile": "https://Stackoverflow.com/users/407213", "pm_score": 4, "selected": false, "text": "\"Le cœur de la crémiére\".parameterize\n=> \"le-coeur-de-la-cremiere\"\n gem install activesupport require 'active_support/inflector'\n\n\"a&]'s--3\\014\\xC2àáâã3D\".parameterize\n# => \"a-s-3-3d\"\n" }, { "answer_id": 20586777, "author": "Diego Moreira", "author_id": 957737, "author_profile": "https://Stackoverflow.com/users/957737", "pm_score": 5, "selected": false, "text": "1.9.3-p392 :001 > require \"i18n\"\n => false\n1.9.3-p392 :002 > I18n.transliterate(\"Olá Mundo!\")\n => \"Ola Mundo!\"\n" }, { "answer_id": 53686995, "author": "user2553863", "author_id": 2553863, "author_profile": "https://Stackoverflow.com/users/2553863", "pm_score": 0, "selected": false, "text": "def self.up\n enable_extension \"unaccent\" # No falla si ya existe\nend\n 2.3.1 :045 > ActiveRecord::Base.connection.execute(\"SELECT unaccent('unaccent', 'àáâãäåÁÄ')\").first\n => {\"unaccent\"=>\"aaaaaaAA\"}\n scope :with_canonical_name, -> (name) {\n where(\"unaccent(foos.name) iLIKE unaccent('#{name}')\")\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
225,481
<p>I'm using T4 for generating repositories for LINQ to Entities entities. </p> <p>The repository contains (amongst other things) a List method suitable for paging. The documentation for <a href="http://msdn.microsoft.com/en-us/library/bb738474.aspx" rel="nofollow noreferrer">Supported and Unsupported Methods</a> does not mention it, but you can't "call" <code>Skip</code> on a unordered <code>IQueryable</code>. It will raise the following exception:</p> <blockquote> <p>System.NotSupportedException: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'..</p> </blockquote> <p>I solved it by allowing to define a default sorting via a partial method. But I'm having problems checking if the expression tree indeed contains an <code>OrderBy</code>.</p> <p>I've reduced the problem to as less code as possible:</p> <pre><code>public partial class Repository { partial void ProvideDefaultSorting(ref IQueryable&lt;Category&gt; currentQuery); public IQueryable&lt;Category&gt; List(int startIndex, int count) { IQueryable&lt;Category&gt; query = List(); ProvideDefaultSorting(ref query); if (!IsSorted(query)) { query = query.OrderBy(c =&gt; c.CategoryID); } return query.Skip(startIndex).Take(count); } public IQueryable&lt;Category&gt; List(string sortExpression, int startIndex, int count) { return List(sortExpression).Skip(startIndex).Take(count); } public IQueryable&lt;Category&gt; List(string sortExpression) { return AddSortingToTheExpressionTree(List(), sortExpression); } public IQueryable&lt;Category&gt; List() { NorthwindEntities ent = new NorthwindEntities(); return ent.Categories; } private Boolean IsSorted(IQueryable&lt;Category&gt; query) { return query is IOrderedQueryable&lt;Category&gt;; } } public partial class Repository { partial void ProvideDefaultSorting(ref IQueryable&lt;Category&gt; currentQuery) { currentQuery = currentQuery.Where(c =&gt; c.CategoryName.Contains(" ")); // no sorting.. } } </code></pre> <p>This is not my real implementation!</p> <p>But my <strong>question</strong> is, how could I implement the <code>IsSorted</code> method? The problem is that LINQ to Entities query's are always of the type <code>ObjectQuery</code>, which implements <code>IOrderedQueryable</code>.</p> <p>So how should I make sure an <code>OrderBy</code> method is present in the expression tree? Is the only option to parse the tree?</p> <p><strong>Update</strong><br> I've added two other overloads to make clear that it's not about how to add sorting support to the repository, but how to check if the <code>ProvideDefaultSorting</code> partial method has indeed added an <code>OrderBy</code> to the expression tree.</p> <p>The problem is, the first partial class is generate by a template and the implementation of the second part of the partial class is made by a team member at another time. You can compare it with the way the .NET Entity Framework generates the EntityContext, it allows extension points for other developers. So I want to try to make it robust and not crash when the <code>ProvideDefaultSorting</code> is not implemented correctly.</p> <p>So maybe the question is more, how can I confirm that the <code>ProvideDefaultSorting</code> did indeed add sorting to the expression tree.</p> <p><strong>Update 2</strong><br> The new question was answered, and accepted, I think I should change the title to match the question more. Or should I leave the current title because it will lead people with the same problem to this solution?</p>
[ { "answer_id": 225749, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "public interface IOrderByExpression<T>\n{\n ApplyOrdering(ref IQueryable<T> query);\n}\n\npublic class OrderByExpression<T, U> : IOrderByExpression<T>\n{\n public IQueryable<T> ApplyOrderBy(ref IQueryable<T> query)\n {\n query = query.OrderBy(exp);\n }\n //TODO OrderByDescending, ThenBy, ThenByDescending methods.\n\n private Expression<Func<T, U>> exp = null;\n\n //TODO bool descending?\n public OrderByExpression (Expression<Func<T, U>> myExpression)\n {\n exp = myExpression;\n }\n}\n public IQueryable<Category> List(int startIndex, int count, IOrderByExpression<Category> ordering)\n{\n NorthwindEntities ent = new NorthwindEntities();\n IQueryable<Category> query = ent.Categories;\n if (ordering == null)\n {\n ordering = new OrderByExpression<Category, int>(c => c.CategoryID)\n }\n ordering.ApplyOrdering(ref query);\n\n return query.Skip(startIndex).Take(count);\n}\n var query = List(20, 20, new OrderByExpression<Category, string>(c => c.CategoryName));\n" }, { "answer_id": 226349, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": " ProvideDefaultSorting(ref query);\n if (!IsSorted(query))\n {\n query = query.OrderBy(c => c.CategoryID);\n }\n //apply a default ordering\n query = query.OrderBy(c => c.CategoryID);\n //add to the ordering\n ProvideDefaultSorting(ref query);\n public void OrderManyTimes()\n {\n DataClasses1DataContext myDC = new DataClasses1DataContext();\n var query = myDC.Customers.OrderBy(c => c.Field3);\n query = query.OrderBy(c => c.Field2);\n query = query.OrderBy(c => c.Field1);\n\n Console.WriteLine(myDC.GetCommand(query).CommandText);\n\n }\n SELECT Field1, Field2, Field3\nFROM [dbo].[Customers] AS [t0]\nORDER BY [t0].[Field1], [t0].[Field2], [t0].[Field3]\n" }, { "answer_id": 226700, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": " public IOrderedQueryable<int> GetOrderedQueryable()\n {\n IQueryable<int> myInts = new List<int>() { 3, 4, 1, 2 }.AsQueryable<int>();\n return myInts.Where(i => i == 2);\n }\n public IOrderedQueryable<int> GetOrderedQueryable()\n {\n IQueryable<int> myInts = new List<int>() { 3, 4, 1, 2 }.AsQueryable<int>();\n return myInts.Where(i => i == 2) as IOrderedQueryable<int>;\n }\n public void GetOrderedQueryable(ref IOrderedQueryable<int> query)\n {\n query = query.Where(i => i == 2);\n }\n" }, { "answer_id": 227160, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "public partial class Repository\n{\n partial void ProvideDefaultSorting(ref IOrderedQueryable<Category> currentQuery);\n\n public IQueryable<Category> List(int startIndex, int count)\n {\n NorthwindEntities ent = new NorthwindEntities();\n IOrderedQueryable<Category> query = ent.CategorySet;\n var oldQuery = query;\n ProvideDefaultSorting(ref query);\n if (oldQuery.Equals(query)) // the partial method did nothing with the query, or just didn't exist\n {\n query = query.OrderBy(c => c.CategoryID);\n }\n return query.Skip(startIndex).Take(count);\n }\n // the rest.. \n}\n\npublic partial class Repository\n{\n partial void ProvideDefaultSorting(ref IOrderedQueryable<Category> currentQuery)\n {\n currentQuery = currentQuery.Where(c => c.CategoryName.Contains(\" \")).OrderBy(c => c.CategoryName); // compile time forced sotring\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11098/" ]
225,489
<p>In regular Java, you can get the text of a stack trace by passing a PrintWriter to printStackTrace. I have a feeling I know the answer to this (i.e. "No") but,</p> <p>Is there any way to obtain the text of a stack trace in JavaME as a String?</p> <p><strong>Update:</strong></p> <p>I should mention that I'm restricted to CLDC 1.0</p>
[ { "answer_id": 225523, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": -1, "selected": false, "text": "try{\n throw new Exception(\"Message\"); \n} catch (Exception ex){\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n ex.printStackTrace(new PrintStream(out));\n System.out.println(new String(out.toByteArray()));\n}\n" }, { "answer_id": 225851, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 3, "selected": true, "text": "catch(Exception) catch(Throwable) java.lang.Error OutOfMemoryError System.gc()" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
225,535
<p>In our database, we have a system set up to keep track of applications. We have a bool column that indicates whether or not the application is approved. Then there's another column that indicates whether or not the application is denied. If neither column is true, then the application is considered to be pending.</p> <p>Is there any easy way to merge those into one value (like say a tinyint or maybe a string that says "approved", "denied", or "pending") in a view? Or is this going to require something like a Table-valued function?</p> <p><strong>UPDATE:</strong> It's difficult to choose an answer choose since they were all helpful. I'll go with baldy's since he posted first.</p>
[ { "answer_id": 225569, "author": "BenR", "author_id": 18039, "author_profile": "https://Stackoverflow.com/users/18039", "pm_score": 3, "selected": false, "text": "select case \n when Approved = 1 then 'Approved'\n when Denied = 1 then 'Denied'\n else 'Pending'\n end 'Status'\n" }, { "answer_id": 225593, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "CASE \n --Denied has precedence\n WHEN Denied = 1 THEN 'Denied'\n WHEN Approved = 1 THEN 'Approved'\n ELSE 'Pending'\nEND as Status\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
225,542
<p>I have a Makefile that starts by running a tool before applying the build rules (which this tool writes for me). If this tool, which is a python script, exits with a non-null status code, I want GNU Make to stop right there and not go on with building the program.</p> <p>Currently, I do something like this (top level, i.e. column 1):</p> <pre><code>$(info Generating build rules...) $(shell python collect_sources.py) include BuildRules.mk </code></pre> <p>But this does not stop make if <code>collect_sources.py</code> exits with a status code of 1. This also captures the standard output of <code>collect_sources.py</code> but does not print it out, so I have the feeling I'm looking in the wrong direction.</p> <p>If at all possible, the solution should even work when a simple MS-DOS shell is the standard system shell.</p> <p>Any suggestion?</p>
[ { "answer_id": 225626, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 3, "selected": false, "text": "$(if $(shell if your_command; then echo ok; fi), , $(error your_command failed))\n your_command your_command && echo ok if shell your_command" }, { "answer_id": 226974, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "BuildRules.mk: collect_sources.py\n python $< >$@\n\ninclude BuildRules.mk\n" }, { "answer_id": 230444, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 3, "selected": true, "text": "SHELL_OUTPUT := $(shell python collect_sources.py 2>&1)\nifeq ($(filter error: [Errno %],$(SHELL_OUTPUT)),)\n $(info $(SHELL_OUTPUT))\nelse\n $(error $(SHELL_OUTPUT))\nendif\n \"collect_sources: error:\" \"[Errno 2]\" $(info) $(error) ifeq ... endif" }, { "answer_id": 49963856, "author": "Alex Cohn", "author_id": 192373, "author_profile": "https://Stackoverflow.com/users/192373", "pm_score": 0, "selected": false, "text": ".PHONY: BuildRules.mk\n\nBuildRules.mk: collect_sources.py\n echo Generating build rules...)\n python $< >$@\n $(MAKE) -f BuildRules.mk\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095/" ]
225,545
<p>I'm creating a C# dll, which is going to be used by others developers in WinForms. For some reasons, I want to detect, if methods from this library, are called from Main (GUI) Thread and warn developer he has done such a thing (ie. in log file). Is there any reasonable way to detect calling method from main thread? Remember I have no access to WinForm application.</p>
[ { "answer_id": 225556, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 5, "selected": true, "text": "if (MyLibraryControl.InvokeRequired)\n //do your thing here\n" }, { "answer_id": 225565, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "SynchronizationContext" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30343/" ]
225,548
<p>Where can I find algorithms for image distortions? There are so much info of Blur and other classic algorithms but so little of more complex ones. In particular, I am interested in swirl effect image distortion algorithm.</p>
[ { "answer_id": 225575, "author": "Chris Johnson", "author_id": 23732, "author_profile": "https://Stackoverflow.com/users/23732", "pm_score": 6, "selected": true, "text": "a = amount of rotation\nb = size of effect\n\nangle = a*exp(-(x*x+y*y)/(b*b))\nu = cos(angle)*x + sin(angle)*y\nv = -sin(angle)*x + cos(angle)*y\n angle = a*(x*x+y*y)\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25194/" ]
225,550
<p>I'm filtering the messages that come to a form with PreFilterMessage like this:</p> <p><code>print("code sample");</code></p> <pre><code> public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_KEYDOWN &amp;&amp; (int)m.WParam == VK_ESCAPE) { this.Close(); return true; } return false; } </code></pre> <p><code>print("code sample");</code></p> <p>but the matter is that form closes only for the first time. After reopening a form it won't close anymore by pressing ESC.</p> <p>How can I accomplish this?</p> <p>Thanks</p>
[ { "answer_id": 232390, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 0, "selected": false, "text": "ShowDialog() Close() PreFilterMessage() this.Visible = false; Control.Hide" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
225,560
<p>I think questions like this are the reason why I don't like working with PHP. The manual is good, if you can find what you are looking for. After reading through the <a href="http://us3.php.net/array" rel="nofollow noreferrer">Array Functions</a>, I didn't see one that provides the functionality I need.</p> <p>I have an array (in my case, numerically indexed) that I want to scan for a particular value and, if it's there, remove it. And then, when all instances of that value have been removed, I want to rearrange the array using <a href="http://us3.php.net/manual/en/function.array-values.php" rel="nofollow noreferrer">array_values</a>.</p>
[ { "answer_id": 225566, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "array_diff $array1 = array(\"a\" => \"green\", \"red\", \"blue\", \"red\");\n$array2 = array(\"b\" => \"green\", \"yellow\", \"red\");\n$result = array_diff($array1, $array2);\n \"blue\"" }, { "answer_id": 225632, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 2, "selected": false, "text": "<?\n$test = \"hello\";\n$array1 = array(\"a\" => \"green\", \"red\", \"bicycle\", \"red\");\n$array2 = array(\"b\" => \"green\", \"yellow\", \"red\", \"blue\", \"yellow\", \"pink\");\n$result = array_diff($array1, $array2);\nprint_r ($result);\n?> \n Array\n(\n [1] => bicycle\n)\n" }, { "answer_id": 225906, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 0, "selected": false, "text": "function array_unset_value($value, &$array) {\n $key = array_search($value, $array);\n while ($key !== false) {\n unset($array[$key]);\n $key = array_search($value, $array);\n }\n}\n" }, { "answer_id": 225911, "author": "Jon", "author_id": 17526, "author_profile": "https://Stackoverflow.com/users/17526", "pm_score": 0, "selected": false, "text": "function myFilter($Value){\n if($Value == 'red'){\n return false;\n }\n return true;\n}\n\n$Values = array(\"a\" => \"green\", \"red\", \"bicycle\", \"red\");\n\n$Values = array_filter($Values, 'myFilter');\n array {\n [\"a\"] => \"green\"\n [1] => \"bicycle\"\n}\n $Values = array_values(array_filter($Values, 'myFilter'));\n array_filter($Values, array($this,'myFilter'));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
225,563
<p>I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely <strong>different parts of the DOM</strong> and mostly positioned using float.</p> <p>All I need is some code to get the absolute position difference between 2 floating DOM elements, preferrably using jQuery. The only thing I found were some hacks parsing upwards the DOM but always very browser-specific (e.g. "this does not work well with Firefox or IE or whatever").</p> <p>Best would be something like this:</p> <pre><code>var distance = getDistance(element1, element2); </code></pre> <p>or in jQuery notation:</p> <pre><code>var distance = $(element1).distanceTo($(element2)); </code></pre>
[ { "answer_id": 225628, "author": "Claudio", "author_id": 30122, "author_profile": "https://Stackoverflow.com/users/30122", "pm_score": 1, "selected": false, "text": "var dx = obj1.offsetLeft - obj2.offsetLeft;\nvar dy = obj1.offsetTop - obj2.offsetTop;\nvar distance = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2));\n" }, { "answer_id": 225760, "author": "Claudio", "author_id": 30122, "author_profile": "https://Stackoverflow.com/users/30122", "pm_score": 1, "selected": false, "text": "var isIE = navigator.appName.indexOf(\"Microsoft\") != -1;\n\nfunction getDistance(obj1, obj2){\n var obj1 = document.getElementById(obj1);\n var obj2 = document.getElementById(obj2);\n var pos1 = getRelativePos(obj1);\n var pos2 = getRelativePos(obj2);\n var dx = pos1.offsetLeft - pos2.offsetLeft;\n var dy = pos1.offsetTop - pos2.offsetTop;\n return {x:dx, y:dy};\n}\nfunction getRelativePos(obj){\nvar pos = {offsetLeft:0,offsetTop:0};\nwhile(obj!=null){\n pos.offsetLeft += obj.offsetLeft;\n pos.offsetTop += obj.offsetTop;\n obj = isIE ? obj.parentElement : obj.offsetParent;\n}\nreturn pos;\n}\n//\nvar obj = getDistance(\"element1\",\"element2\")\nalert(obj.x+\" | \"+obj.y);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22592/" ]
225,572
<p>In the spirit of <a href="https://stackoverflow.com/questions/171156/best-practices-always-return-a-never-a">Best Practices: Always return a ____, never a ____</a>, I face a similar question in my upcoming <a href="https://stackoverflow.com/questions/219164/generics-in-legacy-code">migration from JDK1.4.2 to JDK5 and more</a>. (Yes, I <em>know</em>, <a href="http://java.sun.com/products/archive/eol.policy.html" rel="noreferrer">JDK1.4.2 is EOL!</a> ;-) ).</p> <p>For functions returning a collection (which are not simple <a href="https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property">property collections</a>), I always prefer (in JDK1.4.2) returning an Array instead of a generic List, because:</p> <ul> <li>it enforces the returning type (<code>MyObject[]</code> instead of List of Objects, much more <strong><em>type-safe</em></strong> on a static -- as in 'compilation' -- level)</li> <li>it <em>suggests</em> a 'read-only' character to the returned collection (it is more complicated to add an element to the collection, even though this is not as rigorous as the 'read-only' keyword in c#). This is not the same as saying it is 'immutable' since the references inside the array can still be modified...</li> </ul> <p>Of course, I do always <em>create</em> this returned array (I do not expose any 'internal' array)</p> <p>Now, In JDK5 and more, I could use <code>List&lt;MyObject&gt;</code> if I want to. </p> <p><strong>What are the good reasons for choosing to return <code>MyObject[]</code> instead of List or <code>Collection&lt;MyObject&gt;</code> when coding in java5 ?</strong></p> <p>Bonus, if <code>Collection&lt;MyObject&gt;</code> is used, is it possible to:</p> <ul> <li>enforce a read-only attribute on the returned collection ? (no <code>add()</code> or <code>remove()</code> possible)</li> <li>enforce an immutable aspect to the returned collection ? (even the references of that collection can not be modified)</li> </ul> <p>PS: The <a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html" rel="noreferrer">JavaGenericFAQ</a> did not quite have that one.</p>
[ { "answer_id": 225613, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 2, "selected": false, "text": "Collections" }, { "answer_id": 277315, "author": "mcjabberz", "author_id": 30323, "author_profile": "https://Stackoverflow.com/users/30323", "pm_score": 4, "selected": false, "text": "public void doSomething(Collection<String> strs) { ... }\npublic void doSomething(Collection<Integer> ints) { ... }\n public void doSomething(String[] strs) {\n List<String> strList = Arrays.asList(strs);\n ...\n}\n\npublic void doSomething(Integer[] ints) {\n List<Integer> intList = Arrays.asList(ints);\n ...\n}\n\npublic static void main(String[] args) {\n List<String> strs = new ArrayList<String>();\n List<Integer> ints = new ArrayList<Integer>();\n obj.doSomething(strs.toArray());\n obj.doSomething(ints.toArray());\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
225,594
<p>Can <code>Thread.getContextClassLoader()</code> be null ? The javadoc is not really clear.<br> Should a library take this case into account ?</p> <p>Update: the reason I asked is that <code>beansbinding.dev.java.net</code> does <em>not</em> work in this case (and my code does <code>setContextClassLoader(null)</code></p>
[ { "answer_id": 225670, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 3, "selected": false, "text": "Thread.setContextClassLoader(null)" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22850/" ]
225,598
<p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p> <p>For example, compared to..</p> <ul> <li><a href="http://phpundercontrol.org/about.html" rel="noreferrer">phpUnderControl</a></li> <li><a href="http://jenkins-ci.org/content/about-jenkins-ci" rel="noreferrer">Jenkins</a> <ul> <li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson" rel="noreferrer">Hudson</a></li> </ul></li> <li><a href="http://cruisecontrolrb.thoughtworks.com/" rel="noreferrer">CruiseControl.rb</a></li> </ul> <p>..and others, <a href="http://buildbot.python.org/stable/" rel="noreferrer">BuildBot</a> looks rather.. archaic</p> <p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html" rel="noreferrer">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p> <p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p> <hr> <p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org" rel="noreferrer">Jenkins</a> is different.</p> <p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/" rel="noreferrer">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac" rel="noreferrer">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p> <p>Setting Hudson up for a Python project was pretty simple:</p> <ul> <li>Download Hudson from <a href="http://hudson-ci.org/" rel="noreferrer">http://hudson-ci.org/</a></li> <li>Run it with <code>java -jar hudson.war</code></li> <li>Open the web interface on the default address of <code>http://localhost:8080</code></li> <li>Go to Manage Hudson, Plugins, click "Update" or similar</li> <li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li> <li>Create a new project, enter the repository, SCM polling intervals and so on</li> <li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li> <li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li> <li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li> </ul> <p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins" rel="noreferrer">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p> <ul> <li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin" rel="noreferrer">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/" rel="noreferrer">sloccount</a> separately</li> <li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations" rel="noreferrer">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li> <li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin" rel="noreferrer">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li> </ul>
[ { "answer_id": 667800, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 6, "selected": true, "text": "nosetests --with-xunit --enable-cover\n" }, { "answer_id": 5119040, "author": "Nick Holden", "author_id": 441462, "author_profile": "https://Stackoverflow.com/users/441462", "pm_score": 3, "selected": false, "text": "#!/var/lib/hudson/venv/main/bin/python\nimport os\nimport re\nimport subprocess\nimport logging\nimport optparse\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s')\n\n#venvDir = \"/var/lib/hudson/venv/main/bin/\"\n\nUPLOAD_REPO = \"http://ldndev01:3442\"\n\ndef call_command(command, cwd, ignore_error_code=False):\n try:\n logging.info(\"Running: %s\" % command)\n status = subprocess.call(command, cwd=cwd, shell=True)\n if not ignore_error_code and status != 0:\n raise Exception(\"Last command failed\")\n\n return status\n\n except:\n logging.exception(\"Could not run command %s\" % command)\n raise\n\ndef main():\n usage = \"usage: %prog [options]\"\n parser = optparse.OptionParser(usage)\n parser.add_option(\"-w\", \"--workspace\", dest=\"workspace\",\n help=\"workspace folder for the job\")\n parser.add_option(\"-p\", \"--package\", dest=\"package\",\n help=\"the package name i.e., back_office.reconciler\")\n parser.add_option(\"-v\", \"--build_number\", dest=\"build_number\",\n help=\"the build number, which will get put at the end of the package version\")\n options, args = parser.parse_args()\n\n if not options.workspace or not options.package:\n raise Exception(\"Need both args, do --help for info\")\n\n venvDir = options.package + \"_venv/\"\n\n #find out if venv is there\n if not os.path.exists(venvDir):\n #make it\n call_command(\"virtualenv %s --no-site-packages\" % venvDir,\n options.workspace)\n\n #install the venv/make sure its there plus install the local package\n call_command(\"%sbin/pip install -e ./ --extra-index %s\" % (venvDir, UPLOAD_REPO),\n options.workspace)\n\n #make sure pylint, nose and coverage are installed\n call_command(\"%sbin/pip install nose pylint coverage epydoc\" % venvDir,\n options.workspace)\n\n #make sure we have an __init__.py\n #this shouldn't be needed if the packages are set up correctly\n #modules = options.package.split(\".\")\n #if len(modules) > 1: \n # call_command(\"touch '%s/__init__.py'\" % modules[0], \n # options.workspace)\n #do the nosetests\n test_status = call_command(\"%sbin/nosetests %s --with-xunit --with-coverage --cover-package %s --cover-erase\" % (venvDir,\n options.package.replace(\".\", \"/\"),\n options.package),\n options.workspace, True)\n #produce coverage report -i for ignore weird missing file errors\n call_command(\"%sbin/coverage xml -i\" % venvDir,\n options.workspace)\n #move it so that the code coverage plugin can find it\n call_command(\"mv coverage.xml %s\" % (options.package.replace(\".\", \"/\")),\n options.workspace)\n #run pylint\n call_command(\"%sbin/pylint --rcfile ~/pylint.rc -f parseable %s > pylint.txt\" % (venvDir, \n options.package),\n options.workspace, True)\n\n #remove old dists so we only have the newest at the end\n call_command(\"rm -rfv %s\" % (options.workspace + \"/dist\"),\n options.workspace)\n\n #if the build passes upload the result to the egg_basket\n if test_status == 0:\n logging.info(\"Success - uploading egg\")\n upload_bit = \"upload -r %s/upload\" % UPLOAD_REPO\n else:\n logging.info(\"Failure - not uploading egg\")\n upload_bit = \"\"\n\n #create egg\n call_command(\"%sbin/python setup.py egg_info --tag-build=.0.%s --tag-svn-revision --tag-date sdist %s\" % (venvDir,\n options.build_number,\n upload_bit),\n options.workspace)\n\n call_command(\"%sbin/epydoc --html --graph all %s\" % (venvDir, options.package),\n options.workspace)\n\n logging.info(\"Complete\")\n\nif __name__ == \"__main__\":\n main()\n pip -E /location/of/my/venv/ install my_package==X.Y.Z --extra-index http://my_repo\n pip -E /location/of/my/venv/ install -e ./ --extra-index http://my_repo\n" }, { "answer_id": 32852066, "author": "Dwight Spencer", "author_id": 522599, "author_profile": "https://Stackoverflow.com/users/522599", "pm_score": 0, "selected": false, "text": "make(1) expect(1) crontab(1) systemd.unit(5) incrontab(1)" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
225,617
<p>I'm trying to get this piece of code working a little better. I suspect it's the loop reading one byte at a time. I couldn't find another way of doing this with gzip decompression. Implementing a <code>StreamReader</code> is fine, but it returns a string which I can't pass to the decompression stream.</p> <p>Is there a better way?</p> <pre><code>byte[] bufffer = null; List&lt;byte&gt; resourceBytes = new List&lt;byte&gt;(); int byteValue = 0; WebResource resource = new WebResource(); HttpWebResponse webResponse = null; try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(resourceUri); webRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); webRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); webRequest.UserAgent = agent; webRequest.Accept = "text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1"; webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.Referer = resourceUri.OriginalString; webRequest.Timeout = 5000; webResponse = (HttpWebResponse)webRequest.GetResponse(); Stream webStream = webResponse.GetResponseStream(); if (!string.IsNullOrEmpty(webResponse.ContentEncoding)) { if (webResponse.ContentEncoding.ToLower().Contains("gzip")) { webStream = new GZipStream(webStream, CompressionMode.Decompress); } else if (webResponse.ContentEncoding.ToLower().Contains("deflate")) { webStream = new DeflateStream(webStream, CompressionMode.Decompress); } } do { byteValue = webStream.ReadByte(); if (byteValue != -1) { resourceBytes.Add((byte)byteValue); } } while (byteValue != -1); //Free up resources webStream.Close(); webResponse.Close(); bufffer = resourceBytes.ToArray(); </code></pre>
[ { "answer_id": 225622, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "String ReponseText;\n\nIO.StreamReader ResponseReader = New IO.StreamReader(webStream );\nReponseText= ResponseReader.ReadToEnd();\n 'Declare Array Same size as response\nDim ResponseData(webStream .Length) As Byte \n'Read all the data at once\nwebStream.Read(ResponseData, 0, webStream .Length)\n" }, { "answer_id": 225634, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "int bytesRead;\nbyte[] buffer = new byte[1024];\nwhile((bytesRead = webStream.Read(buffer, 0, buffer.Length)) > 0) {\n // process \"bytesRead\" worth of data from \"buffer\"\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
225,624
<p>I have a site, and it will be sold to different clients but for maintenance reasons, we will be keeping one codebase. So this means that this one codebase will have to be dynamic enough to have different styles and so forth, depending on the client.</p> <p>The domain would be a subdomain-type system, so: projectname.clientname.com , projectname.clientname.com, and so forth, where client name is the company who we have sold the system to.</p> <p>What I'm trying to do is to have a different theme load up depending on the domain. So I may have ecards.savills.com, and for that, I have a folder in Themes called Savills, and inside that folder called Savills, a .CSS file and I want to load that. I've been playing with the request object, but no luck.</p> <p>I've tried several methods to achieve this, using stylesheettheme (don't need to skin buttons btw), but I keep getting stack overflows in a system dll for .NET.</p> <p>What is a robust way to achieve this?</p>
[ { "answer_id": 225646, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "/* Do you have a folder in \"Themes\" or \"APP_Themes\" called Savillis? */\n /* Are you doing that? */\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30004/" ]
225,635
<p>Using the client-side ASP.NET AJAX library, I have created an instance of a client component with the $create shortcut-method (<a href="http://msdn.microsoft.com/da-dk/library/bb397487(en-us).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/da-dk/library/bb397487(en-us).aspx</a>). The object is attached to a DOM element. Now I need to get a reference to the instance, but it is neither registered on window or on the DOM element, and I cannot find it anywhere.</p> <p>Does someone know how you can obtain a reference to the instance?</p> <p>Best regards,</p> <p>JacobE</p>
[ { "answer_id": 225948, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 1, "selected": false, "text": "Returns: A new instance of a component that uses the specified parameters.\n var instance = $create(someType);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30056/" ]
225,637
<p>I recently installed RailRoad gem to generate an .svg diagram of my app's models and controllers.</p> <p>The rake task keeps breaking with a similar error:</p> <pre><code>1.8/usr/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:263:in `load_missing_constant': uninitialized constant </code></pre> <p>I tried the rake task on 2 seperate apps and the error keeps appearing with a different "constant" name.</p> <p>Anyone using it with similar problems?</p>
[ { "answer_id": 2822679, "author": "Ivan", "author_id": 394133, "author_profile": "https://Stackoverflow.com/users/394133", "pm_score": 0, "selected": false, "text": "user@laptop:11:15 AM:rails_app> rake doc:diagrams\n(in /Users/ivan/Sites/lqas)\nrailroad -i -l -a -m -M | dot -Tsvg | sed 's/font-size:14.00/font-size:11.00/g' > doc/models.svg\nrailroad -i -l -C | neato -Tsvg | sed 's/font-size:14.00/font-size:11.00/g' > doc/controllers.svg\nError loading controller classes.\n (Are you running railroad on the aplication's root directory?)\n\n/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- app/controllers/application.rb (MissingSourceFile)\n from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'\n from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'\n from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'\n from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/lib/railroad/controllers_diagram.rb:39:in `load_classes'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/lib/railroad/app_diagram.rb:21:in `initialize'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/lib/railroad/controllers_diagram.rb:14:in `initialize'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/bin/railroad:38:in `new'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/bin/railroad:38\n from /usr/local/bin/railroad:19:in `load'\n from /usr/local/bin/railroad:19\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449483/" ]
225,654
<p>How do you add a page break into a document with XSL-FO? I'm using <a href="http://xmlgraphics.apache.org/fop/" rel="noreferrer">Apache FOP</a> to create PDFs, if that makes a difference.</p>
[ { "answer_id": 225691, "author": "Matthew Wilson", "author_id": 29429, "author_profile": "https://Stackoverflow.com/users/29429", "pm_score": 6, "selected": true, "text": "page-break-after page-break-before page-break-inside keep-together keep-with-next keep-with-previous" }, { "answer_id": 225803, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": 4, "selected": false, "text": "<fo:table break-after=\"page\">\n" }, { "answer_id": 7269723, "author": "cxm8002", "author_id": 893430, "author_profile": "https://Stackoverflow.com/users/893430", "pm_score": 5, "selected": false, "text": "<fo:block page-break-before=\"always\">\n ...things you want in a new page...\n</fo:block>\n" }, { "answer_id": 35364553, "author": "Suzan Balaa", "author_id": 1278870, "author_profile": "https://Stackoverflow.com/users/1278870", "pm_score": 1, "selected": false, "text": "<w:p ><w:r><w:br w:type=\"page\"/></w:r></w:p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
225,666
<p>I have a CompositeControl that contains a DropDownList.</p> <p>I have set the AutoPostBack property of the DropDownList to true.</p> <p>On the page, I have:</p> <pre><code>&lt;asp:UpdatePanel ID="UpdatePanel" runat="server"&gt; &lt;ContentTemplate&gt; &lt;MyControl:Control ID="CustomControl" runat="server" /&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p>I've also tried setting <strong>ChildrenAsTriggers="true"</strong> and <strong>UpdateMode="Always,"</strong> but neither resolved the problem.</p> <p>The problem is that the UpdatePanel is not intercepting the CompositeControl's DropDownList's post back. (A full POST is being performed when the DropDownList is changed)</p> <p>How can I get the UpdatePanel to handle the postback?</p> <p>Thanks!</p> <p><strong>Edit -- Requested Info</strong></p> <p>Country and states are both DropDownLists in the CompositeControl.</p> <pre><code>country.SelectedIndexChanged += new EventHandler(country_SelectedIndexChanged); protected void country_SelectedIndexChanged(Object sender, EventArgs e) { states.DataSource = XXX; states.DataBind(); } </code></pre>
[ { "answer_id": 225926, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 3, "selected": true, "text": "public partial class CatchMyEvent : System.Web.UI.UserControl\n{\n public delegate void ChangedIndex(object sender, EventArgs e);\n public event ChangedIndex SelectedIndexChanged;\n\n protected override void OnInit(EventArgs e)\n {\n base.OnInit(e);\n dropDownListThrow.SelectedIndexChanged += new EventHandler(dropDownListThrow_SelectedIndexChanged);\n labelOutput.Text = \"no\";\n }\n\n public void dropDownListThrow_SelectedIndexChanged(object sender, EventArgs e)\n {\n labelOutput.Text = ((DropDownList)sender).SelectedItem.Text;\n if(SelectedIndexChanged != null)\n {\n SelectedIndexChanged(sender, e);\n }\n }\n}\n <asp:AsyncPostBackTrigger ControlID=\"catchMyEventMain\" EventName=\"SelectedIndexChanged\" />\n protected override void OnInit(EventArgs e)\n{\n base.OnInit(e);\n catchMyEventMain.SelectedIndexChanged += dropDownListThrow_SelectedIndexChanged;\n}\n\npublic void dropDownListThrow_SelectedIndexChanged(object sender, EventArgs e)\n{ \n labelSelectedValue.Text = ((DropDownList)sender).SelectedItem.Text;\n}\n" }, { "answer_id": 349430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " ...\n if (DesignMode || Page == null) return;\n\n var sm = ScriptManager.GetCurrent(Page);\n if (sm == null)\n {\n throw new MissingFieldException(\"The ScriptManager is needed on the page!\");\n }\n sm.RegisterAsyncPostBackControl(<control which initiates async postback>);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8797/" ]
225,675
<p>I believe I'm getting bitten by some combination of nested scoping rules and list comprehensions. <a href="http://www.python.org/~jeremy/weblog/040204.html" rel="noreferrer">Jeremy Hylton's blog post</a> is suggestive about the causes, but I don't really understand CPython's implementation well-enough to figure out how to get around this. </p> <p>Here is an (overcomplicated?) example. If people have a simpler one that demos it, I'd like to hear it. The issue: the list comprehensions using next() are filled with the result from the last iteration. </p> <p><strong>edit</strong>: The Problem:</p> <p>What exactly is going on with this, and how do I fix this? Do I have to use a standard for loop? Clearly the function is running the correct number of times, but the list comprehensions end up with the <em>final</em> value instead of the result of each loop.</p> <p>Some hypotheses:</p> <ul> <li>generators?</li> <li>lazy filling of list comprehensions?</li> </ul> <p><strong>code</strong></p> <pre><code>import itertools def digit(n): digit_list = [ (x,False) for x in xrange(1,n+1)] digit_list[0] = (1,True) return itertools.cycle ( digit_list) </code></pre> <pre> >>> D = digit(5) >>> [D.next() for x in range(5)] ## This list comprehension works as expected [(1, True), (2, False), (3, False), (4, False), (5, False)] </pre> <pre><code>class counter(object): def __init__(self): self.counter = [ digit(4) for ii in range(2) ] self.totalcount=0 self.display = [0,] * 2 def next(self): self.totalcount += 1 self.display[-1] = self.counter[-1].next()[0] print self.totalcount, self.display return self.display def next2(self,*args): self._cycle(1) self.totalcount += 1 print self.totalcount, self.display return self.display def _cycle(self,digit): d,first = self.counter[digit].next() #print digit, d, first #print self._display self.display[digit] = d if first and digit &gt; 0: self._cycle(digit-1) C = counter() [C.next() for x in range(5)] [C.next2() for x in range(5)] </code></pre> <p><strong>OUTPUT</strong></p> <pre> In [44]: [C.next() for x in range(6)] 1 [0, 1] 2 [0, 2] 3 [0, 3] 4 [0, 4] 5 [0, 1] 6 [0, 2] Out[44]: [[0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2]] In [45]: [C.next2() for x in range(6)] 7 [0, 3] 8 [0, 4] 9 [1, 1] 10 [1, 2] 11 [1, 3] 12 [1, 4] Out[45]: [[1, 4], [1, 4], [1, 4], [1, 4], [1, 4], [1, 4]] # this should be: [[0,3],[0,4]....[1,4]] or similar </pre>
[ { "answer_id": 225801, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 5, "selected": true, "text": "return self.display >>> a = [1,2]\n>>> b = [a,a]\n>>> b\n[[1, 2], [1, 2]]\n>>> a.append(3)\n>>> b\n[[1, 2, 3], [1, 2, 3]]\n return self.display[:]" }, { "answer_id": 231613, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "def digit(n):\n for i in itertools.count():\n yield (i%n+1, not i%n)\n def counter(digits, base):\n counter = [0] * digits\n\n def iterator():\n for total in itertools.count(1):\n for i in range(len(counter)):\n counter[i] = (counter[i] + 1) % base\n if counter[i]:\n break\n print total, list(reversed(counter))\n yield list(reversed(counter))\n\n return iterator()\n\nc = counter(2, 4)\nprint list(itertools.islice(c, 10))\n reversed" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
225,686
<p>I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton?</p> <p>The interface I would like is something like:</p> <pre><code>var x = Foo.Instance; var y = Foo.Instance; // x == y ... x.Release(); // this causes the next Foo.Instance to return a fresh object // also, it assumes no further operations on x/y will be performed. </code></pre> <p>Note - the pattern has to be thread-safe, of course.</p> <p><strong>Edit</strong> - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.</p> <p>I would also prefer a pattern that can be reused, if possible.</p>
[ { "answer_id": 225747, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "public sealed class Singleton : IDisposable\n{\n Singleton()\n {\n }\n\n public static Singleton Instance\n {\n get\n {\n if (!Nested.released)\n return Nested.instance;\n else\n throw new ObjectDisposedException();\n }\n }\n\n public void Dispose()\n {\n disposed = true;\n // Do release stuff here\n }\n\n private bool disposed = false;\n\n class Nested\n {\n // Explicit static constructor to tell C# compiler\n // not to mark type as beforefieldinit\n static Nested()\n {\n }\n\n internal static readonly Singleton instance = new Singleton();\n }\n}\n" }, { "answer_id": 225761, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": " public class Foo : IDisposable\n { [ThreadStatic] static Foo _instance = null;\n\n private Foo() {IsReleased = false;}\n\n public static Foo Instance\n { get\n { if (_instance == null) _instance = new Foo();\n return _instance;\n }\n }\n\n public void Release()\n { IsReleased = true;\n Foo._instance = null;\n }\n\n void IDisposable.Dispose() { Release(); }\n\n public bool IsReleased { get; private set;}\n\n }\n" }, { "answer_id": 225850, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 5, "selected": true, "text": "Release internal InternalsVisibleTo private Dispose AppDomain Release" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
225,699
<p>Does anyone know if you can programmatically open a .webarchive on the iPhone? A .webarchive is Safari's way of packaging up a webpage and it's associated resources into a single file.</p> <p>I tried creating one and browsing to a link to one in mobile safari, but it didn't work....</p> <p>Note: I was kind of hoping this could be done without a 3rd party app, as it'd be a nice way to package up a WebApp for use on the iphone without needing a third party tool. </p>
[ { "answer_id": 4952387, "author": "Duck", "author_id": 316469, "author_profile": "https://Stackoverflow.com/users/316469", "pm_score": 5, "selected": true, "text": "NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@\"myFile\"\n withExtension:@\"webarchive\"];\n\n[webView loadRequest:[NSURLRequest requestWithURL:fileURL]];\n" }, { "answer_id": 6589723, "author": "Obliquely", "author_id": 531205, "author_profile": "https://Stackoverflow.com/users/531205", "pm_score": 2, "selected": false, "text": "#define WEB_ARCHIVE @\"Apple Web Archive pasteboard type\"\n\n- (NSString*) htmlStringFromPasteboard;\n{\n NSData* archiveData = [[UIPasteboard generalPasteboard] valueForPasteboardType:WEB_ARCHIVE];\n\n if (archiveData)\n {\n NSError* error = nil;\n id webArchive = [NSPropertyListSerialization propertyListWithData:archiveData options:NSPropertyListImmutable format:NULL error:&error];\n\n if (error)\n {\n return [NSString stringWithFormat:@\"Error: '%@'\", [error localizedDescription]];\n }\n NSDictionary* webMainResource = [webArchive objectForKey:@\"WebMainResource\"];\n NSData * webResourceData = [webMainResource objectForKey:@\"WebResourceData\"];\n\n NSString* string = [[NSString alloc] initWithData:webResourceData encoding:NSUTF8StringEncoding];\n\n return [string autorelease];\n }\n\n return @\"No WebArchive data on the pasteboard just now\";\n\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26510/" ]
225,711
<p>Any ideas how to stop the system bell from sounding when <kbd>CTRL</kbd>-<kbd>A</kbd> is used to select text in a Winforms application?</p> <p>Here's the problem. Create a Winforms project. Place a text box on the form and add the following event handler on the form to allow <kbd>CTRL</kbd>-<kbd>A</kbd> to select all the text in the textbox (no matter which control has the focus).</p> <pre><code>void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.A &amp;&amp; e.Modifiers == Keys.Control) { System.Diagnostics.Debug.WriteLine("Control and A were pressed."); txtContent.SelectionStart = 0; txtContent.SelectionLength = txtContent.Text.Length; txtContent.Focus(); e.Handled = true; } } </code></pre> <p>It works, but despite e.Handled = true, the system bell will sound every time <kbd>CTRL</kbd>-<kbd>A</kbd> is pressed.</p> <hr> <p>Thanks for the reply. </p> <p>KeyPreview on the Form is set to true - but that doesn't stop the system bell from sounding - which is the problem I'm trying to solve - annoying.</p>
[ { "answer_id": 230417, "author": "Blue Waters", "author_id": 30363, "author_profile": "https://Stackoverflow.com/users/30363", "pm_score": 3, "selected": false, "text": "protected override bool ProcessCmdKey(ref Message msg, Keys keyData) \n{\n if (keyData == (Keys.A | Keys.Control)) {\n txtContent.SelectionStart = 0;\n txtContent.SelectionLength = txtContent.Text.Length;\n txtContent.Focus();\n return true;\n }\n return base.ProcessCmdKey(ref msg, keyData);\n}\n" }, { "answer_id": 493151, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": " private void textBox1_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.Control && e.KeyCode == Keys.A)\n {\n this.textBox1.SelectAll();\n e.SuppressKeyPress = true;\n }\n }\n" }, { "answer_id": 19625057, "author": "Ivan Kochurkin", "author_id": 1046374, "author_profile": "https://Stackoverflow.com/users/1046374", "pm_score": 1, "selected": false, "text": "private void textBox_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.Control && e.KeyCode == Keys.A)\n {\n ((TextBox)sender).SelectAll();\n e.SuppressKeyPress = true;\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30363/" ]
225,717
<p>Given a FieldInfo object and an object, I need to get the actual bytes representation of the field. I know that the field is either <code>int,Int32,uint,short</code> etc.</p> <p>How can I get the actual byte representation? BinaryFormatter.Serialize won't help, since it'll give me more information than I need (it also records type name etc.). The <code>Marshal</code> class does not seem to have facilities to use bytes array (but maybe I'm missing something).</p> <p>Thanks</p>
[ { "answer_id": 225729, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "byte[] Bytes;\n\nif (valType == typeof(int))\n{\n int intVal = (int) GetFieldValue(....);\n Bytes = BitConverter.GetBytes(intVval);\n} \nelse if (valType == typeof(long))\n{\n int lngVal = (long) GetFieldValue(....);\n Bytes = BitConverter.GetBytes(lngVal);\n} else ....\n" }, { "answer_id": 225732, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Reflection;\n\npublic class Test\n{\n public int x = 300;\n\n static void Main()\n {\n Test instance = new Test();\n FieldInfo field = typeof(Test).GetField(\"x\");\n\n MethodInfo converter = typeof(BitConverter).GetMethod(\"GetBytes\", \n new Type[] {field.FieldType});\n\n if (converter == null)\n {\n Console.WriteLine(\"No BitConverter.GetBytes method found for type \"\n + field.FieldType); \n }\n else\n {\n byte[] bytes = (byte[]) converter.Invoke(null,\n new object[] {field.GetValue(instance) });\n Console.WriteLine(\"Byte array: {0}\", BitConverter.ToString(bytes));\n } \n }\n}\n" }, { "answer_id": 225771, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": true, "text": "int rawsize = Marshal.SizeOf(value);\nbyte[] rawdata = new byte[rawsize];\nGCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned);\nMarshal.StructureToPtr(value, handle.AddrOfPinnedObject(), false);\nhandle.Free();\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]\nbyte[] _state;\n public T GetValue<T>()\n{\n GCHandle handle = GCHandle.Alloc(RawValue, GCHandleType.Pinned);\n T structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), \n typeof(T));\n handle.Free();\n return structure;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
225,735
<p>Is there an easy way to rename a group of files already contained in a directory, using Python?</p> <p><strong>Example:</strong> I have a directory full of *.doc files and I want to rename them in a consistent way.</p> <blockquote> <p>X.doc -> "new(X).doc"</p> <p>Y.doc -> "new(Y).doc"</p> </blockquote>
[ { "answer_id": 227125, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 8, "selected": true, "text": "import glob, os\n\ndef rename(dir, pattern, titlePattern):\n for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):\n title, ext = os.path.splitext(os.path.basename(pathAndFilename))\n os.rename(pathAndFilename, \n os.path.join(dir, titlePattern % title + ext))\n rename(r'c:\\temp\\xx', r'*.doc', r'new(%s)')\n *.doc c:\\temp\\xx new(%s).doc %s" }, { "answer_id": 227209, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": false, "text": "import re, glob, os\n\ndef renamer(files, pattern, replacement):\n for pathname in glob.glob(files):\n basename= os.path.basename(pathname)\n new_filename= re.sub(pattern, replacement, basename)\n if new_filename != basename:\n os.rename(\n pathname,\n os.path.join(os.path.dirname(pathname), new_filename))\n renamer(\"*.doc\", r\"^(.*)\\.doc$\", r\"new(\\1).doc\")\n renamer(\"*.doc\", r\"^new\\((.*)\\)\\.doc\", r\"\\1.doc\")\n" }, { "answer_id": 7917798, "author": "Cesar Canassa", "author_id": 360829, "author_profile": "https://Stackoverflow.com/users/360829", "pm_score": 7, "selected": false, "text": "import os\n[os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]\n" }, { "answer_id": 10159893, "author": "harisibrahimkv", "author_id": 759163, "author_profile": "https://Stackoverflow.com/users/759163", "pm_score": 3, "selected": false, "text": "import os\nimport sys\n\n# checking whether path and filename are given.\nif len(sys.argv) != 3:\n print \"Usage : python rename.py <path> <new_name.extension>\"\n sys.exit()\n\n# splitting name and extension.\nname = sys.argv[2].split('.')\nif len(name) < 2:\n name.append('')\nelse:\n name[1] = \".%s\" %name[1]\n\n# to name starting from 1 to number_of_files.\ncount = 1\n\n# creating a new folder in which the renamed files will be stored.\ns = \"%s/pic_folder\" % sys.argv[1]\ntry:\n os.mkdir(s)\nexcept OSError:\n # if pic_folder is already present, use it.\n pass\n\ntry:\n for x in os.walk(sys.argv[1]):\n for y in x[2]:\n # creating the rename pattern.\n s = \"%spic_folder/%s%s%s\" %(x[0], name[0], count, name[1])\n # getting the original path of the file to be renamed.\n z = os.path.join(x[0],y)\n # renaming.\n os.rename(z, s)\n # incrementing the count.\n count = count + 1\nexcept OSError:\n pass\n" }, { "answer_id": 20371910, "author": "kiriloff", "author_id": 1141493, "author_profile": "https://Stackoverflow.com/users/1141493", "pm_score": 4, "selected": false, "text": "import os\n\ndef replace(fpath, old_str, new_str):\n for path, subdirs, files in os.walk(fpath):\n for name in files:\n if(old_str.lower() in name.lower()):\n os.rename(os.path.join(path,name), os.path.join(path,\n name.lower().replace(old_str,new_str)))\n" }, { "answer_id": 43704504, "author": "frank__aguirre", "author_id": 5314707, "author_profile": "https://Stackoverflow.com/users/5314707", "pm_score": 2, "selected": false, "text": "directoryName = \"Photographs\"\nfilePath = os.path.abspath(directoryName)\nfilePathWithSlash = filePath + \"\\\\\"\n\nfor counter, filename in enumerate(os.listdir(directoryName)):\n\n filenameWithPath = os.path.join(filePathWithSlash, filename)\n\n os.rename(filenameWithPath, filenameWithPath.replace(filename,\"DSC_\" + \\\n str(counter).zfill(4) + \".jpg\" ))\n\n# e.g. filename = \"photo1.jpg\", directory = \"c:\\users\\Photographs\" \n# The string.replace call swaps in the new filename into \n# the current filename within the filenameWitPath string. Which \n# is then used by os.rename to rename the file in place, using the \n# current (unmodified) filenameWithPath.\n\n# os.listdir delivers the filename(s) from the directory\n# however in attempting to \"rename\" the file using os \n# a specific location of the file to be renamed is required.\n\n# this code is from Windows \n" }, { "answer_id": 45734556, "author": "Jayhello", "author_id": 6329006, "author_profile": "https://Stackoverflow.com/users/6329006", "pm_score": 1, "selected": false, "text": "def batch_rename():\n base_dir = 'F:/ad_samples/test_samples/'\n sub_dir_list = glob.glob(base_dir + '*')\n # print sub_dir_list # like that ['F:/dir1', 'F:/dir2']\n for dir_item in sub_dir_list:\n files = glob.glob(dir_item + '/*.jpg')\n i = 0\n for f in files:\n os.rename(f, os.path.join(dir_item, str(i) + '.jpg'))\n i += 1\n" }, { "answer_id": 46819382, "author": "Amber Davis", "author_id": 8798132, "author_profile": "https://Stackoverflow.com/users/8798132", "pm_score": 2, "selected": false, "text": "folder = r\"R:\\mystuff\\GIS_Projects\\Website\\2017\\PDF\"\n\nimport os\n\n\nfor root, dirs, filenames in os.walk(folder):\n\n\nfor filename in filenames: \n fullpath = os.path.join(root, filename) \n filename_split = os.path.splitext(filename) # filename will be filename_split[0] and extension will be filename_split[1])\n print fullpath\n print filename_split[0]\n print filename_split[1]\n os.rename(os.path.join(root, filename), os.path.join(root, \"NewText_2017_\" + filename_split[0] + filename_split[1]))\n" }, { "answer_id": 49614494, "author": "Dan", "author_id": 5627860, "author_profile": "https://Stackoverflow.com/users/5627860", "pm_score": 1, "selected": false, "text": "# another regex version\n# usage example:\n# replacing an underscore in the filename with today's date\n# rename_files('..\\\\output', '(.*)(_)(.*\\.CSV)', '\\g<1>_20180402_\\g<3>')\ndef rename_files(path, pattern, replacement):\n for filename in os.listdir(path):\n if re.search(pattern, filename):\n new_filename = re.sub(pattern, replacement, filename)\n new_fullname = os.path.join(path, new_filename)\n old_fullname = os.path.join(path, filename)\n os.rename(old_fullname, new_fullname)\n print('Renamed: ' + old_fullname + ' to ' + new_fullname\n" }, { "answer_id": 52156458, "author": "Ajay Chandran", "author_id": 5117807, "author_profile": "https://Stackoverflow.com/users/5117807", "pm_score": 3, "selected": false, "text": "import os\n# get the file name list to nameList\nnameList = os.listdir() \n#loop through the name and rename\nfor fileName in nameList:\n rename=fileName[15:28]\n os.rename(fileName,rename)\n#example:\n#input fileName bulk like :20180707131932_IMG_4304.JPG\n#output renamed bulk like :IMG_4304.JPG\n" }, { "answer_id": 54103383, "author": "murthy annavajhula", "author_id": 9470985, "author_profile": "https://Stackoverflow.com/users/9470985", "pm_score": 0, "selected": false, "text": "import glob2\nimport os\n\n\ndef rename(f_path, new_name):\n filelist = glob2.glob(f_path + \"*.ma\")\n count = 0\n for file in filelist:\n print(\"File Count : \", count)\n filename = os.path.split(file)\n print(filename)\n new_filename = f_path + new_name + str(count + 1) + \".ma\"\n os.rename(f_path+filename[1], new_filename)\n print(new_filename)\n count = count + 1\n" }, { "answer_id": 57222273, "author": "Jim Shaddix", "author_id": 11842083, "author_profile": "https://Stackoverflow.com/users/11842083", "pm_score": 1, "selected": false, "text": "click.edit() import click\nfrom pathlib import Path\n\n# current directory\ndirec_to_refactor = Path(\".\")\n\n# list of old file paths\nold_paths = list(direc_to_refactor.iterdir())\n\n# list of old file names\nold_names = [str(p.name) for p in old_paths]\n\n# modify old file names in an editor,\n# and store them in a list of new file names\nnew_names = click.edit(\"\\n\".join(old_names)).split(\"\\n\")\n\n# refactor the old file names\nfor i in range(len(old_paths)):\n old_paths[i].replace(direc_to_refactor / new_names[i])\n" }, { "answer_id": 68989317, "author": "cappleby", "author_id": 16790441, "author_profile": "https://Stackoverflow.com/users/16790441", "pm_score": 0, "selected": false, "text": "import os\n[os.rename(f, f.replace(f[f.find('___'):], '')) for f in os.listdir('.') if not f.startswith('.')]\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11760/" ]
225,741
<p>Is there a way to set the StartPosition of a Windows Forms form using code? It seems whatever I try results in the StartPostion being the default.</p> <p>Here is what I am doing in the form to display:</p> <pre><code> public DealsForm() { InitializeComponent(); this.StartPosition = FormStartPosition.CenterParent; } </code></pre> <p>Here is what I am doing to display the form:</p> <pre><code> private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { DealsForm frm = new DealsForm(); frm.DataSource = this.Deals; frm.Show(this); } </code></pre> <p>I have tried putting the following in each of the above methods, to no avail:</p> <pre><code>this.StartPosition = FormStartPosition.CenterParent; </code></pre> <p>If I set it via the Property Editor ... it works perfectly, but I would <strong>really</strong> like to do it via code.</p> <p>Should be a no-brainer ... but for the life of me I can't seem to figure it out ... maybe I need more caffeine.</p> <h3>Update:</h3> <p>If I do a <code>ShowDialog()</code> and pass the parent it works ... but I really don't want to show it as a Dialog.</p>
[ { "answer_id": 225768, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 1, "selected": false, "text": "private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n{\n DealsForm frm = new DealsForm();\n\n frm.DataSource = this.Deals;\n\n // Insert this\n frm.StartPosition = FormStartPosition.CenterParent;\n\n frm.Show(this);\n}\n" }, { "answer_id": 225779, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 1, "selected": false, "text": "public DealsForm()\n{\n InitializeComponent();\n this.StartPosition = FormStartPosition.CenterParent; \n}\n public Form1()\n{\n InitializeComponent();\n this.StartPosition = FormStartPosition.CenterScreen;\n}\n private void button1_Click(object sender, EventArgs e)\n{\n Form1 f = new Form1();\n f.Show();\n}\n" }, { "answer_id": 225854, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 5, "selected": true, "text": "public DealsForm()\n{\n InitializeComponent();\n //this.StartPosition = FormStartPosition.CenterParent;\n}\n\n//DealsForm_Load Event\nprivate void DealsForm_Load(object sender, EventArgs e)\n{\n this.Location = this.Owner.Location; //NEW CODE\n}\n private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n{\n DealsForm frm = new DealsForm();\n\n frm.DataSource = this.Deals;\n frm.StartPosition = FormStartPosition.Manual; //NEW CODE\n frm.Show(this);\n}\n" }, { "answer_id": 10726903, "author": "Justin Pihony", "author_id": 779513, "author_profile": "https://Stackoverflow.com/users/779513", "pm_score": 3, "selected": false, "text": "childForm.Location = new Point(\n (parentForm.Location.X + parentForm.Width / 2) - (childForm.Width / 2), \n (parentForm.Location.Y + parentForm.Height / 2) - (childForm.Height / 2));\nchildForm.StartPosition = FormStartPosition.Manual;\n" }, { "answer_id": 17860375, "author": "Si Fitz", "author_id": 2619061, "author_profile": "https://Stackoverflow.com/users/2619061", "pm_score": 3, "selected": false, "text": "private void myForm_Load(object sender, EventArgs e)\n{\n CenterToParent();\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
225,764
<p>I'm trying to safely update the home directory as specified in <code>/etc/passwd</code>, but the standard Linux utils - usermod and vipw - for doing so aren't provided by Cygwin.</p> <p>Could anyone tell me how they changed this in Cygwin?</p>
[ { "answer_id": 226107, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 5, "selected": true, "text": "user:...:/cygdrive/c/Documents and Settings/user:/bin/bash\n :" }, { "answer_id": 327235, "author": "netjeff", "author_id": 41191, "author_profile": "https://Stackoverflow.com/users/41191", "pm_score": 7, "selected": false, "text": "mkpasswd mkpasswd $ mkpasswd -l -p \"$(cygpath -H)\" > /etc/passwd\n mkpasswd cygpath" }, { "answer_id": 361940, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "/cygdrive/c/DOCUME~1/user mkpasswd -l -p \"$(cygpath $(cygpath -dH))\" > /etc/passwd\n" }, { "answer_id": 6326095, "author": "Myer", "author_id": 78202, "author_profile": "https://Stackoverflow.com/users/78202", "pm_score": 2, "selected": false, "text": "echo off\nSETLOCAL\nset SHELL=\\\\bin\\\\bash\nset HOME=%~dp0..\\..\\doc\\unix\nbin\\bash --login -i\nENDLOCAL\n HOME=%~dp0..\\..\\doc\\unix PATH=\"/bin:/usr/local/bin:/usr/X11R6/bin:/usr/bin\" start /wait %CD%\\bin\\bash" }, { "answer_id": 10321615, "author": "M Smith", "author_id": 850252, "author_profile": "https://Stackoverflow.com/users/850252", "pm_score": 4, "selected": false, "text": "cd /\nmv home oldhome\nln -s \"$(cygpath -H)\" home\n cygpath -H /cygdrive/c/Users" }, { "answer_id": 10818934, "author": "wyrdR", "author_id": 1426350, "author_profile": "https://Stackoverflow.com/users/1426350", "pm_score": 2, "selected": false, "text": "reg add HKCU\\Environment /v HOME /t REG_EXPAND_SZ /d ^%USERPROFILE^%\n reg add HKU\\.DEFAULT\\Environment /v HOME /t REG_EXPAND_SZ /d ^%USERPROFILE^%\n Windows Registry Editor Version 5.00\n\n[HKEY_CURRENT_USER\\Environment]\n\"HOME\"=hex(2):25,00,55,00,53,00,45,00,52,00,50,00,52,00,4f,00,46,00,49,00,4c,\\\n 00,45,00,25,00,00,00\n Windows Registry Editor Version 5.00\n\n[HKU\\.DEFAULT\\Environment]\n\"HOME\"=hex(2):25,00,55,00,53,00,45,00,52,00,50,00,52,00,4f,00,46,00,49,00,4c,\\\n 00,45,00,25,00,00,00\n HKEY_CURRENT_USER\\Environment\n HKU\\.DEFAULT\\Environment\n" }, { "answer_id": 35451482, "author": "kitingChris", "author_id": 1260343, "author_profile": "https://Stackoverflow.com/users/1260343", "pm_score": 1, "selected": false, "text": "cd /home\nrm -rf chris\nln -s /cygdrive/z chris\n" }, { "answer_id": 40756931, "author": "Christopher", "author_id": 193617, "author_profile": "https://Stackoverflow.com/users/193617", "pm_score": 2, "selected": false, "text": "/etc/nsswitch.conf /etc/passwd /etc/group [[ -f /etc/passwd ]] && mv /etc/passwd /etc/passwd.bak\n[[ -f /etc/group ]] && mv /etc/group /etc/group.bak\n /etc/nsswitch.conf db_home: db_home: db_home: /home/%U\n /home/$USERNAME %u %U %D %H db_home: db_home: /%H/cygwin %_ %_ %% windows %USERPROFILE% C:\\Users\\$USERNAME cygwin unix desc db_home: windows\n /etc/passwd /etc/group HOME %USERPROFILE% /etc/passwd %HOME% ssh /etc/passwd $HOME cp /etc/passwd /etc/passwd.bak\nmkpasswd -l -p $(cygpath -H) > /etc/passwd \nmkpasswd -d -p $(cygpath -H) >> /etc/passwd \n -d -l /etc/group cp /etc/group /etc/group.bak\nmkgroup -l > /etc/group \nmkgroup -d >> /etc/group \n /cygdrive/c/Users/username" }, { "answer_id": 57097304, "author": "user123456789", "author_id": 5490686, "author_profile": "https://Stackoverflow.com/users/5490686", "pm_score": 0, "selected": false, "text": "C:\\Users\\username .bashrc .profile cd ${HOMEPATH}\n ~/. $HOMEPATH export HOME=${HOMEPATH}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
225,772
<p>I'm currently developing an application using a MySQL database.</p> <p>The database-structure is still in flux and changes while development progresses (I change my local copy, leaving the one on the test-server alone).</p> <p>Is there a way to compare the two instances of the database to see if there were any changes?</p> <p>While currently simply discarding the previous test server database is fine, as testing starts entering test data it could get a bit tricky.<br> The same though more so will happen again later in production...</p> <p>Is there an easy way to incrementally make changes to the production database, preferably by automatically creating a script to modify it? </p> <hr> <p>Tools mentioned in the answers:</p> <ul> <li><a href="https://www.red-gate.com/products/mysql/mysql-compare/" rel="nofollow noreferrer">Red-Gate's MySQL Schema &amp; Data Compare</a> (Commercial)</li> <li><a href="https://launchpad.net/percona-toolkit" rel="nofollow noreferrer">Maatkit (now Percona)</a></li> <li><a href="http://www.liquibase.org" rel="nofollow noreferrer">liquibase</a></li> <li><a href="http://www.quest.com/toad-for-mysql/" rel="nofollow noreferrer">Toad</a></li> <li><a href="http://nobhillsoft.com/NHDBCompare.aspx" rel="nofollow noreferrer">Nob Hill Database Compare</a> (Commercial)</li> <li><a href="http://adamspiers.org/computing/mysqldiff/" rel="nofollow noreferrer">MySQL Diff</a></li> <li><a href="http://www.sqledt.com" rel="nofollow noreferrer">SQL EDT</a> (Commercial)</li> </ul>
[ { "answer_id": 8718572, "author": "Jared", "author_id": 14744, "author_profile": "https://Stackoverflow.com/users/14744", "pm_score": 9, "selected": true, "text": "--skip-comments --skip-extended-insert --skip-extended-insert mysqldump --skip-comments --skip-extended-insert -u root -p dbName1>file1.sql\nmysqldump --skip-comments --skip-extended-insert -u root -p dbName2>file2.sql\ndiff file1.sql file2.sql\n" }, { "answer_id": 10285788, "author": "develCuy", "author_id": 2108644, "author_profile": "https://Stackoverflow.com/users/2108644", "pm_score": 4, "selected": false, "text": "#!/bin/sh\n\necho \"Usage: dbdiff [user1:pass1@dbname1] [user2:pass2@dbname2] [ignore_table1:ignore_table2...]\"\n\ndump () {\n up=${1%%@*}; user=${up%%:*}; pass=${up##*:}; dbname=${1##*@};\n mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname $table > $2\n}\n\nrm -f /tmp/db.diff\n\n# Compare\nup=${1%%@*}; user=${up%%:*}; pass=${up##*:}; dbname=${1##*@};\nfor table in `mysql -u $user -p$pass $dbname -N -e \"show tables\" --batch`; do\n if [ \"`echo $3 | grep $table`\" = \"\" ]; then\n echo \"Comparing '$table'...\"\n dump $1 /tmp/file1.sql\n dump $2 /tmp/file2.sql\n diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff\n else\n echo \"Ignored '$table'...\"\n fi\ndone\nless /tmp/db.diff\nrm -f /tmp/file1.sql /tmp/file2.sql\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27439/" ]
225,825
<p>I'm developing a piece in VB.NET. Inside my primary form, I'm creating a new form to use as a dialog. I was wondering if there was a way to, upon the close of the new dialog, save it's size settings for each user (probably in a file on their machine, through XML or something?)</p>
[ { "answer_id": 225925, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 4, "selected": true, "text": "Public Sub New()\n InitializeComponent()\nEnd Sub\n\nPublic Sub New(ByVal userSize As Size)\n InitializeComponent()\n Me.Size = userSize\nEnd Sub\n\nProtected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)\n MyBase.OnClosing(e)\n My.Settings.DialogSize = Me.Size\n My.Settings.Save()\nEnd Sub\n Dim dlg As MyDialogWindow\n If My.Settings.DialogSize.IsEmpty Then\n dlg = New MyDialogWindow()\n Else\n dlg = New MyDialogWindow(My.Settings.DialogSize)\n End If\n dlg.ShowDialog()\n" }, { "answer_id": 226950, "author": "Joe Morgan", "author_id": 13244, "author_profile": "https://Stackoverflow.com/users/13244", "pm_score": 0, "selected": false, "text": "System.IO.IsolatedStorage" }, { "answer_id": 12751376, "author": "Waleed El-Safty", "author_id": 1723762, "author_profile": "https://Stackoverflow.com/users/1723762", "pm_score": 2, "selected": false, "text": "system.drawing.size Private Sub myForm_FormClosing(ByVal sender As System.Object,\n ByVal e As System.Windows.Forms.FormClosingEventArgs) _\n Handles MyBase.FormClosing\n\n My.Settings.size = Me.Size\n My.Settings.Save()\n\nEnd Sub\n Private Sub myForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _\n Handles MyBase.Load\n ' if this is the first time to load the form \n ' dont set the size ( the form will load with the size in the designe)\n If Not My.Settings.size.IsEmpty Then\n Me.Size = My.Settings.size\n End If\nEnd Sub\n" }, { "answer_id": 60029846, "author": "Aaron", "author_id": 4451823, "author_profile": "https://Stackoverflow.com/users/4451823", "pm_score": 1, "selected": false, "text": "Private Sub LoadWindowPosition()\n\n 'Get window location/position from settings\n Dim ptLocation As System.Drawing.Point = My.Settings.WindowLocation\n\n 'Exit if it has not been set (X = Y = -1)\n If (ptLocation.X = -1) And (ptLocation.Y = -1) Then\n Return\n End If\n\n 'Verify the window position is visible on at least one of our screens\n Dim bLocationVisible As Boolean = False\n\n For Each S As Screen In Screen.AllScreens\n If S.Bounds.Contains(ptLocation) Then\n bLocationVisible = True\n Exit For\n End If\n Next\n\n 'Exit if window location is not visible on any screen \n If Not bLocationVisible Then\n Return\n End If\n\n 'Set Window Size, Location\n Me.StartPosition = FormStartPosition.Manual\n Me.Location = ptLocation\n Me.Size = My.Settings.WindowSize\nEnd Sub\n Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n LoadWindowPosition()\nEnd Sub\n\nPrivate Sub frmMain_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing\n My.Settings.WindowLocation = Me.Location\n My.Settings.WindowSize = Me.Size\nEnd Sub\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13244/" ]
225,828
<p>Since a lot of email clients ignore the HEAD tag, can I embed an inline stylesheet in the body?</p>
[ { "answer_id": 225855, "author": "teebot", "author_id": 24291, "author_profile": "https://Stackoverflow.com/users/24291", "pm_score": 1, "selected": false, "text": "margin padding <div style=\"\">" }, { "answer_id": 227830, "author": "Andy Ford", "author_id": 17252, "author_profile": "https://Stackoverflow.com/users/17252", "pm_score": 3, "selected": false, "text": "style" }, { "answer_id": 228157, "author": "Glen Lipka", "author_id": 29687, "author_profile": "https://Stackoverflow.com/users/29687", "pm_score": 3, "selected": false, "text": "style=\"\" <style>" }, { "answer_id": 73430973, "author": "Richard", "author_id": 492132, "author_profile": "https://Stackoverflow.com/users/492132", "pm_score": 0, "selected": false, "text": "<style> <head> <head>\n <style>\n div.mydiv { background-color: blue; }\n </style>\n</head>\n\n<body>\n <div class='mydiv'>This is the contents of my email message! Thank you \n google, for observing the style tag!</div>\n</body>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
225,830
<p>Im in the situation that I often send small codesnippets and xml-snippets to coworkers and partners via my outlook. Has anyone got a good idea or tool that I can use to have my pastes syntaxhighlighted before I paste them into an email.</p> <p>I was thinking of an intermediate paste to "$fancytool" and then I would have something to copy that will htmlified so I can copy paste it into the "compose email" window.</p> <p><em>Edit-More-info:</em></p> <p>Im pasting from windows within a VMWare virtual Machine, it might be eclipse, xmlspy, logfiles and other programs</p> <p><em>Even-more-info:</em></p> <p>I've seen <a href="http://vim.wikia.com/wiki/Pasting_code_with_syntax_coloring_in_emails" rel="noreferrer">this link</a> how to do it from Vim. Unfortunately it seldom from vim im copying Code, and my email machine hasnt got any vim. The vmware machines has gvim, but I was hoping for an easier way that pasting to vim, saving to file, opening in internetexplorer and then copy/paste</p>
[ { "answer_id": 2327441, "author": "ring bearer", "author_id": 212211, "author_profile": "https://Stackoverflow.com/users/212211", "pm_score": 4, "selected": true, "text": "Paste in to clipboard in RTF as well as plain text :set syn=xml" }, { "answer_id": 65968664, "author": "steffen", "author_id": 845034, "author_profile": "https://Stackoverflow.com/users/845034", "pm_score": 0, "selected": false, "text": "function! HlCopy() range\n exec a:firstline.','.a:lastline.'TOhtml'\n normal yG\n q!\n !start /min powershell \"Get-Clipboard | Set-Clipboard -AsHtml\"\n redraw\nendfun\nvmap Y :call HlCopy()<CR>\n :1,3call HlCopy() TOhtml function! HlCopy() range\n let g:html_font = \"Consolas\"\n let g:html_number_lines = 0\n exec a:firstline.','.a:lastline.'TOhtml'\n normal yG\n q!\n !start /min powershell \"Get-Clipboard | Set-Clipboard -AsHtml\"\n redraw\nendfun\nvmap Y :call HlCopy()<CR>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86/" ]
225,832
<p>Here's the deal. I have an XML document with a lot of records. Something like this:</p> <pre><code>print("&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Orders&gt; &lt;Order&gt; &lt;Phone&gt;1254&lt;/Phone&gt; &lt;City&gt;City1&lt;/City&gt; &lt;State&gt;State&lt;/State&gt; &lt;/Order&gt; &lt;Order&gt; &lt;Phone&gt;98764321&lt;/Phone&gt; &lt;City&gt;City2&lt;/City&gt; &lt;State&gt;State2&lt;/State&gt; &lt;/Order&gt; &lt;/Orders&gt;"); </code></pre> <p>There's also an XSD schema file. I would like to extract data from this file and insert these records into a database table. First of course I would like to validate each order record. For example if there are 5 orders in the file and 2 of them fail validation I would like to insert the 3 that passed validation into the db and left the other 2. There can be thousands of records in one xml file. What would be the best approach here. And how would the validation go for this since I need to discard the failed records and only use the ones that passed validation. At the moment I'm using <b>XmlReaderSettings</b> to validate the XML document records. Should I extract these records into another XML file or a Dataset or a custom object before I insert into a DB. I'm using .Net 3.5. Any code or link is welcome.</p>
[ { "answer_id": 899379, "author": "Richard Morgan", "author_id": 2258, "author_profile": "https://Stackoverflow.com/users/2258", "pm_score": 1, "selected": false, "text": " XDocument doc = XDocument.Load(\"sample.xml\");\n XmlSchemaSet schemas = new XmlSchemaSet();\n schemas.Add(\"\", \"sample.xsd\");\n\n bool errors = false;\n doc.Validate(schemas, (sender, e) =>\n {\n errors = true;\n });\n\n List<XElement> good = new List<XElement>();\n List<XElement> bad = new List<XElement>();\n var orders = doc.Descendants(\"Order\");\n if (errors)\n {\n foreach (var order in orders)\n {\n errors = false;\n order.Validate(order.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>\n {\n errors = true;\n });\n\n if (errors)\n bad.Add(order);\n else\n good.Add(order);\n }\n }\n else\n {\n good = orders.ToList();\n }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
225,833
<p>I have to add a coupon table to my db. There are 3 types of coupons : percentage, amount or 2 for 1.</p> <p>So far I've come up with a coupon table that contains these 3 fields. If there's a percentage value not set to null then it's this kind of coupon.</p> <p>I feel it's not the proper way to do it. Should I create a CouponType table and how would you see it? Where would you store these values?</p> <p>Any help or cue appreciated!</p> <p>Thanks,</p> <p>Teebot</p>
[ { "answer_id": 225862, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 3, "selected": true, "text": "- Table Coupons\n - ID\n - name\n - coupon_type_id # (or whatever fits your style guidelines)\n - amount # Example: 10.00 (treated as $10 off for amount type, treated as \n # 10% for percent type or 10 for 1 with the final type) \n - expiration_date\n\n- Table CouponTypes\n - ID\n - type # (amount, percent, <whatever you decided to call the 2 for 1> :))\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24291/" ]
225,843
<p>I have a menu div that I want to slide down so it's always visible, but I want it to be positioned under my title div. I don't want it to move until the top of the menu hits the top of the screen and then stay in place. Basically I want a sliding menu with a maximum height it can slide to.</p>
[ { "answer_id": 225935, "author": "jaacob", "author_id": 28109, "author_profile": "https://Stackoverflow.com/users/28109", "pm_score": 4, "selected": true, "text": "///// CONFIGURATION VARIABLES:\n\nvar name = \"#rightsidebar\";\nvar menu_top_limit = 241;\nvar menu_top_margin = 20;\nvar menu_shift_duration = 500;\nvar menuYloc = null;\n///////////////////////////////////\n\n$(window).scroll(function() \n{ \n // Calculate the top offset, adding a limit\n offset = menuYloc + $(document).scrollTop() + menu_top_margin;\n\n // Limit the offset to 241 pixels...\n // This keeps the menu out of our header area:\n if(offset < menu_top_limit)\n offset = menu_top_limit;\n\n // Give it the PX for pixels:\n offset += \"px\";\n\n // Animate:\n $(name).animate({top:offset},{duration:menu_shift_duration,queue:false});\n});\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30377/" ]
225,845
<p>I'm trying to get a kernel module to load at boot.</p> <p>If I run <code>insmod /path/to/module.ko</code>, it works fine. But this has to be repeated every time I reboot.</p> <p>If I run <code>modprobe /path/to/module.ko</code>, it can't find the module. I know modprobe uses a configuration file, but I can't get it to load the module even after adding /path/to/module.ko to /etc/modules.</p> <p>What is the proper configuration?</p>
[ { "answer_id": 225971, "author": "Jaime Soriano", "author_id": 28855, "author_profile": "https://Stackoverflow.com/users/28855", "pm_score": 7, "selected": true, "text": "sudo ln -s /path/to/module.ko /lib/modules/`uname -r`\nsudo depmod -a\nsudo modprobe module\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13652/" ]
225,878
<p>If I have a usercontrol (in Silverlight) that I've written, that uses XAML to define it's appearance, how can I make a customised version of it?</p> <p>i.e. I have MyControl.xaml &amp; MyControl.xaml.cs</p> <p>What do I need to do if I want a "SpecialisedControl" child class? I assume I just make a new code file, then inherit from MyControl. But what if I want to change the appearance of the base class - then what do I do?</p>
[ { "answer_id": 3110415, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": false, "text": "public class MyBase : UserControl\n{\n}\n\npublic class FirstUserControl : MyBase\n{\n...\n}\n <local:MyBase \n x:Class=\"FirstUserControl\" \n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:local=\"YourAssembly\" ...>\n\n <!-- Sticking with UserControl instead of local:MyBase makes this clearer -->\n <UserControl.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n ..\n </ResourceDictionary.MergedDictionaries>\n </ResourceDictionary>\n </UserControl.Resources>\n\n..Your XAML\n</local:MyBase>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
225,881
<p>Can anyone provide a clear explanation / example of what these functions do, and when it's appropriate to use them?</p>
[ { "answer_id": 225907, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 6, "selected": true, "text": "CREATE TABLE order_items (\n product_no integer REFERENCES products ON DELETE RESTRICT,\n order_id integer REFERENCES orders ON DELETE CASCADE,\n quantity integer,\n PRIMARY KEY (product_no, order_id)\n);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
225,889
<p>I am using Visual Assist X for C/C++ code in Visual Studio 2005 but I see that, sometime, when visual studio take focus, the processor is working too much and I cannot type code. If I am waiting somes seconds, it return the focus.</p>
[ { "answer_id": 226496, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 1, "selected": false, "text": "VAssistX C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\include" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11664/" ]
225,895
<p>I'm trying to track down an issue in our system and the following code worries me. The following occurs in our doPost() method in the primary servlet (names have been changed to protect the guilty):</p> <pre><code>... if(Single.getInstance().firstTime()){ doPreperations(); } normalResponse(); ... </code></pre> <p>The singleton 'Single' looks like this:</p> <pre><code>private static Single theInstance = new Single(); private Single() { ...load properties... } public static Single getInstance() { return theInstance; } </code></pre> <p>With the way this is set to use a static initializer instead of checking for a null theInstance in the getInstance() method, could this get rebuilt over and over again?</p> <p>PS - We're running WebSphere 6 with the App on Java 1.4</p>
[ { "answer_id": 225913, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 1, "selected": false, "text": "instance firstTime" }, { "answer_id": 225914, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": true, "text": "MySingleton firstTime()" }, { "answer_id": 225933, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "firstTime() doPreparations()" }, { "answer_id": 225998, "author": "nkr1pt", "author_id": 24046, "author_profile": "https://Stackoverflow.com/users/24046", "pm_score": 0, "selected": false, "text": "\npublic class Single {\n\nprivate static class SingleHolder {\n private static final Single INSTANCE = new Single();\n}\n\nprivate Single() {\n...load properties...\n}\n\npublic static Single getInstance() {\n return SingleHolder.INSTANCE;\n}\n\n}" }, { "answer_id": 227637, "author": "mjlee", "author_id": 2829, "author_profile": "https://Stackoverflow.com/users/2829", "pm_score": 3, "selected": false, "text": "public class Single\n{\n private static Single theInstance = new Single();\n\n private Single() \n { \n // load properties\n }\n\n public static Single getInstance() \n {\n return theInstance;\n }\n}\n public class Single\n{\n private static Single theInstance = new Single();\n\n private Single() \n { \n // load properties\n }\n\n public static Single getInstance() \n { \n // check for initialization of theInstance\n if ( theInstance.firstTime() )\n theInstance.doPreparation();\n\n return theInstance;\n }\n}\n public class Single\n{\n private static class SingleHolder\n {\n public static Single theInstance = new Single();\n }\n\n private Single() \n { \n // load properties\n doPreparation();\n }\n\n public static Single getInstance() \n {\n return SingleHolder.theInstance;\n }\n}\n public class A\n{\n final static String word = \"Hello World\";\n}\n public class B\n{\n public static void main(String[] args) {\n System.out.println(A.word);\n }\n}\n public class A\n{\n final static String word = \"Goodbye World\";\n}\n Hello World\n" }, { "answer_id": 990846, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private USDateFactory () { }\n\npublic static USDateFactory getUsdatefactory() {\n if(usdatefactory==null) {\n usdatefactory = new USDateFactory();\n }\n return usdatefactory;\n}\n\npublic String getTextDate (Date date) {\n return null;\n}\n\npublic NumericalDate getNumericalDate (Date date) {\n return null;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30381/" ]
225,915
<p>I have a case where I have a bunch of text boxes and radio buttons on a screen all built dynamically with various DIVs. There are onblur routines for all of the text boxes to validate entry, but depending on the radio button selection, the text box entry could be invalid when it was valid originally. I can't use onblur with the radio buttons because they could go from the radio button into one of the text boxes that was made invalid and create an infinite loop since I'm putting focus into the invalid element. Since each text box has its own special parameters for the onblur calls, I figure the best way to do this is to call the onblur event for the textboxes when the form gets submitted to make sure all entry is still valid with the radio button configuration they have selected. I also need it to stop submitting if one of the onblur events returns false so they can correct the textbox that is wrong. This is what I've written...</p> <pre><code> for (var intElement = 0; intElement &lt; document.forms[0].elements.length; intElement = intElement + 1) { if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount") // The first 3 characters of the name are a unique identifier for each field { if (document.forms[0].elements[intElement].onblur()) { return false; break; } } } return true; </code></pre> <p>I originally had (!document.forms[0].elements[intElement].onblur()) but the alert messages from the onblur events weren't popping up when I had that. Now the alert messages are popping up, but it's still continuing to loop through elements if it hits an error. I've stepped through this with a debugger both ways, and it appears to be looping just fine, but it's either 1) not stopping and returning false when I need it to or 2) not executing my alert messages to tell the user what the error was. Can someone possibly help? It's probably something stupid I'm doing.</p> <p>The onblur method that is getting called looks like this...</p> <pre><code>function f_VerifyRange(tagFactor, reaMin, reaMax, intPrecision, sLOB, sIL, sFactorCode) { var tagCreditOrDebit; var tagIsTotal; var tagPercentageOrDecimal; eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC"); eval("tagIsTotal = document.forms[0]." + tagFactor.name.substr(0,3) + "IsTotal"); eval("tagPercentageOrDecimal = document.forms[0]." + tagFactor.name.substr(0,3) + "PercentageOrDecimal"); if (tagPercentageOrDecimal.value == "P") { reaMax = Math.round((reaMax - 1) * 100); reaMin = Math.round((1 - reaMin) * 100); if (parseFloat(tagFactor.value) == 0) { alert("Please enter a value other than 0 or leave this field blank."); f_SetFocus(tagFactor); return false; } if (tagIsTotal.value == "True") { if (tagCreditOrDebit.checked) { if (parseFloat(tagFactor.value) &gt; reaMin) { alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit."); f_SetFocus(tagFactor); return false; } } else { if (parseFloat(tagFactor.value) &gt; reaMax) { alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit."); f_SetFocus(tagFactor); return false; } } } } return true; } </code></pre> <p><strong>EDIT:</strong> I think I've figured out why this isn't working as expected, but I still don't know how I can accomplish what I need to. The line below...</p> <pre><code> if (!document.forms[0].elements[intElement].onblur()) </code></pre> <p>or</p> <pre><code> if (document.forms[0].elements[intElement].onblur()) </code></pre> <p>is not returning what the single onblur function (f_VerifyRange) is returning. Instead it is always returning either true or false no matter what. In the first case, it returns true and then quits and aborts the submit after the first textbox even though there was no error with the first textbox. In the second case, it returns false and runs through all the boxes. Even though there might have been errors (which it displays), it doesn't think there are any errors, so it continues on with the submit. I guess what I really need is how to get the return value from f_VerifyRange which is my onblur function.</p>
[ { "answer_id": 226284, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "eval(\"tagCreditOrDebit = document.forms[0].\" + tagFactor.name.substr(0,3) + \"CreditOrDebitC\");\n tagCreditOrDebit = document.forms[0][tagFactor.name.substr(0,3) + \"CreditOrDebitC\"];\n document.body;\ndocument['body'];\nvar b = 'body';\ndocument[b];\n document.forms[0] // HTML\n<form name=\"myFormName\">\n\n// Javascript\nvar f = document.myFormName;\n <form id=\"myFormId\">\n\nvar f = document.getElementById(\"myFormId\")\n" }, { "answer_id": 227100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "g_bHardEditsPassed f_VerifyRange g_bHardEditsPassed g_bHardEditsPassed = true;\n\n for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)\n {\n if (document.forms[0].elements[intElement].name.substr(3) == \"FactorAmount\")\n {\n document.forms[0].elements[intElement].onblur()\n if (!g_bHardEditsPassed)\n {\n g_bHardEditsPassed = true;\n return false;\n }\n }\n }\n\n return true;\n" }, { "answer_id": 227893, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": 0, "selected": false, "text": "if (!...onblur()) onblur() undefined OnBlur()" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
225,916
<p>Following on from this question <a href="https://stackoverflow.com/questions/150814/how-to-handle-an-activex-event-in-javascript">here</a></p> <p>I have a custom ActiveX control which raises an event "BeforePageValidated" which has a parameter "args" which is an object which contains a boolean. The purpose of this is to allow the client to override the validation and force it fail by setting the boolean value to true.</p> <p>I can catch the event in IE using the following</p> <pre><code>&lt;script for="objInterviewNOW" event="BeforePageValidated(args)"&gt; </code></pre> <p>However I can't access the property of the args object.</p> <p>How should I be doing this?</p>
[ { "answer_id": 1291903, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "args [ComVisible(true)]\n[GuidAttribute(\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\")]\npublic class args\n{\n\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
225,929
<p>I can see people asking all the time whether multiple inheritance should be included into the next version of C# or Java. C++ folks, who are fortunate enough to have this ability, say that this is like giving someone a rope to eventually hang themselves. </p> <p>What’s the matter with multiple inheritance? Are there any concrete samples? </p>
[ { "answer_id": 226056, "author": "benjismith", "author_id": 22979, "author_profile": "https://Stackoverflow.com/users/22979", "pm_score": 8, "selected": true, "text": "A B doSomething C A B doSomething C c = new C();\nc.doSomething();\n class A:\n at offset 0 ... \"abc\" ... 4 byte int field\n at offset 4 ... \"xyz\" ... 8 byte double field\n at offset 12 ... \"speak\" ... 4 byte function pointer\n\nclass B:\n at offset 0 ... \"foo\" ... 2 byte short field\n at offset 2 ... 2 bytes of alignment padding\n at offset 4 ... \"bar\" ... 4 byte array pointer\n at offset 8 ... \"baz\" ... 4 byte function pointer\n C A B AB BA B B C B" }, { "answer_id": 3184459, "author": "Turing Complete", "author_id": 372920, "author_profile": "https://Stackoverflow.com/users/372920", "pm_score": 3, "selected": false, "text": "public sealed class CustomerEditView : Form, MVCView<Customer>\n" }, { "answer_id": 15883576, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "class X { public virtual void Foo() { Console.WriteLine(\"XFoo\"); }\nclass Y : X {};\nclass Z : X {};\nclass W : Y, Z // Not actually permitted in C#\n{\n public static void Test()\n {\n var it = new W();\n it.Foo();\n }\n}\n W.Test() Foo X class Y : X { public override void Foo() { Console.WriteLine(\"YFoo\"); }\nclass Z : X { public override void Foo() { Console.WriteLine(\"ZFoo\"); }\n W.Test() W.Test() W.Test()" }, { "answer_id": 37380038, "author": "number Zero", "author_id": 6368531, "author_profile": "https://Stackoverflow.com/users/6368531", "pm_score": 2, "selected": false, "text": " A A\n / \\ / \\\nB C D E\n \\ / \\ /\n F G\n \\ /\n H\n F G A A H F G A\n / \\\nB B\n| |\nC D\n \\ /\n E\n B E B A A* E B* B struct A { virtual ~A() {} /* so that the class is polymorphic */ };\nstruct B: virtual A {};\nstruct C: B {};\nstruct D: B {};\nstruct E: C, D {};\n\nint main() {\n E data;\n E *e = &data;\n A *a = dynamic_cast<A *>(e); // works, A is unambiguous\n// B *b = dynamic_cast<B *>(e); // doesn't compile\n B *b = dynamic_cast<B *>(a); // NULL: B is ambiguous\n std::cout << \"E: \" << e << std::endl;\n std::cout << \"A: \" << a << std::endl;\n std::cout << \"B: \" << b << std::endl;\n// the next casts work\n std::cout << \"A::C::B: \" << dynamic_cast<B *>(dynamic_cast<C *>(e)) << std::endl;\n std::cout << \"A::D::B: \" << dynamic_cast<B *>(dynamic_cast<D *>(e)) << std::endl;\n std::cout << \"A=>C=>B: \" << dynamic_cast<B *>(dynamic_cast<C *>(a)) << std::endl;\n std::cout << \"A=>D=>B: \" << dynamic_cast<B *>(dynamic_cast<D *>(a)) << std::endl;\n return 0;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22088/" ]
225,937
<p>There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other.</p> <p>First type:</p> <pre><code>List&lt;string&gt; someList = &lt;some way to init&gt; foreach(string s in someList) { &lt;process the string&gt; } </code></pre> <p>Other Way:</p> <pre><code>List&lt;string&gt; someList = &lt;some way to init&gt; someList.ForEach(delegate(string s) { &lt;process the string&gt; }); </code></pre> <p>I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...</p>
[ { "answer_id": 225952, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 4, "selected": false, "text": "someList.ForEach() foreach foreach" }, { "answer_id": 225957, "author": "Craig.Nicol", "author_id": 1404, "author_profile": "https://Stackoverflow.com/users/1404", "pm_score": 3, "selected": false, "text": "someList.ForEach(s => s.ToUpper())\n" }, { "answer_id": 226040, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "List.ForEach() foreach(item in list) List.ForEach List.ForEach foreach (item in list)" }, { "answer_id": 226082, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "for someList.ForEach(x => { if(x.RemoveMe) someList.Remove(x); }); \n foreach foreach(var item in someList)\n if(item.RemoveMe) someList.Remove(item);\n ForEach() foreach for" }, { "answer_id": 226094, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 4, "selected": false, "text": "public void ForEach(Action<T> action)\n{\n if (action == null)\n {\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);\n }\n for (int i = 0; i < this._size; i++)\n {\n action(this._items[i]);\n }\n}\n public bool MoveNext()\n{\n if (this.version != this.list._version)\n {\n ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);\n }\n if (this.index < this.list._size)\n {\n this.current = this.list._items[this.index];\n this.index++;\n return true;\n }\n this.index = this.list._size + 1;\n this.current = default(T);\n return false;\n}\n" }, { "answer_id": 226299, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 6, "selected": false, "text": "list.ForEach( delegate(item) { foo;}); foreach(item in list) {foo; }; list.ForEach() => }) foreach(item in list) break continue list.ForEach for list.ForEach for list.ForEach(delegate) foreach(item in list) for(int 1 = 0; i < count; i++) foreach foreach(item in list) list.Foreach() => ForEach() Where() Select() Any() All() Max()" }, { "answer_id": 226359, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 4, "selected": false, "text": " // A list of actions to execute later\n List<Action> actions = new List<Action>();\n\n // Numbers 0 to 9\n List<int> numbers = Enumerable.Range(0, 10).ToList();\n\n // Store an action that prints each number (WRONG!)\n foreach (int number in numbers)\n actions.Add(() => Console.WriteLine(number));\n\n // Run the actions, we actually print 10 copies of \"9\"\n foreach (Action action in actions)\n action();\n\n // So try again\n actions.Clear();\n\n // Store an action that prints each number (RIGHT!)\n numbers.ForEach(number =>\n actions.Add(() => Console.WriteLine(number)));\n\n // Run the actions\n foreach (Action action in actions)\n action();\n" }, { "answer_id": 23290957, "author": "Pablo Caballero", "author_id": 1784916, "author_profile": "https://Stackoverflow.com/users/1784916", "pm_score": 2, "selected": false, "text": "public static class MyExtension<T>\n {\n public static void MyForEach(this IEnumerable<T> collection, Action<T> action)\n {\n foreach (T item in collection)\n action.Invoke(item);\n }\n }\n delegate(string s) {\n <process the string>\n}\n private static void myFunction(string s, <other variables...>)\n{\n <process the string>\n}\n (s) => <process the string>\n" }, { "answer_id": 59277515, "author": "Stacy Dudovitz", "author_id": 1552452, "author_profile": "https://Stackoverflow.com/users/1552452", "pm_score": 4, "selected": false, "text": "foreach ForEach(x => { }) List<T> var names = new List<string>\n{\n \"Henry\",\n \"Shirley\",\n \"Ann\",\n \"Peter\",\n \"Nancy\"\n};\n foreach foreach (var name in names)\n{\n Console.WriteLine(name);\n}\n using (var enumerator = names.GetEnumerator())\n{\n\n}\n public List<T>.Enumerator GetEnumerator()\n{\n return new List<T>.Enumerator(this);\n}\n internal Enumerator(List<T> list)\n{\n this.list = list;\n this.index = 0;\n this.version = list._version;\n this.current = default (T);\n}\n\npublic bool MoveNext()\n{\n List<T> list = this.list;\n if (this.version != list._version || (uint) this.index >= (uint) list._size)\n return this.MoveNextRare();\n this.current = list._items[this.index];\n ++this.index;\n return true;\n}\n\nobject IEnumerator.Current\n{\n {\n if (this.index == 0 || this.index == this.list._size + 1)\n ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);\n return (object) this.Current;\n }\n}\n List<T> IList<T> IDisposable Dispose ForEach(x => { }) names.ForEach(name =>\n{\n\n});\n public void ForEach(Action<T> action)\n{\n if (action == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);\n int version = this._version;\n for (int index = 0; index < this._size && (version == this._version || !BinaryCompatibility.TargetsAtLeast_Desktop_V4_5); ++index)\n action(this._items[index]);\n if (version == this._version || !BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)\n return;\n ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);\n}\n for (int index = 0; index < this._size && ... ; ++index)\n action(this._items[index]); Dispose Dispose foreach Iterator<T> for (var i = 0; i < names.Count; i++)\n{\n Console.WriteLine(names[i]);\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450139/" ]
225,953
<p>Where can I find a list of all the C# Color constants and the associated R,G,B (Red, Green, Blue) values?</p> <p>e.g.</p> <p>Color.White == (255,255,255)</p> <p>Color.Black == (0,0,0)</p> <p>etc...</p>
[ { "answer_id": 225967, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "using System;\nusing System.Drawing;\nusing System.Reflection;\n\npublic class Test\n{\n static void Main()\n {\n var props = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static);\n foreach (PropertyInfo prop in props)\n {\n Color color = (Color) prop.GetValue(null, null);\n Console.WriteLine(\"Color.{0} = ({1}, {2}, {3})\", prop.Name,\n color.R, color.G, color.B);\n }\n }\n}\n using System;\nusing System.Drawing;\n\npublic class Test\n{\n static void Main()\n {\n foreach (KnownColor known in Enum.GetValues(typeof(KnownColor)))\n {\n Color color = Color.FromKnownColor(known);\n Console.WriteLine(\"Color.{0} = ({1}, {2}, {3})\", known,\n color.R, color.G, color.B);\n }\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
225,956
<p>My only problem is making them line up three-across and have equal spacing. Apparently, spans can not have width and divs (and spans with display:block) don't appear horizontally next to each other. Suggestions?</p> <p><code>&lt;div style='width:30%; text-align:center; float:left; clear:both;'&gt;</code> Is what I have now.</p>
[ { "answer_id": 225975, "author": "jmcd", "author_id": 2285, "author_profile": "https://Stackoverflow.com/users/2285", "pm_score": 7, "selected": true, "text": "float: left;" }, { "answer_id": 226005, "author": "Jeremy B.", "author_id": 28567, "author_profile": "https://Stackoverflow.com/users/28567", "pm_score": 2, "selected": false, "text": "<div style=\"float: left;\"></div>\n <div style=\"display: inline;\"></div>\n" }, { "answer_id": 226030, "author": "runeh", "author_id": 2906, "author_profile": "https://Stackoverflow.com/users/2906", "pm_score": 5, "selected": false, "text": ".floatybox {\n display: inline-block;\n width: 123px;\n}\n" }, { "answer_id": 226249, "author": "d1rk", "author_id": 30411, "author_profile": "https://Stackoverflow.com/users/30411", "pm_score": 0, "selected": false, "text": "display: block; float: left; width height" }, { "answer_id": 226261, "author": "Sam Murray-Sutton", "author_id": 2977, "author_profile": "https://Stackoverflow.com/users/2977", "pm_score": 4, "selected": false, "text": "<style>\n #whatever div {\n display: inline;\n margin: 0 1em 0 1em;\n width: 30%;\n}\n</style>\n\n<div id=\"whatever\">\n <div>content</div>\n <div>content</div>\n <div>content</div>\n</div>\n clear:both display:inline" }, { "answer_id": 226376, "author": "monkey do", "author_id": 29951, "author_profile": "https://Stackoverflow.com/users/29951", "pm_score": 2, "selected": false, "text": "<style>\nhtml, body {\n margin: 0;\n padding: 0;\n}\n\n.content {\n float: left;\n width: 30%;\n border:none;\n}\n\n.rightcontent {\n float: right;\n width: 30%;\n border:none\n}\n\n.hspacer {\n width:5%;\n float:left;\n}\n\n.clear {\n clear:both;\n}\n</style>\n\n<div class=\"content\">content</div>\n<div class=\"hspacer\">&nbsp;</div>\n<div class=\"content\">content</div>\n<div class=\"hspacer\">&nbsp;</div>\n<div class=\"rightcontent\">content</div>\n<div class=\"clear\"></div>\n" }, { "answer_id": 46955046, "author": "talevineto", "author_id": 8837784, "author_profile": "https://Stackoverflow.com/users/8837784", "pm_score": 2, "selected": false, "text": "<style>\n.all {\ndisplay: table;\n}\n.maincontent {\nfloat: left;\nwidth: 60%; \n}\n.sidebox { \nfloat: right;\nwidth: 30%; \n}\n<div class=\"all\">\n <div class=\"maincontent\">\n MainContent\n </div>\n <div class=\"sidebox\"> \n SideboxContent\n </div>\n</div>\n" }, { "answer_id": 46955258, "author": "talevineto", "author_id": 8837784, "author_profile": "https://Stackoverflow.com/users/8837784", "pm_score": 0, "selected": false, "text": " <!-- CSS -->\n<style rel=\"stylesheet\" type=\"text/css\">\n.all { display: table; }\n.menu { float: left; width: 30%; }\n.content { margin-left: 35%; }\n</style>\n\n<!-- HTML -->\n<div class=\"all\">\n<div class=\"menu\">Menu</div>\n<div class=\"content\">Content</div>\n</div>\n float: left; right; width" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
225,965
<p>I have a form which takes both the user details and an image uploaded by them. I want to write the data to a user table and an image table but i am pretty sure that it cannot be done with just two separate insert statements. Any help would be much appreciated.</p>
[ { "answer_id": 228699, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$rec = mysql_query(\"insert into userdet values(\"$id\",\"$username\",....)\");\nif($rec)\n mysql_query(\"insert into imag values(\"$id\",\"$imgname\",...)\");\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
225,972
<p>I've seen <a href="http://msdn.microsoft.com/en-us/library/7tas5c80.aspx" rel="nofollow noreferrer">How to: Host Controls in Windows Forms DataGridView Cells</a> which explains how to host a control for editing a cell in a DataGridView. But how can I host a control for displaying a cell?</p> <p>I need to display a file name and a button in the same cell. Our UI designer is a graphic designer not a programmer, so I have to match the code to what he's drawn, whether it's possible - or wise - or not. We're using VS2008 and writing in C# for .NET 3.5, if that makes a difference.</p> <p>UPDATE: The 'net suggests creating a custom DataGridViewCell which hosts a panel as a first step; anyone done that?</p>
[ { "answer_id": 486646, "author": "Shalom Craimer", "author_id": 54491, "author_profile": "https://Stackoverflow.com/users/54491", "pm_score": 2, "selected": false, "text": "DataGridViewCell DataGridViewTextBoxCell DataGridViewColumn DataGridViewTextBoxCell IDataGridViewEditingControl PanelDataGridViewCell MyPanelControl IDataGridViewEditingControl" }, { "answer_id": 15181258, "author": "Jeremy Thompson", "author_id": 495455, "author_profile": "https://Stackoverflow.com/users/495455", "pm_score": 2, "selected": false, "text": "private void Form_Load(object sender, EventArgs e)\n{\n DataTable dt = new DataTable();\n dt.Columns.Add(\"name\");\n for (int j = 0; j < 10; j++)\n {\n dt.Rows.Add(\"\");\n }\n this.dataGridView1.DataSource = dt;\n this.dataGridView1.Columns[0].Width = 200;\n\n /*\n * First method : Convert to an existed cell type such ComboBox cell,etc\n */\n\n DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell();\n ComboBoxCell.Items.AddRange(new string[] { \"aaa\",\"bbb\",\"ccc\" });\n this.dataGridView1[0, 0] = ComboBoxCell;\n this.dataGridView1[0, 0].Value = \"bbb\";\n\n DataGridViewTextBoxCell TextBoxCell = new DataGridViewTextBoxCell();\n this.dataGridView1[0, 1] = TextBoxCell;\n this.dataGridView1[0, 1].Value = \"some text\";\n\n DataGridViewCheckBoxCell CheckBoxCell = new DataGridViewCheckBoxCell();\n CheckBoxCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;\n this.dataGridView1[0, 2] = CheckBoxCell;\n this.dataGridView1[0, 2].Value = true;\n\n /*\n * Second method : Add control to the host in the cell\n */\n DateTimePicker dtp = new DateTimePicker();\n dtp.Value = DateTime.Now.AddDays(-10);\n //add DateTimePicker into the control collection of the DataGridView\n this.dataGridView1.Controls.Add(dtp);\n //set its location and size to fit the cell\n dtp.Location = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Location;\n dtp.Size = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Size;\n}\n" }, { "answer_id": 72250348, "author": "Patch", "author_id": 4879042, "author_profile": "https://Stackoverflow.com/users/4879042", "pm_score": 1, "selected": false, "text": "public class AddRemoveColumn : DataGridViewImageColumn\n{\n private AddRemove SelectionControl = null;\n private Bitmap SelectionControlImage = null;\n\n public AddRemoveColumn()\n {\n SelectionControl = new AddRemove();\n }\n\n #region Set Up Column\n protected override void OnDataGridViewChanged()\n {\n base.OnDataGridViewChanged();\n if (DataGridView != null)\n {\n Activate();\n }\n }\n\n private void Activate()\n {\n SelectionControl.LostFocus += SelectionControl_LostFocus;\n this.DataGridView.CellMouseEnter += DataGridView_CellMouseEnter;\n this.DataGridView.BackgroundColorChanged += DataGridView_BackgroundColorChanged;\n\n this.DataGridView.RowHeightChanged += DataGridView_RowHeightChanged;\n SelectionControl.OnAddClicked += AddClicked;\n SelectionControl.OnRemoveClicked += RemoveClicked;\n\n\n this.DataGridView.Controls.Add(SelectionControl);\n SelectionControl.Visible = false;\n\n this.Width = SelectionControl.Width;\n SelectionControl.BackColor = this.DataGridView.BackgroundColor;\n \n this.DataGridView.RowTemplate.Height = SelectionControl.Height +1;\n\n foreach (DataGridViewRow row in DataGridView.Rows)\n {\n row.Height = SelectionControl.Height+1;\n }\n\n SetNullImage();\n }\n #endregion\n\n private void AddClicked(int RowIndex)\n {\n MessageBox.Show(\"Add clicked on index=\" + RowIndex.ToString());\n }\n\n private void RemoveClicked(int RowIndex)\n {\n MessageBox.Show(\"Removed clicked on index=\" + RowIndex.ToString());\n }\n\n private void SetNullImage()\n {\n if (SelectionControlImage != null)\n {\n\n SelectionControlImage.Dispose();\n }\n \n SelectionControlImage = new Bitmap(SelectionControl.Width, SelectionControl.Height);\n\n SelectionControl.DrawToBitmap(SelectionControlImage, new Rectangle(0, 0, SelectionControlImage.Width, SelectionControlImage.Height));\n\n this.DefaultCellStyle.NullValue = SelectionControlImage;\n }\n\n private void DataGridView_RowHeightChanged(object sender, DataGridViewRowEventArgs e)\n {\n if (e.Row.Height <= 40)\n {\n e.Row.Height = 40;\n }\n\n SelectionControl.Visible = false;\n SetPosition(Index, e.Row.Index);\n }\n\n private void DataGridView_BackgroundColorChanged(object sender, EventArgs e)\n {\n SelectionControl.BackColor = this.DataGridView.BackgroundColor;\n\n\n SetNullImage();\n\n }\n\n private void SelectionControl_LostFocus(object sender, EventArgs e)\n {\n SelectionControl.Visible = false;\n }\n\n private void SetPosition(int ColumnIndex, int RowIndex)\n {\n Rectangle celrec = this.DataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, true);//.Rows[e.RowIndex].Cells[e.ColumnIndex].GetContentBounds();\n\n int x_Offet = (celrec.Width - SelectionControl.Width)/ 2;\n int y_Offet = (celrec.Height - SelectionControl.Height)/2;\n\n SelectionControl.Location = new Point(celrec.X + x_Offet, celrec.Y + y_Offet);\n SelectionControl.Visible = true;\n SelectionControl.RowIndex = RowIndex;\n }\n\n private void DataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e)\n {\n if (e.ColumnIndex == this.Index)\n {\n SetPosition(e.ColumnIndex, e.RowIndex);\n }\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
225,984
<p>I have a partial that renders a select box using the following method:</p> <pre><code>&lt;%= collection_select 'type', 'id', @types, "id", "name", {:prompt =&gt; true}, {:onchange =&gt; remote_function( :loading =&gt; "Form.Element.disable('go_button')", :url =&gt; '/sfc/criteria/services', :with =&gt; "'type_id=' + encodeURIComponent(value) + '&amp;use_wizard=#{use_wizard}'"), :class =&gt; "hosp_select_buttons" } %&gt; </code></pre> <p>This partial gets used 2 times on every page, but at one point I need to get the value of the first select box. Using:</p> <pre><code>$('type_id') </code></pre> <p>returns the second select box. Is there a way to find the first one easily? Should I fix this using javascript or by redoing my partial?</p> <p>Note: the dropdowns do get rendered in separate forms.</p>
[ { "answer_id": 486646, "author": "Shalom Craimer", "author_id": 54491, "author_profile": "https://Stackoverflow.com/users/54491", "pm_score": 2, "selected": false, "text": "DataGridViewCell DataGridViewTextBoxCell DataGridViewColumn DataGridViewTextBoxCell IDataGridViewEditingControl PanelDataGridViewCell MyPanelControl IDataGridViewEditingControl" }, { "answer_id": 15181258, "author": "Jeremy Thompson", "author_id": 495455, "author_profile": "https://Stackoverflow.com/users/495455", "pm_score": 2, "selected": false, "text": "private void Form_Load(object sender, EventArgs e)\n{\n DataTable dt = new DataTable();\n dt.Columns.Add(\"name\");\n for (int j = 0; j < 10; j++)\n {\n dt.Rows.Add(\"\");\n }\n this.dataGridView1.DataSource = dt;\n this.dataGridView1.Columns[0].Width = 200;\n\n /*\n * First method : Convert to an existed cell type such ComboBox cell,etc\n */\n\n DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell();\n ComboBoxCell.Items.AddRange(new string[] { \"aaa\",\"bbb\",\"ccc\" });\n this.dataGridView1[0, 0] = ComboBoxCell;\n this.dataGridView1[0, 0].Value = \"bbb\";\n\n DataGridViewTextBoxCell TextBoxCell = new DataGridViewTextBoxCell();\n this.dataGridView1[0, 1] = TextBoxCell;\n this.dataGridView1[0, 1].Value = \"some text\";\n\n DataGridViewCheckBoxCell CheckBoxCell = new DataGridViewCheckBoxCell();\n CheckBoxCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;\n this.dataGridView1[0, 2] = CheckBoxCell;\n this.dataGridView1[0, 2].Value = true;\n\n /*\n * Second method : Add control to the host in the cell\n */\n DateTimePicker dtp = new DateTimePicker();\n dtp.Value = DateTime.Now.AddDays(-10);\n //add DateTimePicker into the control collection of the DataGridView\n this.dataGridView1.Controls.Add(dtp);\n //set its location and size to fit the cell\n dtp.Location = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Location;\n dtp.Size = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Size;\n}\n" }, { "answer_id": 72250348, "author": "Patch", "author_id": 4879042, "author_profile": "https://Stackoverflow.com/users/4879042", "pm_score": 1, "selected": false, "text": "public class AddRemoveColumn : DataGridViewImageColumn\n{\n private AddRemove SelectionControl = null;\n private Bitmap SelectionControlImage = null;\n\n public AddRemoveColumn()\n {\n SelectionControl = new AddRemove();\n }\n\n #region Set Up Column\n protected override void OnDataGridViewChanged()\n {\n base.OnDataGridViewChanged();\n if (DataGridView != null)\n {\n Activate();\n }\n }\n\n private void Activate()\n {\n SelectionControl.LostFocus += SelectionControl_LostFocus;\n this.DataGridView.CellMouseEnter += DataGridView_CellMouseEnter;\n this.DataGridView.BackgroundColorChanged += DataGridView_BackgroundColorChanged;\n\n this.DataGridView.RowHeightChanged += DataGridView_RowHeightChanged;\n SelectionControl.OnAddClicked += AddClicked;\n SelectionControl.OnRemoveClicked += RemoveClicked;\n\n\n this.DataGridView.Controls.Add(SelectionControl);\n SelectionControl.Visible = false;\n\n this.Width = SelectionControl.Width;\n SelectionControl.BackColor = this.DataGridView.BackgroundColor;\n \n this.DataGridView.RowTemplate.Height = SelectionControl.Height +1;\n\n foreach (DataGridViewRow row in DataGridView.Rows)\n {\n row.Height = SelectionControl.Height+1;\n }\n\n SetNullImage();\n }\n #endregion\n\n private void AddClicked(int RowIndex)\n {\n MessageBox.Show(\"Add clicked on index=\" + RowIndex.ToString());\n }\n\n private void RemoveClicked(int RowIndex)\n {\n MessageBox.Show(\"Removed clicked on index=\" + RowIndex.ToString());\n }\n\n private void SetNullImage()\n {\n if (SelectionControlImage != null)\n {\n\n SelectionControlImage.Dispose();\n }\n \n SelectionControlImage = new Bitmap(SelectionControl.Width, SelectionControl.Height);\n\n SelectionControl.DrawToBitmap(SelectionControlImage, new Rectangle(0, 0, SelectionControlImage.Width, SelectionControlImage.Height));\n\n this.DefaultCellStyle.NullValue = SelectionControlImage;\n }\n\n private void DataGridView_RowHeightChanged(object sender, DataGridViewRowEventArgs e)\n {\n if (e.Row.Height <= 40)\n {\n e.Row.Height = 40;\n }\n\n SelectionControl.Visible = false;\n SetPosition(Index, e.Row.Index);\n }\n\n private void DataGridView_BackgroundColorChanged(object sender, EventArgs e)\n {\n SelectionControl.BackColor = this.DataGridView.BackgroundColor;\n\n\n SetNullImage();\n\n }\n\n private void SelectionControl_LostFocus(object sender, EventArgs e)\n {\n SelectionControl.Visible = false;\n }\n\n private void SetPosition(int ColumnIndex, int RowIndex)\n {\n Rectangle celrec = this.DataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, true);//.Rows[e.RowIndex].Cells[e.ColumnIndex].GetContentBounds();\n\n int x_Offet = (celrec.Width - SelectionControl.Width)/ 2;\n int y_Offet = (celrec.Height - SelectionControl.Height)/2;\n\n SelectionControl.Location = new Point(celrec.X + x_Offet, celrec.Y + y_Offet);\n SelectionControl.Visible = true;\n SelectionControl.RowIndex = RowIndex;\n }\n\n private void DataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e)\n {\n if (e.ColumnIndex == this.Index)\n {\n SetPosition(e.ColumnIndex, e.RowIndex);\n }\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
226,002
<p>Have you ever tried this before?</p> <pre><code>static void Main(string[] args) { int x = 10; x = x++; Console.WriteLine(x); } </code></pre> <p>Output: 10.</p> <p>but for </p> <pre><code>static void Main(string[] args) { int x = 10; x++; Console.WriteLine(x); } </code></pre> <p>Output: 11.</p> <p>Could anyone explain why this?</p>
[ { "answer_id": 226008, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "static void Main(string[] args)\n{\n int x = 10;\n x = x++;\n Console.WriteLine(x);\n}\n static int plusplus(ref int x)\n{\n int xOld = x;\n x++;\n return xOld;\n}\n\nstatic void Main(string[] args)\n{\n int x = 10;\n x = plusplus(x);\n Console.WriteLine(x);\n}\n static void Main(string[] args)\n{\n int x = 10;\n x = ++x;\n Console.WriteLine(x);\n}\n" }, { "answer_id": 226019, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "x = x++ x x x var tmp = x;\nx++;\nx = tmp;\n x = x++" }, { "answer_id": 226024, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 4, "selected": false, "text": "x = 10\nx = ++x \n x" }, { "answer_id": 226033, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "x++;\n int returnValue = x;\nx = x+1;\nreturn returnValue;\n" }, { "answer_id": 226036, "author": "Sundar R", "author_id": 8127, "author_profile": "https://Stackoverflow.com/users/8127", "pm_score": -1, "selected": false, "text": "x = x++;\n" }, { "answer_id": 226301, "author": "Juan Pablo Califano", "author_id": 24170, "author_profile": "https://Stackoverflow.com/users/24170", "pm_score": 2, "selected": false, "text": "int x = 10;\n x = x++;\n 1) increment the value contained in x \n now x contains 11\n\n2) return the value that was contained in x before it was incremented\n that is 10\n\n3) assign that value to x\n now, x contains 10\n Console.WriteLine(x);\n" }, { "answer_id": 4896976, "author": "Max ", "author_id": 602981, "author_profile": "https://Stackoverflow.com/users/602981", "pm_score": 1, "selected": false, "text": " int x = 10;\n x++; //x still is 10\n Console.WriteLine(x); //x is now 11(post increment)\n" }, { "answer_id": 39062137, "author": "vitaliy4us", "author_id": 5740380, "author_profile": "https://Stackoverflow.com/users/5740380", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) {\n int x = 10;\n int y = 0;\n y = x + x++; //1, 2, 3, 4\n x += x; //5\n System.out.println(\"x = \" + x + \"; y = \" + y); //6\n}\n public static void main(String[] args) {\n int x = 10;\n x = x++; //1, 2, 3, 4\n System.out.println(x); //5\n}\n" }, { "answer_id": 47232964, "author": "galois", "author_id": 2005732, "author_profile": "https://Stackoverflow.com/users/2005732", "pm_score": 1, "selected": false, "text": "int main(){\n int x = 0;\n while (x<1)\n x = x++;\n}\n ...\n mov -8(rbp), 0 ; x = 0\nL1:\n cmp -8(rbp), 1 ; if x >= 1,\n jge L2 ; leave the loop\n mov eax, -8(rbp) ; t1 = x\n mov ecx, eax ; t2 = t1\n add ecx, 1 ; t2 = t2 + 1\n mov -8(rbp), ecx ; x = t2 (so x = x + 1 !)\n mov -8(rbp), eax ; x = t1 (kidding, it's the original value again)\n jmp L1\nL2:\n...\n t = x\nx = x + 1\nx = t\n ...\nL1:\n jmp L1\n...\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14118/" ]
226,042
<p>As part of our build process we run a database update script as we deploy code to 4 different environments. Further, since the same query will get added to until we drop a release into production it <em>has</em> to be able to run multiple times on a given database. Like this:</p> <pre><code>IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[Table]')) BEGIN CREATE TABLE [Table] (...) END </code></pre> <p>Currently I have a create schema statement in the deployment/build script. Where do I query for the existence of a schema?</p>
[ { "answer_id": 226054, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 9, "selected": true, "text": "IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'jim')\nBEGIN\nEXEC('CREATE SCHEMA jim')\nEND\n CREATE SCHEMA" }, { "answer_id": 521271, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 7, "selected": false, "text": "CREATE SCHEMA <name> CREATE SCHEMA IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = '<name>')\nBEGIN\n -- The schema must be run in its own batch!\n EXEC( 'CREATE SCHEMA <name>' );\nEND\n" }, { "answer_id": 44707980, "author": "Tom", "author_id": 401246, "author_profile": "https://Stackoverflow.com/users/401246", "pm_score": 1, "selected": false, "text": "Schema Count Throw Try Catch Throw declare @HasSchemaX bit\nset @HasSchemaX = case (select count(1) from sys.schemas where lower(name) = lower('SchemaX')) when 1 then 1 when 0 then 0 else 'ERROR' end\n declare @HasSchemaX bit = case (select count(1) from sys.schemas where lower(name) = lower('SchemaX')) when 1 then 1 when 0 then 0 else 'ERROR' end\n if @HasSchemaX = 1\nbegin\n ...\nend -- if @HasSchemaX = 1\n" }, { "answer_id": 55190129, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 3, "selected": false, "text": "EXECUTE('CREATE SCHEMA <name>') DECLARE @schemaName sysname = 'myfunschema';\n-- shortest\nIf EXISTS (SELECT 1 WHERE SCHEMA_ID(@schemaName) IS NOT NULL)\nPRINT 'YEA'\nELSE\nPRINT 'NOPE'\n\nSELECT DB_NAME() AS dbname WHERE SCHEMA_ID(@schemaName) IS NOT NULL -- nothing returned if not there\n\nIF NOT EXISTS ( SELECT top 1 *\n FROM sys.schemas\n WHERE name = @schemaName )\nPRINT 'WOOPS MISSING'\nELSE\nPRINT 'Has Schema'\n\nSELECT SCHEMA_NAME(SCHEMA_ID(@schemaName)) AS SchemaName1 -- null if not there otherwise schema name returned\n\nSELECT SCHEMA_ID(@schemaName) AS SchemaID1-- null if not there otherwise schema id returned\n\n\nIF EXISTS (\n SELECT sd.SchemaExists \n FROM (\n SELECT \n CASE \n WHEN SCHEMA_ID(@schemaName) IS NULL THEN 0\n WHEN SCHEMA_ID(@schemaName) IS NOT NULL THEN 1\n ELSE 0 \n END AS SchemaExists\n ) AS sd\n WHERE sd.SchemaExists = 1\n)\nBEGIN\n SELECT 'Got it';\nEND\nELSE\nBEGIN\n SELECT 'Schema Missing';\nEND\n" }, { "answer_id": 72300881, "author": "Mohammad Sadeq Sirjani", "author_id": 11507996, "author_profile": "https://Stackoverflow.com/users/11507996", "pm_score": 0, "selected": false, "text": "IF NOT EXISTS (SELECT TOP (1) 1 FROM [sys].[schemas] WHERE [name] = 'Person')\nBEGIN\n EXEC ('CREATE SCHEMA [Person]')\nEND\n\nIF NOT EXISTS (SELECT TOP (1) 1 FROM [sys].[tables] AS T\n INNER JOIN [sys].[schemas] AS S ON S.schema_id = T.schema_id\n WHERE T.[name] = 'Guests' AND S.[name] = 'Person')\nBEGIN\n EXEC ('CREATE TABLE [Person].[Guests]\n (\n [GuestId] INT IDENTITY(1, 1) NOT NULL,\n [Forename] NVARCHAR(100) NOT NULL,\n [Surname] NVARCHAR(100) NOT NULL,\n [Email] VARCHAR(255) NOT NULL,\n [BirthDate] DATETIME2 NULL,\n CONSTRAINT [PK_Guests_GuestId] PRIMARY KEY CLUSTERED ([GuestId]),\n CONSTRAINT [UX_Guests_Email] UNIQUE([Email])\n )')\nEND\n CREATE SCHEMA CREATE TABLE" }, { "answer_id": 72974092, "author": "David Sopko", "author_id": 1197553, "author_profile": "https://Stackoverflow.com/users/1197553", "pm_score": 0, "selected": false, "text": "IF NOT EXISTS (\nSELECT SCHEMA_NAME\nFROM INFORMATION_SCHEMA.SCHEMATA\nWHERE SCHEMA_NAME = '<schema name>' )\n \nBEGIN\n EXEC sp_executesql N'CREATE SCHEMA <schema name>' \nEND\nGO\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156/" ]
226,050
<p>I am trying to use <code>ResourceBundle#getStringArray</code> to retrieve a <code>String[]</code> from a properties file. The description of this method in the documentation reads:</p> <blockquote> <p>Gets a string array for the given key from this resource bundle or one of its parents.</p> </blockquote> <p>However, I have attempted to store the values in the properties file as multiple individual key/value pairs:</p> <pre><code>key=value1 key=value2 key=value3 </code></pre> <p>and as a comma-delimited list:</p> <pre><code>key=value1,value2,value3 </code></pre> <p>but neither of these is retrievable using <code>ResourceBundle#getStringArray</code>.</p> <p>How do you represent a set of key/value pairs in a properties file such that they can be retrieved using <code>ResourceBundle#getStringArray</code>?</p>
[ { "answer_id": 226160, "author": "Robert J. Walker", "author_id": 4287, "author_profile": "https://Stackoverflow.com/users/4287", "pm_score": 6, "selected": true, "text": "Properties Object String String bundle.getStringArray(key) (String[]) bundle.getObject(key) String[] String split()" }, { "answer_id": 229338, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public String[] getPropertyStringArray(PropertyResourceBundle bundle, String keyPrefix) {\n String[] result;\n Enumeration<String> keys = bundle.getKeys();\n ArrayList<String> temp = new ArrayList<String>();\n\n for (Enumeration<String> e = keys; keys.hasMoreElements();) {\n String key = e.nextElement();\n if (key.startsWith(keyPrefix)) {\n temp.add(key);\n }\n }\n result = new String[temp.size()];\n\n for (int i = 0; i < temp.size(); i++) {\n result[i] = bundle.getString(temp.get(i));\n }\n\n return result;\n}\n" }, { "answer_id": 1291284, "author": "João Silva", "author_id": 140816, "author_profile": "https://Stackoverflow.com/users/140816", "pm_score": 3, "selected": false, "text": "getList getStringArray" }, { "answer_id": 14691389, "author": "Murlo", "author_id": 2040338, "author_profile": "https://Stackoverflow.com/users/2040338", "pm_score": 1, "selected": false, "text": "mail.ccEmailAddresses=he@anyserver.at, she@anotherserver.at\n myBundle=PropertyResourceBundle.getBundle(\"mailTemplates/bundle-name\", _locale);\n public List<String> getCcEmailAddresses() \n{\n List<String> ccEmailAddresses=new ArrayList<String>();\n if(this.myBundle.containsKey(\"mail.ccEmailAddresses\"))\n {\n ccEmailAddresses.addAll(Arrays.asList(this.template.getString(\"mail.ccEmailAddresses\").split(\"\\\\s*(,|\\\\s)\\\\s*\")));// 1)Zero or more whitespaces (\\\\s*) 2) comma, or whitespace (,|\\\\s) 3) Zero or more whitespaces (\\\\s*)\n } \n return ccEmailAddresses;\n}\n" }, { "answer_id": 27667910, "author": "Lokesh Garg", "author_id": 3991465, "author_profile": "https://Stackoverflow.com/users/3991465", "pm_score": 1, "selected": false, "text": "@Override\nprotected Object[][] getContents() {\n // TODO Auto-generated method stub\n\n String[] str1 = {\"L1\",\"L2\"};\n\n return new Object[][]{\n\n {\"name\",str1},\n {\"country\",\"UK\"} \n };\n}\n" }, { "answer_id": 29901682, "author": "chrismarx", "author_id": 228369, "author_profile": "https://Stackoverflow.com/users/228369", "pm_score": 1, "selected": false, "text": "base.module.elementToSearch=1,2,3,4,5,6\n\n@Value(\"${base.module.elementToSearch}\")\n private String[] elementToSearch;\n" }, { "answer_id": 30181278, "author": "Sujith", "author_id": 2327123, "author_profile": "https://Stackoverflow.com/users/2327123", "pm_score": -1, "selected": false, "text": "key=value1;value2;value3\n\nString[] toArray = rs.getString(\"key\").split(\";\");\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9254/" ]
226,052
<p>What is the state generating Excel documents from a PHP application on a Linux server?</p> <p>I am interesting in creating Office 97 (xls) Excel files. My limited research on the subject has turned up this <a href="http://pear.php.net/package/Spreadsheet_Excel_Writer" rel="nofollow noreferrer">Pear package</a>. It appears to be in beta status since 2006.</p> <p>Can you share your success or failures in generating Excel files from PHP? Is there a reliable and mature tool available?</p> <p>Update: For this application I do need to generate an Excel file, not just a CSV file.</p>
[ { "answer_id": 226066, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 2, "selected": false, "text": "header(\"Content-Type: application/vnd.ms-excel\");\nheader(\"Expires: 0\");\nheader(\"Cache-Control: must-revalidate, post-check=0, pre-check=0\");\n" }, { "answer_id": 226348, "author": "Mojah", "author_id": 30330, "author_profile": "https://Stackoverflow.com/users/30330", "pm_score": 1, "selected": false, "text": "header(\"Content-type: application/vnd.ms-excel\");\nheader(\"Content-Disposition: attachment; filename=excel.xls\");\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13850/" ]
226,064
<p>How do I load a true color image into a CImageList?</p> <p>Right now I have</p> <pre><code>mImageList.Create(IDB_IMGLIST_BGTASK, 16, 1, RGB(255,0,255)); </code></pre> <p>Where <code>IDB_IMGLIST_BGTASK</code> is a 64x16 True color image. The ClistCtrl I am using it in shows 16 bpp color. I don't see a Create overload that allows me to specify both the bpp and the resource to load from.</p>
[ { "answer_id": 226104, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 4, "selected": true, "text": "CBitmap bm;\nbm.LoadBitmap(IDB_IMGLIST_BGTASK);\nmImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 4, 4);\nmImageList.Add(&bm, RGB(255,0,255));\n" }, { "answer_id": 226114, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 1, "selected": false, "text": "CImageList::Create(int cx, int cy, UINT nFlags, int nInitial, int nGrow)\n nFlags ILC_COLOR32 | ILC_MASK" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
226,065
<p>I have a Coupon table. A Coupon can be applicable to certain items only or to a whole category of items.</p> <p>For example: a 5$ coupon for a Pizza 12" <strong>AND</strong> (1L Pepsi <strong>OR</strong> French fries)</p> <p>The best I could come up with is to make a CouponMenuItems table containing a coupon_id and bit fields such as IsOr and IsAnd. It doesn't work because I have 2 groups of items in this example. The second one being a OR relation between 2 items.</p> <p>Any idea of how I could do it so the logic to implement is as simple as possible?</p> <p>Any help or cue appreciated! </p> <p>Thanks,</p> <p>Teebot</p>
[ { "answer_id": 226121, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "Coupon\n CouponId\n Name\n ...\n\nItem\n ItemId\n Name\n ...\n\nGroup\n GroupId\n\nGroupMembership\n GroupMembershipId\n GroupId\n ItemId\n\nItemAssociation\n ItemAssociationId\n Item1Id\n Item2Id\n IsOr : bit -- (default 0 means and)\n\nGroupAssociation\n GroupAssociationId\n Group1Id\n Group2Id\n IsOr : bit -- (default 0 means and)\n" }, { "answer_id": 226400, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "+----------+ 1 +---------------+ *\n| Coupon |<#>------>| <<interface>> |<--------------+\n+----------+ | CouponItem | |\n| +value | +---------------+ |\n+----------+ | +cost() | |\n +---------------+ |\n /|\\ |\n | |\n +--------------------------------+ |\n | | | |\n LeafCouponItem AndCouponItem OrCouponItem |\n <#> <#> |\n | | |\n +-------------+---------+\n class Coupon {\n Money value;\n CouponItem item;\n}\n\ninterface CouponItem {\n Money cost();\n}\n\nclass AndCouponItem implements CouponItem {\n List<CouponItem> items;\n Money cost() {\n Money cost = new Money(0);\n for (CouponItem item : items) {\n cost = cost.add(item.cost());\n }\n return cost;\n }\n}\n\nclass OrCouponItem implements CouponItem {\n List<CouponItem> items;\n Money cost() {\n Money max = new Money(0);\n for (CouponItem item : items) {\n max = Money.max(max, item.cost);\n }\n return max;\n }\n}\n\nclass LeafCouponItem implements CouponItem {\n Money cost;\n Money cost() {\n return cost;\n }\n}\n COUPON COUPON_ITEM\n------ -----------\nID ID\nVALUE COUPON_ID (FK to COUPON.ID)\n DISCRIMINATOR (AND, OR, or LEAF)\n COUPON_ITEM_ID (FK to COUPON_ITEM.ID)\n DESCRIPTION\n COST \n > SELECT * FROM COUPON\n\nID 100\nVALUE 5\n > SELECT * FROM COUPON_ITEM\n\nID COUPON_ID DISCRIMINATOR COUPON_ITEM_ID DESCRIPTION COST\n200 100 AND NULL NULL NULL\n201 100 LEAF 200 PIZZA 10\n202 100 OR 200 NULL NULL\n203 100 LEAF 202 PEPSI 2\n204 100 LEAF 202 FRIES 3\n" }, { "answer_id": 226826, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "Table\n primary key\n= = = = =\nCOUPONS\n coupon_id\n\nPRODUCT_GROUPS\n group_id\n\nITEM_LIST\n item_id\n\nITEM_GROUP_ASSOC\n item_id, group_id\n\nCOUPON_GROUP_ASSOC\n coupon_id, group_id \n\nCOUPON_ITEM_ASSOC\n coupon_id, item_id\n COUPON_ITEM_ASSOC" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24291/" ]
226,071
<p>I have the HTML given below:</p> <pre><code>&lt;ul id="thumbsPhotos"&gt; &lt;li src="/images/1alvaston-hall-relaxing-lg.jpg" onclick="updatePhoto (this.title)"&gt;&lt;img src="/images/1alvaston-hall-relaxing-sl.jpg" width="56" height="56"&gt;&lt;/li&gt; &lt;li onclick="updatePhoto(this.title)" src=""&gt;&lt;img src="" width="56" height="56"&gt;&lt;/li&gt; &lt;li onclick="updatePhoto(this.title)" src=""&gt;&lt;img src="" width="56" height="56"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Now, I want to replace all the <code>src</code> in <code>&lt;li&gt;</code> tags not in <code>&lt;img&gt;</code> tags using <code>InnerHTML</code>. With this, my output will be:</p> <pre><code>&lt;ul id="thumbsPhotos"&gt; &lt;li title="/images/1alvaston-hall-relaxing-lg.jpg" onclick="updatePhoto(this.title)"&gt;&lt;img src="/images/1alvaston-hall-relaxing-sl.jpg" width="56" height="56"&gt;&lt;/li&gt; &lt;li onclick="updatePhoto(this.title)" title=""&gt;&lt;img src="" width="56" height="56"&gt;&lt;/li&gt; &lt;li onclick="updatePhoto(this.title)" title=""&gt;&lt;img src="" width="56" height="56"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 226099, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "$(document).ready(function() {\n $(\"li[src], li[src='']\").each(function() {\n var li = $(this);\n li.attr(\"title\", li.attr(\"src\"));\n li.removeAttr(\"src\");\n });\n});\n" }, { "answer_id": 226100, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "// find:\n<li ([^>]*)src=\"(.*?)\"(.*?)>\n\n// replace:\n<li $1title=\"$2\"$3>\n var ul = document.getElementById(\"thumbsPhotos\");\nul.innerHTML = ul.innerHTML.replace(\n /<li ([^>]*)src=\"(.*?)\"(.*?)>/g,\n '<li $1title=\"$2\"$3>'\n);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30394/" ]
226,088
<p>My predicament is fairly simple: This function gets the <code>id</code> of 'this' <code>&lt;li&gt;</code> element based on parent <code>id</code> of <code>&lt;ul&gt;</code>. It used to work fine but not any more, I will either need to have <code>&lt;ul&gt;</code> use <code>class</code>es instead of <code>id</code> while still being able to assign <code>id</code> of 'current' to the current element, or change my css.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function myFunction(element) { liArray = document.getElementById("leftlist").childNodes; i = 0; while (liArray[i]) { liArray[i].id = ""; i++; } element.id = "current"; // or element.className ? }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul#leftlist { background-color: rgb(205, 205, 205); } ul#leftlist li#current a { color: rgb(96, 176, 255); background-color: 218, 218, 218); } ul#leftlist li a { color: rgb(86, 86, 86); } #leftlist a:link { color: rgb(86, 86, 86); background-color: #ddd; } #leftlist a:active { color: rgb(96, 176, 255); background-color: rgb(218, 218, 218); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul id="leftlist"&gt; &lt;li onClick='myFunction(this);'&gt; &lt;a href="123" bla bla &lt;/a&gt;&lt;/li&gt; &lt;li onClick='myFunction(this);'&gt; .... etc.&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p>Perhaps I need to change my css. This worked before but now the current <code>id</code> is not being effective as <code>ul#leftlist li a</code> takes priority even when i assign <code>id="current"</code> via JavaScript.</p>
[ { "answer_id": 226186, "author": "Erlend Halvorsen", "author_id": 1920, "author_profile": "https://Stackoverflow.com/users/1920", "pm_score": 2, "selected": false, "text": "ul#leftlist li.current a {\n color: rgb(96,176,255) !important;\n background-color:218,218,218) !important;\n}\n" }, { "answer_id": 226202, "author": "Matt", "author_id": 29228, "author_profile": "https://Stackoverflow.com/users/29228", "pm_score": 0, "selected": false, "text": "ul#leftlist li#current a{color: rgb(96,176,255); background-color:218,218,218);}\n rgb( background-color ul#leftlist li#current a{color: rgb(96,176,255); background-color: rgb(218,218,218);}\n current" }, { "answer_id": 226207, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 0, "selected": false, "text": "function myFunction(element){\n var liArray = document.getElementById(\"leftlist\").childNodes;\n var i=0, item;\n while (item = liArray[i++]) {\n if (item.nodeType === 1) {\n item.className = item.className.replace(/(^| )current( |$)/g, '');\n }\n }\n element.className += \" current\";\n}\n ul#leftlist li.current a { ... }\n" }, { "answer_id": 226217, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "liArray=element.parentNode.getElementsByTagName(\"li\");\n ul#leftlist #myParent ul#leftlist .myParent ul#leftlist" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419730/" ]
226,102
<p>I realise this is not the ideal place to ask about this in terms of searchability, but I've got a page whose JavaScript code throws "Stack overflow in line 0" errors when I look at it in Internet Explorer.</p> <p>The problem is quite clearly not in line 0, but somewhere in the list of stuff that I'm writing to the document. Everything works fine in Firefox, so I don't have the delights of Firebug and friends to assist in troubleshooting.</p> <p>Are there any standard causes for this? I'm guessing this is probably an Internet Explorer 7 bug or something quite obscure, and my <a href="http://en.wiktionary.org/wiki/Google-fu" rel="nofollow noreferrer">Google-fu</a> is bringing me little joy currently. I can find lots of people who have run into this before, but I can't seem to find how they solved it.</p>
[ { "answer_id": 226113, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": true, "text": "\"Disable Script Debugging\" Visual Studio IE" }, { "answer_id": 226437, "author": "glenatron", "author_id": 15394, "author_profile": "https://Stackoverflow.com/users/15394", "pm_score": 4, "selected": false, "text": "OnError()" }, { "answer_id": 1826033, "author": "massoud", "author_id": 222095, "author_profile": "https://Stackoverflow.com/users/222095", "pm_score": 3, "selected": false, "text": "<%@ Page MaintainScrollPositionOnPostback" }, { "answer_id": 9143712, "author": "Tillito", "author_id": 131165, "author_profile": "https://Stackoverflow.com/users/131165", "pm_score": 2, "selected": false, "text": "<pages smartNavigation=\"true\" maintainScrollPositionOnPostBack=\"true\" />\n" }, { "answer_id": 9536083, "author": "devsnd", "author_id": 1191373, "author_profile": "https://Stackoverflow.com/users/1191373", "pm_score": 2, "selected": false, "text": "By.id(\"xyz\")" }, { "answer_id": 13979424, "author": "pmaruszczyk", "author_id": 269804, "author_profile": "https://Stackoverflow.com/users/269804", "pm_score": 0, "selected": false, "text": "a() b() var i = 0;\nfunction a() { b(); }\nfunction b() {\n i++; \n if (i < 30) {\n a();\n }\n}\n\na();\n setTimeout var i = 0;\nfunction a() { b(); }\nfunction b() {\n i++; \n if (i < 30) {\n setTimeout( function() {\n a();\n }, 0);\n }\n}\n\na();\n" }, { "answer_id": 14449734, "author": "Muhd", "author_id": 446921, "author_profile": "https://Stackoverflow.com/users/446921", "pm_score": 1, "selected": false, "text": ".clone $($(selector).html())" }, { "answer_id": 19586779, "author": "Max", "author_id": 840672, "author_profile": "https://Stackoverflow.com/users/840672", "pm_score": 1, "selected": false, "text": "$('.numbersonly').on(\"keyup input propertychange\", function () {\n //code\n});\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15394/" ]
226,105
<p>I'm trying to read a single XML document from stream at a time using dom4j, process it, then proceed to the next document on the stream. Unfortunately, dom4j's SAXReader (using JAXP under the covers) keeps reading and chokes on the following document element.</p> <p>Is there a way to get the SAXReader to stop reading the stream once it finds the end of the document element? Is there a better way to accomplish this?</p>
[ { "answer_id": 231621, "author": "Trenton", "author_id": 2601671, "author_profile": "https://Stackoverflow.com/users/2601671", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\"?>" }, { "answer_id": 245467, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 0, "selected": false, "text": "SubdocReader sdr=new SubdocReader(input);\nwhile(!sdr.eof()) {\n sdr.next();\n // read doc here using DOM\n // then process document\n }\ninput.close();\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7708/" ]
226,108
<p>I've been reading about "web services" here on SO, on Wikipedia, Google, etc., and I don't quite understand what they are. What is the plain English definition/description?</p> <p>If I make a simple website using PHP that just, say, prints a random integer to the page... is this a "web service"? If not, why not?</p>
[ { "answer_id": 226128, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 5, "selected": false, "text": "<RANDOM>some random number</RANDOM>\n <HEAD>...</HEAD> \n<BODY>some random number</BODY>\n" }, { "answer_id": 17562538, "author": "Devrath", "author_id": 1083093, "author_profile": "https://Stackoverflow.com/users/1083093", "pm_score": 3, "selected": false, "text": "Simple way to explain web service is ::" }, { "answer_id": 34698358, "author": "user1079065", "author_id": 1079065, "author_profile": "https://Stackoverflow.com/users/1079065", "pm_score": 2, "selected": false, "text": "user on website -> HTML/JS/JQuery etc -> give me a random number ->ur program\n ur program -> generate random number -> generate HTML and encapsulate o/p -> go back to user user -> my application -> XML/JSON/some other format -> give me a random number ->ur program ur program -> generate random number -> generate XML/JSON/some other format -> my application -> generate HTML and encapsulate o/p -> go back to user" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
226,127
<p>I have a project with a number of different classes querying and modifying data in a common set of tables. I've set up a .dbml file which provides us with a DataContext class. My question is whether a single instance of the DataContext should be used by all objects, or whether multiple instances are safe to use. I'm also wondering about thread safety in the case of a single DataContext, and whether access to it's methods should be synchronized.</p>
[ { "answer_id": 226260, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "User Application" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14357/" ]
226,131
<p>Safari on iPhone automatically creates links for strings of digits that appear to the telephone numbers. I am writing a web page containing an IP address, and Safari is turning that into a phone number link. Is it possible to disable this behavior for a whole page or an element on a page?</p>
[ { "answer_id": 226229, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 1, "selected": false, "text": "&#48; = 0\n&#57; = 9\n" }, { "answer_id": 226247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<meta name = \"format-detection\" content = \"telephone=no\">\n" }, { "answer_id": 227238, "author": "lewinski", "author_id": 30491, "author_profile": "https://Stackoverflow.com/users/30491", "pm_score": 11, "selected": true, "text": "<meta name=\"format-detection\" content=\"telephone=no\">\n" }, { "answer_id": 3437864, "author": "BobFromBris", "author_id": 381975, "author_profile": "https://Stackoverflow.com/users/381975", "pm_score": 3, "selected": false, "text": "<label> <div> telephone=no" }, { "answer_id": 5557962, "author": "catshow", "author_id": 693700, "author_profile": "https://Stackoverflow.com/users/693700", "pm_score": 5, "selected": false, "text": "self.webView.dataDetectorTypes = UIDataDetectorTypeNone;\n" }, { "answer_id": 5797082, "author": "mattstuehler", "author_id": 49383, "author_profile": "https://Stackoverflow.com/users/49383", "pm_score": 2, "selected": false, "text": " <meta name = \"format-detection\" content = \"telephone=no\">\n &#48; = 0\n&#57; = 9\n 555.5<span>5</span>5.5555" }, { "answer_id": 6047555, "author": "mhenry1384", "author_id": 24267, "author_profile": "https://Stackoverflow.com/users/24267", "pm_score": 2, "selected": false, "text": "ABN 98<img class=\"PreventSafariFromTurningIntoLink\" /> 009<img /> 675<img /> 709\n" }, { "answer_id": 6349251, "author": "yodaisgreen", "author_id": 246034, "author_profile": "https://Stackoverflow.com/users/246034", "pm_score": 3, "selected": false, "text": "<a href=\"#\"> 1234567 </a>\n" }, { "answer_id": 7305442, "author": "Alan M.", "author_id": 199374, "author_profile": "https://Stackoverflow.com/users/199374", "pm_score": 3, "selected": false, "text": "<meta name = \"format-detection\" content = \"telephone=no\">\n <input type=\"text\" readonly=\"readonly\" style=\"border:none;\" value=\"3105551212\">\n" }, { "answer_id": 7778171, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "// ...\n\n- (void)webViewDidStartLoad:(UIWebView *)theWebView \n{\n // disable telephone detection, basically <meta name=\"format-detection\" content=\"telephone=no\" />\n theWebView.dataDetectorTypes = UIDataDetectorTypeAll ^ UIDataDetectorTypePhoneNumber;\n\n return [ super webViewDidStartLoad:theWebView ];\n}\n\n// ...\n" }, { "answer_id": 9008797, "author": "someone else", "author_id": 1169920, "author_profile": "https://Stackoverflow.com/users/1169920", "pm_score": 1, "selected": false, "text": "<meta name=\"format-detection\" content=\"telephone=no\">" }, { "answer_id": 10401451, "author": "cabrera", "author_id": 935846, "author_profile": "https://Stackoverflow.com/users/935846", "pm_score": 2, "selected": false, "text": "<meta name = \"format-detection\" content = \"telephone=no\"> will cease operations <span class='ios-avoid-format'>on June 1,\n2012</span><span></span>.\n @media only screen and (device-width: 768px) and (orientation:portrait){\nspan.ios-date{display:none;}\nspan.ios-date + span:after{content:\"on June 1, 2012\";}\n}\n" }, { "answer_id": 11021252, "author": "Vincent Tobiaz", "author_id": 1454437, "author_profile": "https://Stackoverflow.com/users/1454437", "pm_score": 1, "selected": false, "text": "<a href=\"#\" style=\"color: #666666; \n text-decoration: none;\n pointer-events: none;\">\n Boca Raton, FL 33487\n</a>\n" }, { "answer_id": 14870203, "author": "Jay", "author_id": 751570, "author_profile": "https://Stackoverflow.com/users/751570", "pm_score": 2, "selected": false, "text": "(604) 555<span></span> -4321\n" }, { "answer_id": 15358743, "author": "Florian Grell", "author_id": 353907, "author_profile": "https://Stackoverflow.com/users/353907", "pm_score": 6, "selected": false, "text": ".element { pointer-events: none; }\n.element > a { text-decoration:none; color:inherit; }\n" }, { "answer_id": 17928016, "author": "Phil LaNasa", "author_id": 2374900, "author_profile": "https://Stackoverflow.com/users/2374900", "pm_score": 1, "selected": false, "text": "Phone: 1-8&#48;&#48;<span>-</span>62&#48;<span>-</span>38&#48;3\n" }, { "answer_id": 22605764, "author": "Marc", "author_id": 3454790, "author_profile": "https://Stackoverflow.com/users/3454790", "pm_score": 2, "selected": false, "text": "a[href^=tel] {\n color: inherit;\n text-decoration:inherit;\n}\n" }, { "answer_id": 30804432, "author": "kaosmos", "author_id": 2477547, "author_profile": "https://Stackoverflow.com/users/2477547", "pm_score": 1, "selected": false, "text": "tel: &#8288; 0613605&#8288;048&#8288;8" }, { "answer_id": 31054065, "author": "diazwatson", "author_id": 2285763, "author_profile": "https://Stackoverflow.com/users/2285763", "pm_score": 3, "selected": false, "text": "<a> javascript: void(0) href <a href=\"javascript: void(0)\">+44 456 77 89 87</a>" }, { "answer_id": 36733173, "author": "stickyuser", "author_id": 2717951, "author_profile": "https://Stackoverflow.com/users/2717951", "pm_score": 6, "selected": false, "text": "&zwj;" }, { "answer_id": 36927988, "author": "Daniel", "author_id": 2995613, "author_profile": "https://Stackoverflow.com/users/2995613", "pm_score": 1, "selected": false, "text": "‑" }, { "answer_id": 38213781, "author": "Kareem", "author_id": 2151420, "author_profile": "https://Stackoverflow.com/users/2151420", "pm_score": 0, "selected": false, "text": "301 <div style=\"display:inline-block\">441</div> 3909\n" }, { "answer_id": 73746889, "author": "dev_willis", "author_id": 1437705, "author_profile": "https://Stackoverflow.com/users/1437705", "pm_score": 0, "selected": false, "text": "<p> a[href^=\"tel:\"] <code>" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10947/" ]
226,132
<p>What are the differences between a wiki and a CMS? Is there any?</p>
[ { "answer_id": 10086896, "author": "Nimesh", "author_id": 826618, "author_profile": "https://Stackoverflow.com/users/826618", "pm_score": 0, "selected": false, "text": "The New York Times TechCrunch WordPress" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15884/" ]
226,144
<p>We all know that you can overload a function according to the parameters:</p> <pre><code>int mul(int i, int j) { return i*j; } std::string mul(char c, int n) { return std::string(n, c); } </code></pre> <p>Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used:</p> <pre><code>int n = mul(6, 3); // n = 18 std::string s = mul(6, 3); // s = "666" // Note that both invocations take the exact same parameters (same types) </code></pre> <p>You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.</p>
[ { "answer_id": 226173, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 4, "selected": false, "text": "mul(1, 2);" }, { "answer_id": 226192, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "string char" }, { "answer_id": 226208, "author": "Paolo Tedesco", "author_id": 15622, "author_profile": "https://Stackoverflow.com/users/15622", "pm_score": -1, "selected": false, "text": "template<typename T>\nT mul(int i,int j){\n return i * j;\n}\n\ntemplate<>\nstd::string mul(int i,int j){\n return std::string(j,i);\n}\n int x = mul<int>(2,3);\nstd::string s = mul<std::string>(2,3);\n" }, { "answer_id": 226220, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 3, "selected": false, "text": "class BadIdea\n{\n public:\n operator string() { return \"silly\"; }\n operator int() { return 15; }\n};\n\nBadIdea mul(int, int)\n" }, { "answer_id": 226251, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 7, "selected": true, "text": "class mul\n{\npublic:\n mul(int p1, int p2)\n {\n param1 = p1;\n param2 = p2;\n }\n operator int ()\n {\n return param1 * param2;\n }\n\n operator std::string ()\n {\n return std::string(param2, param1 + '0');\n }\n\nprivate:\n int param1;\n int param2;\n};\n" }, { "answer_id": 228923, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 6, "selected": false, "text": "std::string mul(char c, int n) { return std::string(n, c); }\n\nstd::string s = mul(6, 3); // s = \"666\"\n std::string s = mul(static_cast<char>(54), 3); // s = \"666\"\n int mul(int *, int i, int j) { return i*j; }\nstd::string mul(std::string *, char c, int n) { return std::string(n, c); }\n int n = mul((int *) NULL, 6, 3); // n = 18\nstd::string s = mul((std::string *) NULL, 54, 3); // s = \"666\"\n template<typename T>\nT mul(int i, int j)\n{\n // If you get a compile error, it's because you did not use\n // one of the authorized template specializations\n const int k = 25 ; k = 36 ;\n}\n template<>\nint mul<int>(int i, int j)\n{\n return i * j ;\n}\n\ntemplate<>\nstd::string mul<std::string>(int i, int j)\n{\n return std::string(j, static_cast<char>(i)) ;\n}\n int n = mul<int>(6, 3); // n = 18\nstd::string s = mul<std::string>(54, 3); // s = \"666\"\n short n2 = mul<short>(6, 3); // error: assignment of read-only variable ‘k’\n // For \"int, int\" calls\ntemplate<typename T>\nT mul(int i, int j)\n{\n // If you get a compile error, it's because you did not use\n // one of the authorized template specializations\n const int k = 25 ; k = 36 ;\n}\n\ntemplate<>\nint mul<int>(int i, int j)\n{\n return i * j ;\n}\n\n// For \"char, int\" calls\ntemplate<typename T>\nT mul(char i, int j)\n{\n // If you get a compile error, it's because you did not use\n // one of the authorized template specializations\n const int k = 25 ; k = 36 ;\n}\n\ntemplate<>\nstd::string mul<std::string>(char i, int j)\n{\n return std::string(j, (char) i) ;\n}\n int n = mul<int>(6, 3); // n = 18\nstd::string s = mul<std::string>('6', 3); // s = \"666\"\n short n2 = mul<short>(6, 3); // n = 18\n" }, { "answer_id": 429724, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 5, "selected": false, "text": "mul class StringOrInt\n{\npublic:\n StringOrInt(int p1, int p2)\n {\n param1 = p1;\n param2 = p2;\n }\n operator int ()\n {\n return param1 * param2;\n }\n\n operator std::string ()\n {\n return std::string(param2, param1 + '0');\n }\n\nprivate:\n int param1;\n int param2;\n};\n\nStringOrInt mul(int p1, int p2)\n{\n return StringOrInt(p1, p2);\n}\n mul int main(int argc, char* argv[])\n{\n vector<int> x;\n x.push_back(3);\n x.push_back(4);\n x.push_back(5);\n x.push_back(6);\n\n vector<int> intDest(x.size());\n transform(x.begin(), x.end(), intDest.begin(), bind1st(ptr_fun(&mul), 5));\n // print 15 20 25 30\n for (vector<int>::const_iterator i = intDest.begin(); i != intDest.end(); ++i)\n cout << *i << \" \";\n cout << endl;\n\n vector<string> stringDest(x.size());\n transform(x.begin(), x.end(), stringDest.begin(), bind1st(ptr_fun(&mul), 5));\n // print 555 5555 55555 555555\n for (vector<string>::const_iterator i = stringDest.begin(); i != stringDest.end(); ++i)\n cout << *i << \" \";\n cout << endl;\n\n return 0;\n}\n" }, { "answer_id": 2831943, "author": "justin romaine", "author_id": 340936, "author_profile": "https://Stackoverflow.com/users/340936", "pm_score": -1, "selected": false, "text": "\nclass mul\n{\n int m_i,m_j;\npublic:\n mull(int i,int j):m_i(i),m_j(j){}\n template\n operator R() \n {\n return (R)m_i * m_j;\n }\n};\n \ndouble d = mul(1,2);\nlong l = mul(1,2);\n" }, { "answer_id": 6754713, "author": "John Littleberry Sr", "author_id": 852895, "author_profile": "https://Stackoverflow.com/users/852895", "pm_score": 2, "selected": false, "text": "//This is not valid\n int foo();\n float foo();\n\n typedef int Int;\n\n int foo(int j);\n int foo(Int j);\n\n//Valid:\n int foo(int j);\n char* foo(char * s);\n int foo(int j, int k);\n float foo(int j, float k);\n float foo(float j, float k);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
226,172
<p>We (apparently) had poorly executed of our Solaris MySQL database engine last night. At least some of the InnoDB tables are corrupted, with timestamp out of order errors in the transaction log, and a specific error about the index being corrupted.</p> <p>We know about the tools available for MyISAM table repairs, but cannot find anything for InnoDB.</p> <p>Side note: attempting a table optimize (in my attempt to rebuild the corrupted index) causes the database server to crash.</p>
[ { "answer_id": 3322930, "author": "Sandro Frattura", "author_id": 400741, "author_profile": "https://Stackoverflow.com/users/400741", "pm_score": 5, "selected": false, "text": "create table <new table> like <old table>;\ninsert <new table> select * from <old table>;\ntruncate table <old table>;\ninsert <old table> select * from <new table>;\n" }, { "answer_id": 5917337, "author": "jpetazzo", "author_id": 580281, "author_profile": "https://Stackoverflow.com/users/580281", "pm_score": 3, "selected": false, "text": "broken SELECT COUNT(*) FROM broken PRIMARY KEY id CREATE TABLE broken_repair LIKE broken; INSERT broken_repair SELECT * FROM broken WHERE id NOT IN (SELECT id FROM broken_repair) LIMIT 1; LIMIT 100000 LIMIT 1 SELECT MAX(id) FROM broken broken_repair OFFSET LIMIT" }, { "answer_id": 32806203, "author": "Terry Lin", "author_id": 1839495, "author_profile": "https://Stackoverflow.com/users/1839495", "pm_score": -1, "selected": false, "text": "set-variable=innodb_force_recovery=6\n mysqlcheck --database db_name table_name -uroot -p\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29975/" ]
226,206
<p>I would actually love to have an AlternatingItemTemplate on a GridView, but all it offers is an AlternatingItemStyle. In my grid, each two column row (in a table layout), has an image in the first column, and a description in the second column. I would like to have the positioning of the image and description alternate on alternate rows. </p> <p>How can I do this?</p>
[ { "answer_id": 226358, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<asp:Repeater runat=\"server\" ID=\"Repeater1\" OnItemDataBound=\"Repeater1_ItemDataBound\" />\n public void Repeater1_ItemDataBound(Object sender, RepeaterItemEventArgs e)\n{\n if (e.Item.ItemType == ListItemType.AlternatingItem)\n {\n // e.Item is an alternating item\n }\n else\n {\n }\n}\n" }, { "answer_id": 226960, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 3, "selected": true, "text": "<div class=\"MyImage\"><img src=\"\" /></div>\n<div class=\"MyDescription\">Blah...Blah...</div>\n .MyItemStyle .MyImage {width:49%; float:left;}\n.MyItemStyle .MyDescription {width:49%; float:right;}\n\n.MyAltItemStyle .MyImage {width:49%; float:right;}\n.MyAltItemStyle .MyDescription {width:49%; float:left;}\n ItemStyle = \"MyItemStyle\"\nAlternatingItemStyle = \"MyAltItemStyle\"\n" }, { "answer_id": 227088, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": " <asp:GridView>\n <Columns>\n <asp:TemplateColumn>\n <%# Container.DataItemIndex % 2 == 0 ? Eval(\"Image\") : Eval(\"Desc\") %>\n </asp:TemplateColumn>\n <asp:TemplateColumn>\n <%# Container.DataItemIndex % 2 == 0 ? Eval(\"Desc\") : Eval(\"Image\") %>\n </asp:TemplateColumn>\n </Columns>\n </asp:GridView>\n <asp:GridView>\n <Columns>\n <asp:TemplateColumn>\n <uc:Image Data='<%# Eval(\"Image\") %>' \n Visible='<%# Container.DataItemIndex % 2 == 0 %>' />\n <uc:Description Data='<%# Eval(\"Description\") %>' \n Visible='<%# Container.DataItemIndex % 2 != 0 %>' />\n </asp:TemplateColumn>\n <asp:TemplateColumn>\n <uc:Image Data='<%# Eval(\"Image\") %>' \n Visible='<%# Container.DataItemIndex % 2 != 0 %>' />\n <uc:Description Data='<%# Eval(\"Description\") %>' \n Visible='<%# Container.DataItemIndex % 2 == 0 %>' />\n </asp:TemplateColumn>\n </Columns>\n </asp:GridView>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]