qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
305,519
<p>In an impersonation scenario related to Sharepoint I need to execute some code in a separate process (the process will run in the context of a certain user). I do not want to launch a separate application, basically I want to do a "run as" on just a method.</p>
[ { "answer_id": 305558, "author": "Gunnar Steinn", "author_id": 33468, "author_profile": "https://Stackoverflow.com/users/33468", "pm_score": 2, "selected": false, "text": "...\nWrapperImpersonationContext context = new WrapperImpersonationContext(domain, username, password);\ncontext.Enter();\n\nResults res = MyImpersonatedMethod(data);\n\ncontext.Leave();\n...\n" }, { "answer_id": 305600, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": true, "text": "Dim psiNewProcess As New ProcessStartInfo(\"Notepad.exe\")\n\npsiNewProcess.UserName = \"MyUserName\"\npsiNewProcess.Password = \"MyPassword\"\n\nProcess.Start(psiNewProcess)\n Dim instance As ProcessStartInfo\nDim value As SecureString\n\nvalue = instance.Password\n\ninstance.Password = value\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
305,523
<p>I am writing a QT application and I need to embed a terminal (we say,xterm) within a QDialog, like some KDE application (see kdevelop/kate/...).</p> <p>I've been trying with: - QX11EmbedContainer placed into the QLayout of my QDialog - QProcess for the program I want to excecute</p> <p>I expect the QProcess running within the QX11EmbedContainer, but it does not work.</p> <p>The problem is that I can't put the xterm into the QX11EmbedContainer, the only thing I obtain is an xterm window (unfortunately separated from my QDialog). Does anybody got the same problem?</p>
[ { "answer_id": 307752, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 0, "selected": false, "text": " QProcess process(&container);\n QString executable(app.arguments()[1]);\n QStringList arguments;\n arguments << \"-into\" << QString::number(container.winId());\n process.start(executable, arguments);\n" }, { "answer_id": 310298, "author": "JuanDeLosMuertos", "author_id": 39339, "author_profile": "https://Stackoverflow.com/users/39339", "pm_score": 3, "selected": true, "text": "#include <kparts/part.h>\n#include <assert.h>\n#include <kde_terminal_interface.h>\n#include <kpluginfactory.h>\n#include <klibloader.h>\n KLibFactory* factory = KLibLoader::self()->factory( \"libkonsolepart\" );\nKParts::Part* p = static_cast<KParts::Part*>(factory->create( this,\"tralala\", \nQStringList() << \"dio\") );\n\nassert(p);\nsetCentralWidget( p->widget() );\nTerminalInterface *t = qobject_cast<TerminalInterface*>(p);\nt->showShellInDir( QDir::home().path() );\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39339/" ]
305,527
<p>I cannot figure out a way to disable a container AND its children in Swing. Is Swing really missing this basic feature?</p> <p>If I do setEnabled(false) on a container, its children are still enabled.</p> <p>My GUI structure is pretty complex, and doing a traversion of all elements below the container is not an option. Neither is a GlassPane on top of the container (the container is not the entire window).</p>
[ { "answer_id": 305551, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 4, "selected": false, "text": "JXLayer.setLocked(true)" }, { "answer_id": 2214729, "author": "Dylan", "author_id": 267889, "author_profile": "https://Stackoverflow.com/users/267889", "pm_score": 0, "selected": false, "text": "Component[] comps = myPanel.getComponents();\nfor (Component comp:comps){\n comp.setEnabled(false);\n}\n" }, { "answer_id": 2339273, "author": "Defd", "author_id": 250777, "author_profile": "https://Stackoverflow.com/users/250777", "pm_score": 0, "selected": false, "text": "class ControlledActionListener extends ActionListener {\n ...\n public void actionPerformed( ActionEvent e ) {\n if( !container.isEnabled() ) return;\n\n doYourBusinessHere();\n }\n}\n" }, { "answer_id": 4387278, "author": "spygas", "author_id": 534950, "author_profile": "https://Stackoverflow.com/users/534950", "pm_score": 0, "selected": false, "text": "@Override\npublic void setEnabled(boolean en) {\n super.setEnabled(en);\n setComponentsEnabled(this, en);\n}\n\nprivate void setComponentsEnabled(java.awt.Container c, boolean en) {\n Component[] components = c.getComponents();\n for (Component comp: components) {\n if (comp instanceof java.awt.Container)\n setComponentsEnabled((java.awt.Container) comp, en);\n comp.setEnabled(en);\n }\n}\n" }, { "answer_id": 4387359, "author": "barjak", "author_id": 112053, "author_profile": "https://Stackoverflow.com/users/112053", "pm_score": 2, "selected": false, "text": " a\n / \\\n b c\n / \\\n d e\n\nsetMoreDisabled(c)\n\n a\n / \\\n b (c)\n / \\\n (d) (e)\n\nsetMoreDisabled(a)\n\n (a)\n / \\\n b (c)\n / \\\n (d) (e)\n\nsetMoreEnabled(a)\n\n a\n / \\\n b (c)\n / \\\n (d) (e)\n import java.awt.Component;\nimport java.awt.Container;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\npublic class EnableDisable {\n\n private static final Map<Component, Integer> componentAvailability = new WeakHashMap<Component, Integer>();\n\n public static void setMoreEnabled(Component component) {\n setEnabledRecursive(component, +1);\n }\n\n public static void setMoreDisabled(Component component) {\n setEnabledRecursive(component, -1);\n }\n\n // val = 1 for enabling, val = -1 for disabling\n private static void setEnabledRecursive(Component component, int val) {\n if (component != null) {\n final Integer oldValObj = componentAvailability.get(component);\n final int oldVal = (oldValObj == null)\n ? 0\n : oldValObj;\n final int newVal = oldVal + val;\n componentAvailability.put(component, newVal);\n\n if (newVal >= 0) {\n component.setEnabled(true);\n } else if (newVal < 0) {\n component.setEnabled(false);\n }\n if (component instanceof Container) {\n Container componentAsContainer = (Container) component;\n for (Component c : componentAsContainer.getComponents()) {\n setEnabledRecursive(c,val);\n }\n }\n }\n }\n\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15932/" ]
305,529
<p>Greetings to all! This is my first question here on stackoverflow. I have a WPF application that I am writing for the fellow developers in my department, and there are a couple of settings that I need to check for at startup and update if they are not set (one is the location of an executable on the users computer, we all have it, just not in the same place). So when my app starts up for the first time, I need to pop a filechooser to have them select the location.</p> <p>What I need to do is write the location of that to the appSettings, but I just can't seem to get it, and I searched Google pretty hard last night trying to find a way to do it. Most answers I saw involved reading the app.config file as straight XML, and that doesn't seem right.</p> <p>So, I just need a way to update values in the appSettings for my application. I can read from them just fine, just haven't figured out how to write to them. Thanks so much!</p> <p>James</p>
[ { "answer_id": 305547, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 6, "selected": true, "text": "Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\noConfig.AppSettings.Settings[\"PreferenceToRemember\"].Value = \"NewValue\";\noConfig.Save(ConfigurationSaveMode.Full);\nConfigurationManager.RefreshSection(\"appSettings\");\n System.Configuration" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39337/" ]
305,536
<pre><code>// A Mutex allows threads mutually exclusive access to a resource. //----------------------------------------------------------------------- class Mutex { private: CRITICAL_SECTION m_mutex; public: Mutex() { InitializeCriticalSection(&amp;m_mutex); } ~Mutex() { DeleteCriticalSection(&amp;m_mutex); } void acquire() { EnterCriticalSection(&amp;m_mutex); } void release() { LeaveCriticalSection(&amp;m_mutex); } }; </code></pre> <p>Using the Entrek Codesnitch software to debug and test for any memory leaks, etc., it reports the following error:</p> <pre><code>InitializeCriticalSection Error: lpCriticalSection (0x000387d4) points to an invalid memory location (0x00018984) Mutex::Mutex in lockmutex.h, line 29 </code></pre> <p>Maybe all my sleepless nights are finally getting to me. But I don't understand what it's exactly complaining about. Any ideas?</p>
[ { "answer_id": 305704, "author": "Tim Lesher", "author_id": 14942, "author_profile": "https://Stackoverflow.com/users/14942", "pm_score": 3, "selected": false, "text": "struct Customer {\n char * name;\n};\n\nextern void greetCustomer(Customer* c);\n\nclass CheckoutLine {\n private:\n Customer m_customer;\n public CheckoutLine() {\n greetCustomer(&m_customer);\n }\n};\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7599/" ]
305,538
<p>I'm working on a webserver that I didn't totally set up and I'm trying to figure out which parts of a web page are being sent encrypted and which aren't. Firefox tells me that parts of the page are encrypted, but I want to know what, specifically, is encrypted.</p>
[ { "answer_id": 7691014, "author": "Professor Falken", "author_id": 888986, "author_profile": "https://Stackoverflow.com/users/888986", "pm_score": 4, "selected": false, "text": "Response Headers \nServer nginx/0.8.54\nDate Fri, 07 Oct 2011 17:35:16 GMT\nContent-Type text/html\nContent-Length 185\nConnection keep-alive\nLocation http://external.example.com/embed/?key=t6Qu2&width=940&height=300&interval=week&baseAtZero=false\n\nRequest Headers\nHost external.example.com\nUser-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1\nAccept */*\nAccept-Language en-gb,en;q=0.5\nAccept-Encoding gzip, deflate\nAccept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7\nConnection keep-alive\nReferer https://mysite.example.com/real-time-data\nCookie JSESSIONID=B33FF1C1F1B732E7F05A547A9CB76ED3\nPragma no-cache\nCache-Control no-cache\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8092/" ]
305,552
<p>Need to locate the following pattern:</p> <p>The letter I followed by a space then three alpha numerics followed by a space</p> <p>"I ALN " "I H21 " "I 31M "</p> <p>these items are also followed by a lat/lon that is trapped by this expression:</p> <p>Dim regex As New Regex("\d{6} \d{7}")</p> <p>Can the expressions be combined to return a match that would look like:</p> <p>"H21 ###### #######"</p> <p>Thanks,</p> <p>Dave</p>
[ { "answer_id": 305560, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "I ([a-zA-Z\\d]{3} \\d{6} \\d{7})\n" }, { "answer_id": 305573, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 3, "selected": true, "text": "\n/^[A-z] ([0-z]{3}) [A-z] [0-z]{3} L (\\d{6} \\d{7})/\n \n/^I ([0-z]{3}) .* (\\d{6} \\d{7})/\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38349/" ]
305,554
<p>Assume I have a function like this:</p> <pre><code>MyClass &amp;MyFunction(void) { static MyClass *ptr = 0; if (ptr == 0) ptr = new MyClass; return MyClass; } </code></pre> <p>The question is at program exit time, will the ptr variable ever become invalid (i.e. the contents of that ptr are cleaned up by the exiting process)? I realize that this function leaks, but it is only an example for simplicity.</p> <p>The same question also applies to other primitives besides pointers as well. How about if I have a static integer, does the value of that integer always persist throughout exit or is variable due to static destruction order issues?</p> <p>EDIT:</p> <p>Just to clarify, I want to know what actually happens to the contents of the static pointer (or any other primitive type like an int or a float) and not to the memory it is pointing to. For instance, imagine that the ptr points to some memory address which I want to check in the destructor of some other static class. Can I rely on the fact that the contents of the ptr won't be changed (i.e. that the pointer value won't be cleaned up during the static destruction process)?</p> <p>Thanks, Joe</p>
[ { "answer_id": 305569, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 2, "selected": false, "text": "MyClass" }, { "answer_id": 306018, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": true, "text": "'imagine that the ptr points to some memory address which I want to check in the destructor of some other static class'\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7587/" ]
305,555
<p>How to get the last selected item in a .Net Forms multiselect ListBox? Apparently if I select an item in the listbox and then select another 10 the selected item is the first one.</p> <p>I would like to obtain the last element that I selected/deselected.</p>
[ { "answer_id": 305597, "author": "flesh", "author_id": 27805, "author_profile": "https://Stackoverflow.com/users/27805", "pm_score": 3, "selected": false, "text": "ListItem i = list.SelectedItems[list.SelectedItems.Length-1];\n" }, { "answer_id": 305601, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "SelectedIndexChanged SelectedIndices // for the sake of the example, I defined a single List<int>\nList<int> listBox1_selection = new List<int>();\n\nprivate void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n TrackSelectionChange((ListBox)sender, listBox1_selection);\n}\n\nprivate void TrackSelectionChange(ListBox lb, List<int> selection)\n{\n ListBox.SelectedIndexCollection sic = lb.SelectedIndices;\n foreach (int index in sic)\n if (!selection.Contains(index)) selection.Add(index);\n\n foreach (int index in new List<int>(selection))\n if (!sic.Contains(index)) selection.Remove(index);\n}\n" }, { "answer_id": 1327872, "author": "Khadaji", "author_id": 55520, "author_profile": "https://Stackoverflow.com/users/55520", "pm_score": 0, "selected": false, "text": " private void listBox1_MouseUp(object sender, MouseEventArgs e)\n {\n int jj = listBox1.IndexFromPoint(e.X, e.Y);\n object Test = listBox1.Items[jj];\n object LatestItemSelected;\n if(listBox1.SelectedItems.Contains(Test))\n LatestItemSelected = Test;\n }\n" }, { "answer_id": 10027171, "author": "Aman Ahmed", "author_id": 1315056, "author_profile": "https://Stackoverflow.com/users/1315056", "pm_score": 3, "selected": false, "text": "private void ListBox1_MouseClick(object sender, MouseEventArgs e)\n{\n string s = ListBox1.Items[ListBox1.IndexFromPoint(e.Location)].ToString();\n\n MessageBox.Show(s);\n}\n" }, { "answer_id": 39109899, "author": "Tony", "author_id": 5669693, "author_profile": "https://Stackoverflow.com/users/5669693", "pm_score": -1, "selected": false, "text": " Dim SelectedAry(-1) As Integer\n\n Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged\n Dim LastOne As Integer = -1\n ' First time there no elements in the preserved array\n If SelectedAry.Length = 0 Then\n If ListBox1.SelectedIndex <> -1 Then\n LastOne = 0\n End If\n Else\n 'If the SelectedIndices array is larger than the preserved SelectedAry - means that another one had been selected\n If ListBox1.SelectedIndices.Count >= SelectedAry.Length Then\n For i = 0 To ListBox1.SelectedIndices.Count - 1\n 'Go through both arrays comparing the values until there is a mismatch\n 'This means that the value in the SelectesIndices is the last one to be added\n If ListBox1.SelectedIndices(i) <> SelectedAry(i) Then\n LastOne = i\n Exit For\n End If\n Next\n End If\n End If\n ' Copy the Listbox selectedindices array into the SelectedAry which is preserved for the next selected index change\n ReDim SelectedAry(ListBox1.SelectedIndices.Count)\n For i = 0 To ListBox1.SelectedIndices.Count - 1\n SelectedAry(i) = ListBox1.SelectedIndices(i)\n Next\n ' Display the last one added\n If LastOne >= 0 Then\n Dim FileName As String = txtFolder.Text & \"\\\" & ListBox1.Items(ListBox1.SelectedIndices(LastOne)).ToString\n Display_File(FileName)\n Else\n End If\n End Sub\n" }, { "answer_id": 45033619, "author": "SworDance", "author_id": 8289271, "author_profile": "https://Stackoverflow.com/users/8289271", "pm_score": 0, "selected": false, "text": "int lastSelectedIndex = (int)typeof(ListBox).GetProperty(\"FocusedIndex\",BindingFlags.NonPublic|BindingFlags.Instance).GetValue(myListBox,null);\nSelectedItemType mySelectedItem = myListBox.Items[lastSelectedIndex] as SelectedItemType;\n" }, { "answer_id": 68476503, "author": "Chadee Fouad", "author_id": 6548223, "author_profile": "https://Stackoverflow.com/users/6548223", "pm_score": 0, "selected": false, "text": "Private Sub ListBox2_Change()\n \n 'Preview Doc\n Previous_Selections = Me.Label2.Caption\n \n 'This logic figures out the last selected item if you already have existing selections\n For i = 0 To ListBox2.ListCount - 1\n If ListBox2.Selected(i) Then\n MyItem = ListBox2.List(i)\n \n 'Check if this is a new selection or and old one\n If IsIn(MyItem, Previous_Selections) = False Then\n \n 'This is a new selection\n 'Record new selection for as 'previous' for next time\n For n = 0 To ListBox2.ListCount - 1\n If ListBox2.Selected(n) Then Selections = Selections & ListBox2.List(n) & \", \"\n Next\n \n 'Preview last selected item\n FullPath = Me.ListBox1.Value & \"\\\" & MyItem\n Me.Label2.Caption = Selections\n Call Preview_Document(FullPath)\n Exit Sub\n End If\n End If\n Next i\n \n \n \nEnd Sub\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18631/" ]
305,568
<p>Excuting the line of SQL:</p> <pre><code>SELECT * INTO assignment_20081120 FROM assignment ; </code></pre> <p>against a database in oracle to back up a table called assignment gives me the following ORACLE error: ORA-00905: Missing keyword</p>
[ { "answer_id": 305584, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 5, "selected": false, "text": "ASSIGNMENT ASSIGNMENT_20081120 ASSIGNMENT%ROWTYPE CREATE TABLE assignment_20081120\nAS\nSELECT *\n FROM assignment\n" }, { "answer_id": 1485696, "author": "Uwe Keim", "author_id": 107625, "author_profile": "https://Stackoverflow.com/users/107625", "pm_score": 3, "selected": false, "text": "SELECT...INTO SELECT...INTO SELECT INSERT INTO assignment_20081120 SELECT * FROM assignment;\n SELECT...INTO" }, { "answer_id": 1486431, "author": "Rene", "author_id": 17323, "author_profile": "https://Stackoverflow.com/users/17323", "pm_score": 2, "selected": false, "text": "Declare\n l_variable assignment%rowtype\nbegin\n select *\n into l_variable\n from assignment;\nexception\n when no_data_found then\n dbms_output.put_line('No record avialable')\n when too_many_rows then\n dbms_output.put_line('Too many rows')\nend;\n Declare\n l_variable assignment%rowtype\nbegin\n select *\n into l_variable\n from assignment\n where ID=<my id number>;\nexception\n when no_data_found then\n dbms_output.put_line('No record avialable')\n when too_many_rows then\n dbms_output.put_line('Too many rows')\nend;\n" }, { "answer_id": 4145375, "author": "David", "author_id": 503324, "author_profile": "https://Stackoverflow.com/users/503324", "pm_score": 1, "selected": false, "text": "CREATE TABLE assignment_20101120 AS SELECT * FROM assignment;\n" }, { "answer_id": 46675417, "author": "logixologist", "author_id": 499027, "author_profile": "https://Stackoverflow.com/users/499027", "pm_score": 2, "selected": false, "text": "IN SELECT * FROM TBL_INDEPENTS IN\nJOIN TBL_VOTERS VO on IN.VOTERID = VO.VOTERID\n SELECT ..., ...., IN, ..., .... FROM SOMETABLE\n" }, { "answer_id": 64643722, "author": "ManhKM", "author_id": 7170757, "author_profile": "https://Stackoverflow.com/users/7170757", "pm_score": 1, "selected": false, "text": "CREATE TABLE name_table_bk\nAS\nSELECT *\n FROM name_table;\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
305,574
<p>This question follows on from <a href="https://stackoverflow.com/questions/299114/can-i-search-for-php-class-members-and-methods-with-vim-star-search">this vim search question</a></p> <p>I have a setting in my .vimrc which excludes $ as a valid part of a word:</p> <pre><code>set iskeyword-=$ </code></pre> <p>This works fine for most files but isn't working in PHP. I assume it is being overwritten by a php plugin, but since plugins are loaded after .vimrc I can't work out how to overwrite this setting. I'd prefer not to have to type </p> <pre><code>:set isk-=$ </code></pre> <p>every time I load a PHP file.</p> <p>Any suggestions?</p> <p>( Ubuntu 8.04 / Vim 7.1.138 if it matters )</p> <p><strong>Summary</strong></p> <p>Two excellent answers, thank you!</p> <p>I went with <a href="https://stackoverflow.com/users/18771/tomalak">tomalak</a>'s because it was less effort, and added the following to my ~/.vimrc</p> <pre><code>autocmd FileType php setlocal isk-=$ </code></pre> <p>but thanks also to <a href="https://stackoverflow.com/questions/305574/can-i-stop-settings-in-vimrc-from-being-overwritten-by-plugins#305820">Luc Hermitte</a>. Putting the settings in a ~/vim/after/ftplugin/php.vim file also worked.</p> <p><em>:help autocmd</em> and <em>:help after-directory</em> both helped too</p>
[ { "answer_id": 305627, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "set isk-=$ $VIMRUNTIME\\filetype.vim vimrc au FileType php set isk-=$\n vimrc" }, { "answer_id": 305820, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 3, "selected": false, "text": ":setlocal isk-=$ :verbose set isk :scriptnames" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20074/" ]
305,579
<p>In your practice, how do you effectively track and manage technical debt? </p> <p>Is there a specific metric, like <a href="http://jamesshore.com/Blog/An-Approximate-Measure-of-Technical-Debt.html" rel="nofollow noreferrer">SLOC</a>, that you use?</p> <p>How do you visually display your results to stakeholders and management? </p> <p>What benefits have you seen in the process?</p>
[ { "answer_id": 310809, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "@todo @todo @todo" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
305,591
<p>This seems like something simple, but I can't seem to figure it out! I'm trying to get 2-way data-binding to work on an ASP.net page with a check box as one of the columns. How do I get the updated values (from check boxes) back from the gridview ?????</p> <p>Here is my data type:</p> <pre><code>[Serializable] public class UserRequirements { public string FirstName { get; set; } public string LastName { get; set; } public string UserId { get; set; } public string Email { get; set; } public bool ThingRequired { get; set; } } </code></pre> <p>My markup looks something like this:</p> <pre><code>&lt;form id="form1" method="post" runat="server" &gt; &lt;asp:GridView ID="UserTable" runat="server" AutoGenerateColumns="false" &gt; &lt;Columns&gt; ... &lt;asp:TemplateField HeaderText="Required ?"&gt; &lt;ItemTemplate&gt; &lt;asp:CheckBox id="chkBox1" runat="server" on Text ="Required" checked='&lt;%# DataBinder.Eval(Container.DataItem,"ThingRequired") %&gt;'&gt; &lt;/asp:CheckBox&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;asp:Button id="thebutton" Text="Save Changes" OnClick="UpdateRequirements" runat="server" CausesValidation=false /&gt; &lt;/form&gt; </code></pre> <p>My code behind looks something like this:</p> <pre><code> List&lt;UserRequirements &gt; _userList = new List&lt;UserRequirements &gt;(); protected void Page_Load(object sender, EventArgs e) { _userList = data_layer.GetUserRequirments(); this.UserTable.DataSource = _userList; this.UserTable.DataBind(); } </code></pre> <p>Eventually, I will call something like this, but I don't know where this should go or how to get the values back from the gridview:</p> <pre><code>void UpdateRequirements(object sender, EventArgs e) { _userList = ???????????? // How do I get the data? data_layer.UpdateUserRequirements( _userList ); } </code></pre>
[ { "answer_id": 305617, "author": "MysticSlayer", "author_id": 28139, "author_profile": "https://Stackoverflow.com/users/28139", "pm_score": 2, "selected": false, "text": " if (chkBx != null && chkBx.Checked)\n {\n /// put your code here\n }\n }\n" }, { "answer_id": 305645, "author": "flesh", "author_id": 27805, "author_profile": "https://Stackoverflow.com/users/27805", "pm_score": 1, "selected": false, "text": "protected void OnCheckedChanged(object sender, EventArgs e)\n{ \n CheckBox c = (CheckBox)sender as CheckBox; \n string checkBoxId = c.ID; \n bool checkBoxValue = c.Checked;\n //update database\n}\n <asp:CheckBox ID=\"<%# Eval('Id') %>\" />\n foreach (UserRequirement item in Requirements)\n {\n Control c = grid.FindControl(item.Id);\n CheckBox cbx = c as CheckBox;\n if (cbx != null)\n {\n bool value = cbx.Checked;\n //update db\n }\n }\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5208/" ]
305,605
<p>I'm writing a simple .bat file and I've run into some weird behavior. There are a couple places where I have to do a simple if/else, but the code inside the blocks don't seem to be working correctly.</p> <p>Here's a simple case that demonstrates the error:</p> <pre><code>@echo off set MODE=FOOBAR if "%~1"=="" ( set MODE=all echo mode: %MODE% ) else ( set MODE=%~1 echo mode: %MODE% ) echo mode: %MODE% </code></pre> <p>The output I'm getting is:</p> <pre><code>C:\&gt;test.bat test mode: FOOBAR mode: test </code></pre> <p>Why is the echo inside the code block not getting the new value of the variable? In the actual code I'm writing I need to build a few variables and reference them within the scope of the if/else. I could switch this to use labels and gotos instead of an if/else, but that doesn't seem nearly as clean.</p> <p>What causes this behavior? Is there some kind of limit on variables within code blocks?</p>
[ { "answer_id": 305640, "author": "user33675", "author_id": 33675, "author_profile": "https://Stackoverflow.com/users/33675", "pm_score": 6, "selected": true, "text": " set VAR=before\n if \"%VAR%\" == \"before\" (\n set VAR=after\n if \"%VAR%\" == \"after\" @echo If you see this, it worked\n )\n set LIST=\nfor %i in (*) do set LIST=%LIST% %i\necho %LIST%\n for %i in (*) do set LIST= %i\n set VAR=before\nif \"%VAR%\" == \"before\" (\n set VAR=after\n if \"!VAR!\" == \"after\" @echo If you see this, it worked\n)\n\nset LIST=\nfor %i in (*) do set LIST=!LIST! %i\necho %LIST%\n" }, { "answer_id": 305653, "author": "Harry Lime", "author_id": 21590, "author_profile": "https://Stackoverflow.com/users/21590", "pm_score": -1, "selected": false, "text": "set MODE=FOOBAR\n" }, { "answer_id": 70235162, "author": "Andry", "author_id": 2672125, "author_profile": "https://Stackoverflow.com/users/2672125", "pm_score": 0, "selected": false, "text": "Conditional block (...) @echo off\n\nset \"MODE=\"\n(\n (\n set MODE=all\n echo MODE=%MODE%\n )\n echo MODE=%MODE%\n)\necho MODE=%MODE%\n call @echo off\n\nset \"MODE=\"\n(\n (\n set MODE=all\n call echo MODE=%%MODE%%\n )\n)\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409/" ]
305,611
<p>Does anyone know of any C container libraries? I am looking for something which gives standard implementations of linked lists, arrays, hash tables etc, much in the same way as the C++ STL does. Key concerns are:</p> <ol> <li>Client code should be able to create containers for multiple different data types without modifying the library.</li> <li>The interface for creating and using the containers should be intuitive.</li> </ol>
[ { "answer_id": 902923, "author": "user105991", "author_id": 105991, "author_profile": "https://Stackoverflow.com/users/105991", "pm_score": 2, "selected": false, "text": "#include \"queue.h\"" }, { "answer_id": 902960, "author": "Lear", "author_id": 80223, "author_profile": "https://Stackoverflow.com/users/80223", "pm_score": 4, "selected": false, "text": "void*" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23435/" ]
305,615
<p>When measuring network latency (time ack received - time msg sent) in any protocol over TCP, what timer would you recommend to use and why? What resolution does it have? What are other advantages/disadvantages?</p> <p>Optional: how does it work?</p> <p>Optional: what timer would you NOT use and why?</p> <p>I'm looking mostly for Windows / C++ solutions, but if you'd like to comment on other systems, feel free to do so.</p> <p>(Currently we use GetTickCount(), but it's not a very accurate timer.)</p>
[ { "answer_id": 306101, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 4, "selected": true, "text": "#include <sys/time.h>\n\nint main()\n{\n timespec ts;\n // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD\n clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22724/" ]
305,637
<p>I need to signal a running application (Windows service) when certain things happen in SQL Server (2005). Is there a possibility to send a message from a trigger to an external application on the same system?</p>
[ { "answer_id": 305660, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 1, "selected": false, "text": "CREATE PROC shutdown10\nAS\nEXEC xp_cmdshell 'net send /domain:SQL_USERS ''SQL Server shutting down \n in 10 minutes. No more connections allowed.', no_output\nEXEC xp_cmdshell 'net pause sqlserver'\nWAITFOR DELAY '00:05:00'\nEXEC xp_cmdshell 'net send /domain: SQL_USERS ''SQL Server shutting down \n in 5 minutes.', no_output\nWAITFOR DELAY '00:04:00'\nEXEC xp_cmdshell 'net send /domain:SQL_USERS ''SQL Server shutting down \n in 1 minute. Log off now.', no_output\nWAITFOR DELAY '00:01:00'\nEXEC xp_cmdshell 'net stop sqlserver', no_output\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
305,647
<p>My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.</p> <p>What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?</p>
[ { "answer_id": 305662, "author": "Tim Pietzcker", "author_id": 20670, "author_profile": "https://Stackoverflow.com/users/20670", "pm_score": 1, "selected": false, "text": "tempfile tempfile.mkstemp() tempfile" }, { "answer_id": 305763, "author": "Tim Pietzcker", "author_id": 20670, "author_profile": "https://Stackoverflow.com/users/20670", "pm_score": 2, "selected": false, "text": "%APPDATA% %ALLUSERSPROFILE% import os\napp_path = os.getenv(\"APPDATA\") + \"\\\\MyApplicationData\"\ntry:\n os.mkdir(app_path)\nexcept WindowsError:\n # already exists\n" }, { "answer_id": 305996, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 1, "selected": false, "text": "wx.StandardPaths" }, { "answer_id": 68076330, "author": "Mike T", "author_id": 327026, "author_profile": "https://Stackoverflow.com/users/327026", "pm_score": 1, "selected": false, "text": "import os\nfrom appdirs import user_cache_dir\n\ndirname = user_cache_dir(\"AppName\", \"Author\", \"v1.0\")\n# C:\\Users\\username\\AppData\\Local\\Author\\AppName\\Cache\\v1.0\n\n# create it, if it doesn't exist\nos.makedirs(dirname, exist_ok=True)\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17498/" ]
305,651
<p>I've seen this syntax a couple times now, and it's beginning to worry me,</p> <p>For example:</p> <pre><code>iCalendar iCal = new iCalendar(); Event evt = iCal.Create&lt;Event&gt;(); </code></pre>
[ { "answer_id": 305655, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "public T Create<T>()\n List<Event> list = new List<Event>();\n Create public T Copy<T>(T original)\n Copy(someEvent);\n Copy<Event>(someEvent);\n" }, { "answer_id": 305675, "author": "mmx", "author_id": 33708, "author_profile": "https://Stackoverflow.com/users/33708", "pm_score": 1, "selected": false, "text": "return-type MethodName<type-parameter-list>(parameter-list)\n Array.ForEach(myArray, Console.WriteLine);\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31765/" ]
305,665
<p>Using C# and the .Net framework 2.0. I have an MDI application and need to handle dragover/dragdrop events. I have a list docked to the left on my application and would like to be able to drag an item from the list and drop it in the MDI client area and have the correct MDI child for the item open. I can't seem to figure out where to attach the handler. I've tried attaching to the main form's events and the MdiClient that is part of the form, but neither event handler seems to get called when I expect them to. </p> <p>I'm also using an Infragistics Tabbed MDI Manager, so I'm not sure if that's affecting it.</p>
[ { "answer_id": 4013546, "author": "Shlomi Loubaton", "author_id": 428831, "author_profile": "https://Stackoverflow.com/users/428831", "pm_score": 0, "selected": false, "text": "...\nusing System.Linq;\n...\n\npublic partial class Form1 : Form\n{\n MdiClient mdi_client;\n public Form1()\n {\n InitializeComponent();\n mdi_client = this.Controls.OfType<MdiClient>().FirstOrDefault();\n mdi_client.AllowDrop = true;\n mdi_client.DragEnter += Form1_DragEnter;\n mdi_client.DragDrop += Form1_DragDrop;\n }\n\n private void Form1_DragDrop(object sender, DragEventArgs e)\n {\n myForm m = new myForm();\n m.Text = (string)e.Data.GetData(typeof(string));\n m.MdiParent = this;\n m.Show();\n m.Location = mdi_client.PointToClient(new Point(e.X, e.Y));\n }\n\n private void Form1_DragEnter(object sender, DragEventArgs e)\n {\n e.Effect = DragDropEffects.All;\n }\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33724/" ]
305,673
<p>Essentially, I have to get a flat file into a database. The flat files come in with the first two characters on each line indicating which type of record it is.</p> <p>Do I create a class for each record type with properties matching the fields in the record? Should I just use arrays?</p> <p>I want to load the data into some sort of data structure before saving it in the database so that I can use unit tests to verify that the data was loaded correctly.</p> <p>Here's a sample of what I have to work with (BAI2 bank statements):</p> <pre><code>01,121000358,CLIENT,050312,0213,1,80,1,2/ 02,CLIENT-STANDARD,BOFAGB22,1,050311,2359,,/ 03,600812345678,GBP,fab1,111319005,,V,050314,0000/ 88,fab2,113781251,,V,050315,0000,fab3,113781251,,V,050316,0000/ 88,fab4,113781251,,V,050317,0000,fab5,113781251,,V,050318,0000/ 88,010,0,,,015,0,,,045,0,,,100,302982205,,,400,302982205,,/ 16,169,57626223,V,050311,0000,102 0101857345,/ 88,LLOYDS TSB BANK PL 779300 99129797 88,TRF/REF 6008ABS12300015439 88,102 0101857345 K BANK GIRO CREDIT 88,/IVD-11 MAR 49,1778372829,90/ 98,1778372839,1,91/ 99,1778372839,1,92 </code></pre>
[ { "answer_id": 305692, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": true, "text": "record.ClientReference\n record[0]\n" }, { "answer_id": 305741, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 1, "selected": false, "text": " public void setField2(String s)\n {\n if (field1==88 && s.equals ...\n\n else if (field2==22 && s \n }\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
305,688
<p>I'm pretty sure the answer to this is no. I know that I can write</p> <blockquote> <p>if lcase(strFoo) = lcase(request.querystring("x")) then...</p> </blockquote> <p>or use inStr, but I just want to check there isn't some undocumented setting buried in the registry or somewhere that makes the content of VBScript strings behave consistently with the rest of the scripting language!</p> <p>Thanks Dan</p>
[ { "answer_id": 305753, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 3, "selected": false, "text": "Dim dicList : Set dicList = CreateObject(\"Scripting.Dictionary\")\nDim strTest\n\ndicList.CompareMode = 0 ' Binary ie case sensitive\ndicList.Add \"FOO\", \"\"\ndicList.Add \"BAR\", \"\"\ndicList.Add \"Wombat\", \"\"\n\nstrTest = \"foo\"\nWScript.Echo CStr(dicList.Exists(strTest))\n\nSet dicList = CreateObject(\"Scripting.Dictionary\")\ndicList.CompareMode = 1 ' Text ie case insensitive\ndicList.Add \"FOO\", \"\"\ndicList.Add \"BAR\", \"\"\ndicList.Add \"Wombat\", \"\"\n\nstrTest = \"foo\"\nWScript.Echo CStr(dicList.Exists(strTest))\n" }, { "answer_id": 310643, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 4, "selected": false, "text": "StrComp vbTextCompare If StrComp(strFoo, Request.QueryString(\"x\"), vbTextCompare) = 0 Then ...\n LCase UCase StrComp" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21203/" ]
305,690
<p>I am working on a tool where I need to convert string values to their proper object types. E.g. convert a string like <code>"2008-11-20T16:33:21Z"</code> to a <code>DateTime</code> value. Numeric values like <code>"42"</code> and <code>"42.42"</code> must be converted to an <code>Int32</code> value and a <code>Double</code> value respectively. </p> <p>What is the best and most efficient approach to detect if a string is an integer or a number? Are <code>Int32.TryParse</code> or <code>Double.TryParse</code> the way to go? </p>
[ { "answer_id": 305703, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "switch TypeConverter DateTime foo = new DateTime(2008, 11, 20);\n TypeConverter converter = TypeDescriptor.GetConverter(foo);\n string s = converter.ConvertToInvariantString(foo);\n object val = converter.ConvertFromInvariantString(s);\n" }, { "answer_id": 305707, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 4, "selected": false, "text": "Int.TryParse Double.TryParse Regex.IsMatch(\"^\\d+$\")" }, { "answer_id": 305839, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 0, "selected": false, "text": "public static class ConvertFromString\n{\n public static T? ConvertTo<T>(this String numberToConvert) where T : struct\n {\n T? returnValue = null;\n\n MethodInfo neededInfo = GetCorrectMethodInfo(typeof(T));\n if (neededInfo != null && !numberToConvert.IsNullOrEmpty())\n {\n T output = default(T);\n object[] paramsArray = new object[2] { numberToConvert, output };\n returnValue = new T();\n\n object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);\n\n if (returnedValue is Boolean && (Boolean)returnedValue)\n {\n returnValue = (T)paramsArray[1];\n }\n else\n {\n returnValue = null;\n } \n }\n\n return returnValue;\n }\n}\n private static MethodInfo GetCorrectMethodInfo(Type typeToCheck)\n{\n\n MethodInfo returnValue = someCache.Get(typeToCheck.FullName);\n\n if(returnValue == null)\n {\n Type[] paramTypes = new Type[2] { typeof(string), typeToCheck.MakeByRefType() };\n returnValue = typeToCheck.GetMethod(\"TryParse\", paramTypes);\n if (returnValue != null)\n {\n CurrentCache.Add(typeToCheck.FullName, returnValue);\n }\n }\n\n return returnValue;\n}\n decimal? converted = someString.ConvertTo<decimal>();\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27393/" ]
305,780
<p>I am porting some queries from Access to T-SQL and those who wrote the queries used the Avg aggregate function on datetime columns. This is not supported in T-SQL and I can understand why - it doesn't make sense. What is getting averaged?</p> <p>So I was about to start reverse engineering what Access does when it aggregates datetime using Avg, but thought I would throw the question out here first.</p>
[ { "answer_id": 305869, "author": "Scott Ivey", "author_id": 36297, "author_profile": "https://Stackoverflow.com/users/36297", "pm_score": 3, "selected": true, "text": "select AverageDate = cast(avg(cast(MyDateColumn as decimal(20, 10))) as datetime)\nfrom MyTable\n" }, { "answer_id": 306484, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "SELECT AVG(datetime_column - TIMESTAMP '2000-01-01 00:00:00.000000') +\n TIMESTAMP '2000-01-01 00:00:00.000000'\n FROM table_containing_datetime_column;\n CREATE TEMP TABLE table_containing_datetime_column\n(\n datetime_column DATETIME YEAR TO FRACTION(5) NOT NULL\n);\n\nINSERT INTO table_containing_datetime_column VALUES('2008-11-19 12:12:12.00000');\nINSERT INTO table_containing_datetime_column VALUES('2008-11-19 22:22:22.00000');\n\nSELECT AVG(datetime_column - DATETIME(2000-01-01 00:00:00.00000) YEAR TO FRACTION(5)) +\n DATETIME(2000-01-01 00:00:00.00000) YEAR TO FRACTION(5)\nFROM table_containing_datetime_column;\n 2008-11-19 17:17:17.00000\n" }, { "answer_id": 980321, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 1, "selected": false, "text": "DATETIME FLOAT DOUBLE FLOAT8 IEEEDOUBLE NUMBER DATETIME FLOAT DATETIME SELECT CDBL(CDATE('9999-12-31 23:59:59'))\n SELECT CDATE(CDBL(2958465.9999999997))\n SELECT CDATE(CDBL(2958465.9999999998))\n DATETIME FLOAT SELECT CAST(AVG(CAST(MyDateTimeColumn AS FLOAT)) AS DATETIME)\n from MyTable\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22355/" ]
305,787
<p>I have a series of Eclipse projects containing a number of plugins and features that are checked into CVS. I now need to run an automated build of these plugins. Ideally I'd like to do it without having to hardcode large numbers of Eclipse library locations by hand, which has been the problem with the automatically generated Ant files that Eclipse provides. The build also needs to run headlessly.</p> <p>Does anyone have experience of this sort of set-up with Eclipse, and recommendations for how to achieve it?</p>
[ { "answer_id": 305813, "author": "mendicant", "author_id": 1800, "author_profile": "https://Stackoverflow.com/users/1800", "pm_score": 1, "selected": false, "text": "<property file=\"eclipse.libraries.properties\" />\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39368/" ]
305,797
<p>The program that I am currently assigned to has a requirement that I copy the contents of a table to a backup table, prior to the real processing.</p> <p>During code review, a coworker pointed out that</p> <pre><code>INSERT INTO BACKUP_TABLE SELECT * FROM PRIMARY_TABLE </code></pre> <p>is unduly risky, as it is possible for the tables to have different columns, and different column orders.</p> <p>I am also under the constraint to not create/delete/rename tables. ~Sigh~</p> <p>The columns in the table are expected to change, so simply hard-coding the column names is not really the solution I am looking for.</p> <p>I am looking for ideas on a reasonable non-risky way to get this job done.</p>
[ { "answer_id": 305812, "author": "gx.", "author_id": 21580, "author_profile": "https://Stackoverflow.com/users/21580", "pm_score": 0, "selected": false, "text": "CREATE TABLE secondary_table AS SELECT * FROM primary_table;\n CREATE TABLE secondary_table AS SELECT * FROM primary_table LIMIT 1;\nINSERT INTO secondary_table SELECT * FROM primary_table;\n" }, { "answer_id": 305831, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 1, "selected": false, "text": "INSERT INTO backup_table( col1, col2, col3, ... colN )\n SELECT col1, col2, col3, ..., colN\n FROM primary_table\n" }, { "answer_id": 305840, "author": "Jim Hudson", "author_id": 8051, "author_profile": "https://Stackoverflow.com/users/8051", "pm_score": 4, "selected": true, "text": "create table backup_table as select * from primary_table;\n insert into backup_table (<list of columns>) select <list of columns> from primary_table;\n" }, { "answer_id": 305848, "author": "m0j0", "author_id": 31319, "author_profile": "https://Stackoverflow.com/users/31319", "pm_score": 2, "selected": false, "text": "DELETE FROM TABLE;" }, { "answer_id": 1578155, "author": "Michael Dillon", "author_id": 189361, "author_profile": "https://Stackoverflow.com/users/189361", "pm_score": 1, "selected": false, "text": "INSERT INTO BACKUP_TABLE\nSELECT *\nFROM PRIMARY_TABLE\n INSERT INTO BACKUP_TABLE (<list of columns>) \nSELECT <list of columns> \nFROM PRIMARY_TABLE\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
305,805
<p>I am developing some school grading software and decided to use Github to host the project. After building some code on my Ubuntu box I pushed it to Github and then cloned it down to my MacBook Pro. After editing the code on the MBP I pushed it back to Github. The next morning I tried to update my repo on the Ubuntu box with a <code>git pull</code> and it gave me all kinds of trouble.</p> <p>Whats the best way to work in this situation? I don't want to fork my own repo and I don't really want to send myself emails or pull requests. Why can't I just treat Github like a master and push/pull from it onto all of my personal repos on different computers?</p>
[ { "answer_id": 307742, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 4, "selected": true, "text": "git pull git pull # GitHub gives you that instruction, you've already done that\n# git remote add origin git@github.com:user_name/repo_name.git\n\n# GitHub doesn't specify the following instructions\ngit config branch.master.remote origin\ngit config branch.master.merge refs/heads/master\n git pull" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21512/" ]
305,817
<p>I want to be able to read from an unsorted source text file (one record in each line), and insert the line/record into a destination text file by specifying the line number where it should be inserted.</p> <p>Where to insert the line/record into the destination file will be determined by comparing the incoming line from the incoming file to the already ordered list in the destination file. (The destination file will start as an empty file and the data will be sorted and inserted into it one line at a time as the program iterates over the incoming file lines.)</p> <p>Incoming File Example:</p> <pre><code>1 10/01/2008 line1data 2 11/01/2008 line2data 3 10/15/2008 line3data </code></pre> <p>Desired Destination File Example:</p> <pre><code>2 11/01/2008 line2data 3 10/15/2008 line3data 1 10/01/2008 line1data </code></pre> <p>I could do this by performing the sort in memory via a linked list or similar, but I want to allow this to scale to very large files. (And I am having fun trying to solve this problem as I am a C++ newbie :).)</p> <p>One of the ways to do this may be to open 2 file streams with <code>fstream</code> (1 in and 1 out, or just 1 in/out stream), but then I run into the difficulty that it's difficult to find and search the file position because it seems to depend on absolute position from the start of the file rather than line numbers :).</p> <p>I'm sure problems like this have been tackled before, and I would appreciate advice on how to proceed in a manner that is good practice.</p> <p>I'm using Visual Studio 2008 Pro C++, and I'm just learning C++.</p>
[ { "answer_id": 306003, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "sort cat <file> | sort -k 2,2 > <file2> ; mv <file2> <file>\n cat <file> | sort -k 2,2 > <file>\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39360/" ]
305,835
<p>I'm trying to understand the differences between Assembly.Load and Assembly.ReflectionOnlyLoad.</p> <p>In the code below I am attempting to find all of the objects in a given assembly that inherit from a given interface:</p> <pre><code>var myTypes = new List&lt;Type&gt;(); var assembly = Assembly.Load("MyProject.Components"); foreach (var type in assembly.GetTypes()) { if (type.GetInterfaces().Contains(typeof(ISuperInterface))) { myTypes.Add(type); } } </code></pre> <p>This code works fine for me, but I was doing some research into other possibly better alternatives and came across Assembly.ReflectionOnlyLoad() method.</p> <p>I assumed that since I'm not loading or executing any of the objects, essentially just querying on their definitions that I could use ReflectionOnlyLoad for a slight performance increase...</p> <p>But it turns out that when I change Assembly.Load to Assembly.ReflectionOnlyLoad I get the following error when it calls assembly.GetTypes():</p> <blockquote> <pre><code>System.Reflection.ReflectionTypeLoadException: </code></pre> <p>Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.</p> </blockquote> <p>I assumed that the above code was JUST doing reflection and "looking at" the library... but is this some sort of instance of the Heisenberg Uncertainty Principle whereby looking at the library and the objects in it is actually attempting to instantiate them in some way?</p> <p>Thanks, Max</p>
[ { "answer_id": 306096, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 6, "selected": true, "text": "LoaderExceptions AppDomain.ReflectionOnlyAssemblyResolve" }, { "answer_id": 306293, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 3, "selected": false, "text": "public class MyBase\n{\n public void Foo() { }\n}\n public class MySubclass : MyBase\n{\n}\n" }, { "answer_id": 662256, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 2, "selected": false, "text": "ReflectionOnlyLoad() InvalidOperationException" }, { "answer_id": 49253700, "author": "Gerrie Pretorius", "author_id": 505558, "author_profile": "https://Stackoverflow.com/users/505558", "pm_score": 1, "selected": false, "text": "Assembly.Load AppDomain Assembly.ReflectionOnlyLoad AppDomain public void AssemblyLoadTest(string assemblyToLoad)\n{\n var initialAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //4\n\n Assembly.ReflectionOnlyLoad(assemblyToLoad);\n var reflectionOnlyAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //4\n\n //Shows that assembly is NOT loaded in to AppDomain with Assembly.ReflectionOnlyLoad\n Assert.AreEqual(initialAppDomainAssemblyCount, reflectionOnlyAppDomainAssemblyCount); // 4 == 4\n\n Assembly.Load(assemblyToLoad);\n var loadAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //5\n\n //Shows that assembly is loaded in to AppDomain with Assembly.Load\n Assert.AreNotEqual(initialAppDomainAssemblyCount, loadAppDomainAssemblyCount); // 4 != 5\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29662/" ]
305,843
<p>I have a unit test that works fine locally but when uploaded to TeamCity build server fails with "The process cannot access the file because it is being used by another process."</p> <ol> <li>Before I do anything in the Test I check in the setup if the file exists and if so try to delete it. This fails with the same error message as above</li> <li>When wriitng the file, I close the writer then dispose of it which I believe should get rid of any resources.</li> </ol> <p>So I have a couple queries </p> <ol> <li>Has anyone had similar issues and manage to get around them</li> <li>How can find out programticall what process has selfishly locked the file!!!</li> </ol> <p>Cheers</p>
[ { "answer_id": 305847, "author": "Mark", "author_id": 37923, "author_profile": "https://Stackoverflow.com/users/37923", "pm_score": 2, "selected": false, "text": "Find Handle or DLL" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
305,849
<p>I usually, almost without thinking anymore, use forward declarations so that I won't have to include headers. Something along this example:</p> <pre><code>//----------------------- // foo.h //----------------------- class foo { foo(); ~foo(); }; //----------------------- // bar.h //----------------------- class foo; // forward declaration class bar { bar(); ~bar(); foo* foo_pointer; }; </code></pre> <p>Some developers like to use this method to avoid problems with inclusion circles. I rather use it to minimize the overhead in extensive inclusion hierarchies, an important part of physical design (for larger projects in particular).</p> <p>However, in some cases I really like to declare members as normal objects instead of pointers to benefit from the automatic construction/destruction mechanism. This leads to the problem that forward declarations can't be used anymore, since the compiler needs the class definition in such case, eg:</p> <pre><code>//----------------------- // foo.h //----------------------- class foo { foo(); ~foo(); }; //----------------------- // bar.h //----------------------- class foo; // Not enough given the way we declare "foo_object".. #include "foo.h" // ..instead this is required class bar { bar(); ~bar(); foo foo_object; }; </code></pre> <p>So, I would be happy if anyone knows an alternative language construct which can be used here so that I can declare "foo_object" as shown in the example, but without including its header.</p> <p>Regards</p> <p>/Robert</p>
[ { "answer_id": 305862, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "// bar.h\nclass foo;\n\nclass bar {\n foo& foo_;\n\npublic:\n bar();\n ~bar();\n};\n\n// bar.cc\nbar::bar() : foo_(*new foo)\n{\n // ...\n}\n\nbar::~bar()\n{\n // ...\n delete &foo_;\n}\n" }, { "answer_id": 305961, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": true, "text": "//-----------------------\n// bar.h\n//-----------------------\n\n#include <memory>\nclass foo; // Not enough given the way we declare \"foo_object\"..\n\nclass bar\n{\npublic:\n bar();\n ~bar();\n\n foo &foo_object() { return *foo_ptr; }\n const foo &foo_object() const { return *foo_ptr; }\n\nprivate:\n auto_ptr<foo> foo_ptr;\n};\n #include <iostream>\nusing namespace std;\n\nclass Foo;\n\ntemplate <typename T>\nclass DefaultConstuctorPtr\n{\n T *ptr;\n void operator =(const DefaultConstuctorPtr &);\n DefaultConstuctorPtr(const DefaultConstuctorPtr &);\n\npublic:\n DefaultConstuctorPtr() : ptr(new T()) {}\n ~DefaultConstuctorPtr() { delete ptr; }\n\n T *operator *() { return ptr; }\n const T *operator *() const { return ptr; }\n};\n\nclass Bar\n{\n DefaultConstuctorPtr<Foo> foo_ptr;\npublic:\n Bar() {} // The compiler should really need Foo() to be defined here?\n};\n\nclass Foo\n{\npublic:\n Foo () { cout << \"Constructing foo\"; }\n};\n\nint main()\n{\n Bar bar;\n}\n" }, { "answer_id": 306016, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 0, "selected": false, "text": "myAuto template<class T>\nclass myAuto\n{\n private:\n T * obj;\n\n public:\n myAuto() : obj(new T) { }\n ~myAuto() { delete obj; }\n T& object() { return *obj; }\n T* operator ->() { return obj; }\n}; // foo.h:\nclass foo\n{\n public:\n foo();\n ~foo();\n void some_foo_func();\n}; //bar.h:\nclass foo;\nclass bar\n{\n public:\n bar();\n ~bar();\n myAuto<foo> foo_object;\n};\n //main.cc:\n#include \"foo.h\"\n#include \"bar.h\"\n\nint main()\n{\n bar a_bar;\n\n a_bar.foo_object->some_foo_func();\n\n return 0;\n}" }, { "answer_id": 306028, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "template<typename Type>\nstruct member {\n boost::shared_ptr<Type> ptr;\n member(): ptr(new Type) { }\n};\n\nstruct foo;\nstruct bar {\n bar();\n ~bar();\n\n // automatic management for m\n member<foo> m;\n};\n" }, { "answer_id": 306296, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 0, "selected": false, "text": "//-----------------------\n// foo.h\n//-----------------------\nclass foo\n{\n foo();\n ~foo();\n};\n\n\n//-----------------------\n// bar.h\n//-----------------------\n\nclass foo;\n\nclass bar\n{\nprivate:\n struct impl;\n boost::shared_ptr<impl> impl_;\npublic:\n bar();\n\n const foo& get_foo() const;\n};\n\n//-----------------------\n// bar.cpp\n//-----------------------\n#include \"bar.h\"\n#include \"foo.h\"\n\nstruct bar::impl\n{\n foo foo_object;\n ...\n}\n\nbar::bar() :\nimpl_(new impl)\n{\n}\n\nconst foo& bar::get_foo() const\n{\n return impl_->foo_object;\n}\n" }, { "answer_id": 308366, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "this this erase(this)" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
305,856
<p>I have a project where multiple developers are using a copy of the same windows Virtual PC image (W2K3 SE SP2). Because our solution is tied to the machine-name (less than ideal, i know) all of the developers have the same machine name.</p> <p>We use a VPN to connect to a remote system, upon connection we get the "Windows Error: A duplicate name exists on the network" error.</p> <p>Since all development is happening locally, we're not dependent on other machines connecting to us -- only outbound connections.</p> <p>I know it's best practice to change the machine name, but what's the reasoning behind this? What impact would this have?</p>
[ { "answer_id": 305862, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "// bar.h\nclass foo;\n\nclass bar {\n foo& foo_;\n\npublic:\n bar();\n ~bar();\n};\n\n// bar.cc\nbar::bar() : foo_(*new foo)\n{\n // ...\n}\n\nbar::~bar()\n{\n // ...\n delete &foo_;\n}\n" }, { "answer_id": 305961, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": true, "text": "//-----------------------\n// bar.h\n//-----------------------\n\n#include <memory>\nclass foo; // Not enough given the way we declare \"foo_object\"..\n\nclass bar\n{\npublic:\n bar();\n ~bar();\n\n foo &foo_object() { return *foo_ptr; }\n const foo &foo_object() const { return *foo_ptr; }\n\nprivate:\n auto_ptr<foo> foo_ptr;\n};\n #include <iostream>\nusing namespace std;\n\nclass Foo;\n\ntemplate <typename T>\nclass DefaultConstuctorPtr\n{\n T *ptr;\n void operator =(const DefaultConstuctorPtr &);\n DefaultConstuctorPtr(const DefaultConstuctorPtr &);\n\npublic:\n DefaultConstuctorPtr() : ptr(new T()) {}\n ~DefaultConstuctorPtr() { delete ptr; }\n\n T *operator *() { return ptr; }\n const T *operator *() const { return ptr; }\n};\n\nclass Bar\n{\n DefaultConstuctorPtr<Foo> foo_ptr;\npublic:\n Bar() {} // The compiler should really need Foo() to be defined here?\n};\n\nclass Foo\n{\npublic:\n Foo () { cout << \"Constructing foo\"; }\n};\n\nint main()\n{\n Bar bar;\n}\n" }, { "answer_id": 306016, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 0, "selected": false, "text": "myAuto template<class T>\nclass myAuto\n{\n private:\n T * obj;\n\n public:\n myAuto() : obj(new T) { }\n ~myAuto() { delete obj; }\n T& object() { return *obj; }\n T* operator ->() { return obj; }\n}; // foo.h:\nclass foo\n{\n public:\n foo();\n ~foo();\n void some_foo_func();\n}; //bar.h:\nclass foo;\nclass bar\n{\n public:\n bar();\n ~bar();\n myAuto<foo> foo_object;\n};\n //main.cc:\n#include \"foo.h\"\n#include \"bar.h\"\n\nint main()\n{\n bar a_bar;\n\n a_bar.foo_object->some_foo_func();\n\n return 0;\n}" }, { "answer_id": 306028, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "template<typename Type>\nstruct member {\n boost::shared_ptr<Type> ptr;\n member(): ptr(new Type) { }\n};\n\nstruct foo;\nstruct bar {\n bar();\n ~bar();\n\n // automatic management for m\n member<foo> m;\n};\n" }, { "answer_id": 306296, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 0, "selected": false, "text": "//-----------------------\n// foo.h\n//-----------------------\nclass foo\n{\n foo();\n ~foo();\n};\n\n\n//-----------------------\n// bar.h\n//-----------------------\n\nclass foo;\n\nclass bar\n{\nprivate:\n struct impl;\n boost::shared_ptr<impl> impl_;\npublic:\n bar();\n\n const foo& get_foo() const;\n};\n\n//-----------------------\n// bar.cpp\n//-----------------------\n#include \"bar.h\"\n#include \"foo.h\"\n\nstruct bar::impl\n{\n foo foo_object;\n ...\n}\n\nbar::bar() :\nimpl_(new impl)\n{\n}\n\nconst foo& bar::get_foo() const\n{\n return impl_->foo_object;\n}\n" }, { "answer_id": 308366, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "this this erase(this)" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30809/" ]
305,860
<p>What do you think is the best way to implement an interactive grid similar to a Sudoku board for a native iPhone application? I did not see an object to fill this need in the SDK.</p> <p>Should I make a custom control for an individual cell, then initialize as many of them as I need in a grid form?</p> <p><a href="https://i.stack.imgur.com/o9CSk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o9CSk.jpg" alt="Sudoku grid"></a><br> <sub>(source: <a href="http://www.sudoku.4thewww.com/Grids/grid.jpg" rel="nofollow noreferrer">4thewww.com</a>)</sub> </p> <p>Any and all comments are welcome. Thanks!</p>
[ { "answer_id": 306149, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "hidden" }, { "answer_id": 306152, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 2, "selected": false, "text": "UIView" }, { "answer_id": 11272338, "author": "Alex Gray", "author_id": 547214, "author_profile": "https://Stackoverflow.com/users/547214", "pm_score": 1, "selected": false, "text": "int % int - (void)awakeFromNib {\n self.wantsLayer = YES;\n CALayer *grid = self.layer;\n grid.backgroundColor = CGColorCreateGenericRGB(0.1, 0.1, 0.4, .8);\n grid.layoutManager = [CAConstraintLayoutManager layoutManager]; \n int rows = 8; int columns = 8;\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < columns; c++) {\n CALayer *cell = [CALayer layer];\n cell.borderColor = CGColorCreateGenericGray(0.8, 0.8);\n cell.borderWidth = 1; cell.cornerRadius = 4;\n cell.name = [NSString stringWithFormat:@\"%u@%u\", c, r];\n [cell addConstraint:\n [CAConstraint constraintWithAttribute: kCAConstraintWidth\n relativeTo: @\"superlayer\"\n attribute: kCAConstraintWidth\n scale: 1.0 / columns offset: 0]];\n [cell addConstraint:\n [CAConstraint constraintWithAttribute: kCAConstraintHeight\n relativeTo: @\"superlayer\"\n attribute: kCAConstraintHeight\n scale: 1.0 / rows offset: 0]];\n [cell addConstraint:\n [CAConstraint constraintWithAttribute: kCAConstraintMinX\n relativeTo: @\"superlayer\"\n attribute: kCAConstraintMaxX\n scale: c / (float)columns offset: 0]];\n [cell addConstraint:\n [CAConstraint constraintWithAttribute: kCAConstraintMinY\n relativeTo: @\"superlayer\"\n attribute: kCAConstraintMaxY\n scale: r / (float)rows offset: 0]];\n [grid addSublayer:cell];\n} } }\n" }, { "answer_id": 12820704, "author": "Himanshu Gupta", "author_id": 1637772, "author_profile": "https://Stackoverflow.com/users/1637772", "pm_score": 1, "selected": false, "text": "#import \"SudokuClass.h\"\n#import \"GridView.h\"\n\n@interface GridView ()\n\n@end\n\n@implementation GridView\n\n\n-(void)createNumberButton {\n\n int cellWidth = 34;\n int cellHeight = 34;\n int xSta = 7 - cellWidth;\n int ySta = 50 - cellHeight;\n //NSMutableDictionary *buttonTable = [[NSMutableDictionary alloc] initWithCapacity:81];\n for (int i = 1; i < 10; i++) {\n xSta = xSta + cellWidth;\n for (int j = 1 ; j < 10; j++) {\n ySta = ySta + cellHeight;\n CGRect pos = CGRectMake(xSta, ySta, cellWidth, cellHeight);\n UIButton *b = [SudokuClass createSudokuButtonForView:self atPos:pos \n withTag:j*10+i forAction:@selector(numButtonPressed:)];\n NSString *picName = @\"ButtonPic.jpg\";\n [b setBackgroundImage:[[UIImage imageNamed:picName] stretchableImageWithLeftCapWidth:0 topCapHeight:0] forState:0];\n [self.view addSubview:b];\n //[numButtons addObject:b];\n }\n ySta = 50 - cellHeight;\n }}\n-(void)viewDidLoad\n{\n\n [self createNumberButton];\n [super viewDidLoad];\n}\n@end\n +(UIButton *)createSudokuButtonForView:(UIViewController *)view atPos:(CGRect)position withTag:(int)tag forAction:(SEL)action {\nUIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];\n[b setFrame:position];\n[b.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];\n[b setTag:tag];\n[b addTarget:view action:action forControlEvents:UIControlEventTouchDown];\n[b setTitle:@\"\" forState:0];\n[b setTitleColor:[UIColor blackColor] forState:0];\n//b.layer.frame = CGRectMake(xSta-1, ySta-1, 31, 31);\n//[b.layer setBorderWidth:borderWidth];\n\n\nb.userInteractionEnabled = YES;\nreturn b;}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39365/" ]
305,870
<p>I am attempting to write a Windows Service in C#. I need to find the path to a certain file, which is stored in an environment variable. In a regular C# console application, I can achieve that with the following line:</p> <pre><code>string t = System.Environment.GetEnvironmentVariable("TIP_HOME"); </code></pre> <p>If I write that to the console I see that it was successful.</p> <p>Now, if I try that same code in a Windows Service, the string <code>t</code> is empty.</p> <p>Any idea why?</p>
[ { "answer_id": 306090, "author": "Brian", "author_id": 39373, "author_profile": "https://Stackoverflow.com/users/39373", "pm_score": 1, "selected": false, "text": "foreach(DictionaryEntry de in Environment.GetEnvironmentVariables(tgt))\n{\n key = (string)de.Key;\n value = (string)de.Value;\n\n if(key.Equals(\"TIP_HOME\") && value != null)\n log.WriteEntry(\"TIP_HOME=\"+value, EventLogEntryType.Information);\n}\n" }, { "answer_id": 2728574, "author": "Richard Quadling", "author_id": 327748, "author_profile": "https://Stackoverflow.com/users/327748", "pm_score": 6, "selected": false, "text": "Var1=Value1\nVar2=Value2\n" }, { "answer_id": 29177790, "author": "Joseph", "author_id": 2003060, "author_profile": "https://Stackoverflow.com/users/2003060", "pm_score": 1, "selected": false, "text": "Local Service Local System Network Service protected override void OnStart(string[] args)\n{\n EventLog.WriteEntry(\"The HomePath for this service is '\" + Environment.GetEnvironmentVariable(\"HOMEPATH\") + \"'\", EventLogEntryType.Information);\n}\n The HomePath for this service is '\\Users\\Admin-PC'" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39373/" ]
305,880
<p>I've got what I think is a simple question. I've seen examples both ways. The question is - "why can't I place my annotations on the field?". Let me give you an example....</p> <pre><code>@Entity @Table(name="widget") public class Widget { private Integer id; @Id @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { return this.id; } public Integer setId(Integer Id) { this.id = id;} } </code></pre> <p>The above code works fine (assuming there's not a typo in there). When the annotation is placed on the getter of the property everything is perfect.</p> <p>However, that seems awkward to me. In my mind it's cleaner to place the annotation on the field, like so --</p> <pre><code>@Entity @Table(name="widget") public class Widget { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; public Integer getId() { return this.id; } public Integer setId(Integer Id) { this.id = id;} } </code></pre> <p>I've seen examples of both ways. However, when I run this second example I get the following...</p> <pre> java.lang.NullPointerException at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:25) at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:1) at java.lang.ThreadLocal$ThreadLocalMap.getAfterMiss(Unknown Source) at java.lang.ThreadLocal$ThreadLocalMap.get(Unknown Source) at java.lang.ThreadLocal$ThreadLocalMap.access$000(Unknown Source) at java.lang.ThreadLocal.get(Unknown Source) at com.widget.util.hibernate.HibernateSessionFactory.get(HibernateSessionFactory.java:33) at com.widget.db.dao.AbstractDao.(AbstractDao.java:12) at com.widget.db.dao.WidgetDao.(WidgetDao.java:9) at com.widget.db.dao.test.WidgetDaoTest.findById(WidgetDaoTest.java:17) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) ... </pre> <p>Here's the skeleton of <code>HibernateSessionFactory</code> (line 25 is marked) ....</p> <pre><code>protected Session initialValue() { SessionFactory sessionFactory = null; try { Configuration cfg = new AnnotationConfiguration().configure(); String url = System.getProperty("jdbc.url"); if (url != null) { cfg.setProperty("hibernate.connection.url", url); } sessionFactory = cfg.buildSessionFactory(); } catch (Exception e) { } Session session = sessionFactory.openSession(); // LINE 25 return session; } </code></pre> <p>Anyone have an idea what's going on here?</p>
[ { "answer_id": 305902, "author": "Jonathan", "author_id": 28209, "author_profile": "https://Stackoverflow.com/users/28209", "pm_score": 0, "selected": false, "text": "@Entity\n@Table(name=\"widget\")\npublic class Widget {\n @Id\n @GeneratedValue(strategy=GenerationType.AUTO)\n\n private Integer id;\n\n public Integer getId() { return this.id; }\n public Integer setId(Integer Id) { this.id = id;}\n}\n" }, { "answer_id": 306116, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 1, "selected": false, "text": "*.hbm.xml default-access property field" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39374/" ]
305,886
<p>For a new project I have to import the pre-existing data from MySql.</p> <p>In <a href="http://www.connectionstrings.com/?carrier=mysql" rel="noreferrer">this site</a> I have found many options, some including the installation of drivers. What is the fastest &amp; easiest way to do it?</p> <p>Update: this would be just a one time import</p>
[ { "answer_id": 6423238, "author": "Abdul HaSeeB", "author_id": 808157, "author_profile": "https://Stackoverflow.com/users/808157", "pm_score": 3, "selected": false, "text": "-- Create Link Server\n\nEXEC master.dbo.sp_addlinkedserver \n@server = N'MYSQL', \n@srvproduct=N'MySQL', \n@provider=N'MSDASQL', \n@provstr=N'DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; _\n DATABASE=tigerdb; USER=root; PASSWORD=hejsan; OPTION=3'\n\n-- Import Data\n\nSELECT * INTO testMySQL.dbo.shoutbox\nFROM openquery(MYSQL, 'SELECT * FROM tigerdb.shoutbox')\n" }, { "answer_id": 10800270, "author": "marcin.golebiowski", "author_id": 975270, "author_profile": "https://Stackoverflow.com/users/975270", "pm_score": 1, "selected": false, "text": "MySQL to MS SQL Server" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4264/" ]
305,894
<p>I am trying to update an old JavaScript function used to detect support for AJAX (i.e. the XmlHttpRequest object). I've looked online (including SO) and found various solutions but I'm not sure which is the most efficient for simply detecting support.</p> <p>The current function is:</p> <pre><code> function IsSyncAJAXSupported() { var isSyncAJAXSupported = true; var xmlHttp = null; var clsids = ["Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for(var i=0; i&lt;clsids.length &amp;&amp; xmlHttp == null; i++) { try { xmlHttp = new ActiveXObject(clsids[i]); } catch(e){} } if(xmlHttp == null &amp;&amp; MS.Browser.isIE) { isSyncAJAXSupported = false; } return isSyncAJAXSupported; } </code></pre> <p>In Firefox 3, the above gives errors because MS is undefined.</p> <p>I realise that using a library would be better but that's not an option for the short term. We are only supporting IE6 and above + recent versions of Firefox, Safari/WebKit and Opera.</p> <p>What's the best way of getting a true/false for XmlHttpRequest support?</p>
[ { "answer_id": 305926, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "function CreateXMLHttpRequest()\n{\n // Firefox and others\n try { return new XMLHttpRequest(); } catch (e) {}\n // Internet Explorer\n try { return new ActiveXObject(\"Microsoft.XMLHTTP\"); } catch (e) {}\n try { return new ActiveXObject(\"Msxml2.XMLHTTP\"); } catch (e) {}\n //alert(\"XMLHttpRequest not supported\");\n // No luck!\n return null;\n}\n" }, { "answer_id": 306073, "author": "Tom Robinson", "author_id": 12124, "author_profile": "https://Stackoverflow.com/users/12124", "pm_score": 1, "selected": true, "text": "var xhr = null;\ntry { xhr = new XMLHttpRequest(); } catch (e) {}\ntry { xhr = new ActiveXObject(\"Microsoft.XMLHTTP\"); } catch (e) {}\ntry { xhr = new ActiveXObject(\"Msxml2.XMLHTTP\"); } catch (e) {}\nreturn (xhr!=null);\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12124/" ]
305,905
<p>What's the best way to kill a process and all its child processes from a Perl script? It should run at least under Linux and Solaris, and not require installation of any additional packages.</p> <p>My guess would be to get a list of all processes and their parents by parsing files in /proc or by parsing the output of <code>ps</code> (neither of which seems portable between Linux and Solaris); and then killing all processes in the tree (which seems prone to race conditions).</p> <p>I could live with the race conditions in this particular case, but how do I portably get the process list?</p>
[ { "answer_id": 305919, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "kill -$signum, $pgid;\n $signum $pgid perlfunc SIGTERM kill 'TERM', -$pgid;\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148773/" ]
305,911
<p>Lets say you have a property like:</p> <pre><code>Person person1; public Person Captin{ get{ return person1; } set{ person1 = value; } } public void SomeFunction(){ Captin.name = "Hook" } </code></pre> <p>In this case if you set the name on the property we know that the new name of Hook will get applied to the underlying value of person1. What if our implementation were a little different say:</p> <pre><code>public Person Captin{ get{ return ReadCaptinFromDisk(); } set{ WriteCaptinToDisk(value); } } public void SomeFunction(){ Captin.name = "Hook" } </code></pre> <p>In this case for the underlying value to get set properly we need to have the Captin's set code called as part of the assignment to Captin.name. </p> <p>I am interested in knowing if the parameter set code will call the set on assignments of field or method calls on property references. especially for this kind of situation where the value needs to be propagated to disk (etc.).</p>
[ { "answer_id": 305942, "author": "JSC", "author_id": 37311, "author_profile": "https://Stackoverflow.com/users/37311", "pm_score": 2, "selected": false, "text": "public void SomeFunction() {\n Person p = Captin;\n p.name = \"Hook\";\n Captin = p;\n}\n" }, { "answer_id": 11548200, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "Foo Bar _Bar _Bar Foo.Bar.Text = \"George\" Text Foo _Bar Foo.Boz Rectangle _Boz Foo.Boz Rectangle Foo._Boz Foo.Boz.X _Boz X Foo.Boz.X = 5; Rectangle temp; temp.X = 5; X Rectangle X MyListOfRectangles List<Rectangle> Rectangle MyListOfRectangles[5].X MyListOfRectangles[5] MyListOfRectangles[4]" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
305,915
<p>I have a form containing a web browser control. This browser control will load some HTML from disk and display it. I want to be able to have a button in the HTML access C# code in my form. </p> <p>For example, a button in the HTML might call the Close() method on the form.</p> <p>Target platform: C# and Windows Forms (any version)</p>
[ { "answer_id": 305974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " private void MyMethod()\n {\n // do something\n }\n\n private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n {\n MyMethod();\n e.Cancel = true;\n }\n" }, { "answer_id": 339712, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 4, "selected": false, "text": "using System.Runtime.InteropServices;\n\n[ComVisible(true)]\npublic class External\n{\n private static MainWindow m_mainWindow = null;\n\n public External(MainWindow mainWindow)\n {\n m_mainWindow = mainWindow; \n }\n\n public void CloseApplication()\n {\n m_mainWindow.Close();\n }\n\n\n public string CurrentDate(string format)\n {\n return DateTime.Now.ToString(format); \n }\n}\n private void MainWindow_Load(object sender, EventArgs e)\n {\n m_external = new External(this);\n\n browserControl.ObjectForScripting = m_external; \n }\n // Javascript code\nfunction CloseButton_Click()\n{\n if (window.external)\n {\n window.external.CloseApplication();\n }\n}\n browserControl.Document.InvokeScript(\"jScriptFunction\", new object[] { \"param1\", 2, \"param2\" });\n" }, { "answer_id": 9591978, "author": "Matthew Skelton", "author_id": 1253233, "author_profile": "https://Stackoverflow.com/users/1253233", "pm_score": 0, "selected": false, "text": "Type.InvokeMember()" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
305,924
<p>I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.</p> <pre><code>def analyser(testFunc): print testFunc.__name__, 'belongs to the class, ... </code></pre> <p>I thought </p> <pre><code>testFunc.__class__ </code></pre> <p>would solve my problems, but that just tells me that testFunc is a function.</p>
[ { "answer_id": 305948, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "testFunc.__self__.__class__\n testFunc.__objclass__\n Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) \n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import hashlib\n>>> hd = hashlib.md5().hexdigest\n>>> hd\n<built-in method hexdigest of _hashlib.HASH object at 0x7f9492d96960>\n>>> hd.__self__.__class__\n<type '_hashlib.HASH'>\n>>> hd2 = hd.__self__.__class__.hexdigest\n>>> hd2\n<method 'hexdigest' of '_hashlib.HASH' objects>\n>>> hd2.__objclass__\n<type '_hashlib.HASH'>\n >>> hd.im_class\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'builtin_function_or_method' object has no attribute 'im_class'\n>>> hd2.im_class\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'method_descriptor' object has no attribute 'im_class'\n __objclass__ __self__" }, { "answer_id": 305980, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 5, "selected": true, "text": "testFunc.im_class\n im_class im_self" }, { "answer_id": 40953053, "author": "Conchylicultor", "author_id": 4172685, "author_profile": "https://Stackoverflow.com/users/4172685", "pm_score": 5, "selected": false, "text": ".im_class .__qualname__ class C:\n def f(): pass\n class D:\n def g(): pass\n\nprint(C.__qualname__) # 'C'\nprint(C.f.__qualname__) # 'C.f'\nprint(C.D.__qualname__) #'C.D'\nprint(C.D.g.__qualname__) #'C.D.g'\n def f():\n def g():\n pass\n return g\n\nf.__qualname__ # 'f'\nf().__qualname__ # 'f.<locals>.g'\n" }, { "answer_id": 60496733, "author": "Modi Sanjay", "author_id": 6383089, "author_profile": "https://Stackoverflow.com/users/6383089", "pm_score": 0, "selected": false, "text": "def getLocalMethods(clss):\nimport types\n# This is a helper function for the test function below.\n# It returns a sorted list of the names of the methods\n# defined in a class. It's okay if you don't fully understand it!\nresult = [ ]\nfor var in clss.__dict__:\n val = clss.__dict__[var]\n if (isinstance(val, types.FunctionType)):\n result.append(var)\nreturn sorted(result)\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
305,937
<p>I am creating a C# WinForms application. I would like to have a Custom Form Border. And I want to create a black custom window (with border and controls) like that of Adobe Lightroom. For example - <a href="https://i.stack.imgur.com/VNDFM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VNDFM.jpg" alt="Border like Adobe Lightroom" /></a> How do I create it, please help?</p>
[ { "answer_id": 12511904, "author": "Nikita", "author_id": 1611550, "author_profile": "https://Stackoverflow.com/users/1611550", "pm_score": 2, "selected": false, "text": " #region Кастомизированное поведение - рамки, активность и т.д.\n private bool isCurrentlyActive = false;\n private bool childControlsAreHandled = false;\n private Pen activeWindowFramePen, inactiveWindowFramePen;\n private Point[] framePoints;\n\n private void AddControlPaintHandler(Control ctrl)\n {\n ctrl.Paint += DrawWindowFrame;\n if (ctrl.Controls != null)\n {\n foreach (Control childControl in ctrl.Controls)\n {\n AddControlPaintHandler(childControl);\n }\n }\n }\n\n protected override void OnActivated(EventArgs e)\n {\n base.OnActivated(e);\n if ((this.childControlsAreHandled == false)\n && (WindowFrameType != Forms.WindowFrameType.NoFrame)\n && (this.MdiParent == null))\n {\n RecalculateWindowFramePoints();\n AddControlPaintHandler(this);\n this.childControlsAreHandled = true;\n }\n\n this.isCurrentlyActive = true;\n if (InactiveWindowOpacity < 1)\n {\n base.Opacity = 1;\n }\n base.Invalidate(true);\n }\n\n protected override void OnDeactivate(EventArgs e)\n {\n base.OnDeactivate(e);\n this.isCurrentlyActive = false;\n if (InactiveWindowOpacity < 1)\n {\n base.Opacity = InactiveWindowOpacity;\n }\n base.Invalidate(true);\n }\n\n protected override void OnResizeEnd(EventArgs e)\n {\n base.OnResizeEnd(e);\n this.framePoints = null;\n RecalculateWindowFramePoints();\n this.Invalidate(true);\n }\n\n private Pen ActivePen\n {\n get\n {\n if (this.isCurrentlyActive)\n {\n if (this.activeWindowFramePen == null)\n {\n this.activeWindowFramePen = new Pen(Color.FromArgb((int)(WindowFrameOpacity*255), WindowFrameActiveColor), WindowFrameSize * 2);\n }\n return this.activeWindowFramePen;\n }\n else\n {\n if (this.inactiveWindowFramePen == null)\n {\n this.inactiveWindowFramePen = new Pen(Color.FromArgb((int)(WindowFrameOpacity*255), WindowFrameInactiveColor), WindowFrameSize * 2);\n }\n return this.inactiveWindowFramePen;\n }\n }\n }\n\n private Point[] RecalculateWindowFramePoints()\n {\n if ((WindowFrameType == Forms.WindowFrameType.AllSides)\n && (this.framePoints != null)\n && (this.framePoints.Length != 5))\n {\n this.framePoints = null;\n }\n if ((WindowFrameType == Forms.WindowFrameType.LeftLine)\n && (this.framePoints != null)\n && (this.framePoints.Length != 2))\n {\n this.framePoints = null;\n }\n if (this.framePoints == null)\n {\n switch (WindowFrameType)\n {\n case Forms.WindowFrameType.AllSides:\n this.framePoints = new Point[5]\n {\n new Point(this.ClientRectangle.X, this.ClientRectangle.Y),\n new Point(this.ClientRectangle.X + this.ClientRectangle.Width, this.ClientRectangle.Y),\n new Point(this.ClientRectangle.X + this.ClientRectangle.Width, this.ClientRectangle.Y + this.ClientRectangle.Height),\n new Point(this.ClientRectangle.X, this.ClientRectangle.Y + this.ClientRectangle.Height),\n new Point(this.ClientRectangle.X, this.ClientRectangle.Y)\n };\n break;\n case Forms.WindowFrameType.LeftLine:\n this.framePoints = new Point[2]\n {\n new Point(this.ClientRectangle.X, this.ClientRectangle.Y),\n new Point(this.ClientRectangle.X, this.ClientRectangle.Y + this.ClientRectangle.Height)\n };\n break;\n }\n }\n return this.framePoints;\n }\n\n private void DrawWindowFrame(object sender, PaintEventArgs e)\n {\n if (WindowFrameType == Forms.WindowFrameType.NoFrame)\n {\n return;\n }\n if ((this.framePoints == null) || (this.framePoints.Length == 0))\n {\n return;\n }\n Control ctrl = (Control)(sender);\n // пересчитаем точки в координатах контрола.\n List<Point> pts = new List<Point>();\n foreach (var p in this.framePoints)\n {\n pts.Add(ctrl.PointToClient(this.PointToScreen(p)));\n }\n e.Graphics.DrawLines(ActivePen, pts.ToArray());\n }\n\n public static int WindowFrameSize = 2;\n public static WindowFrameType WindowFrameType = Forms.WindowFrameType.NoFrame;\n public static Color WindowFrameActiveColor = Color.YellowGreen;\n public static Color WindowFrameInactiveColor = SystemColors.ControlDark;\n public static double InactiveWindowOpacity = 1.0;\n public static double WindowFrameOpacity = 0.3;\n #endregion\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
305,991
<p>I'm under the impression that the Dot '.' (wild card) character is dangerous to use. Is my fear unfounded? Thanks</p>
[ { "answer_id": 306104, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": ".* .*<one>.*<two>.*<three>.*</three>.*</two>.*</one>.*\n" }, { "answer_id": 306154, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 2, "selected": false, "text": "[^x]* .*?x .* .*? .{0,10}" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
305,994
<p>I searched all over this site and the web for a good and <strong>simple</strong> example of autocomplete using jQuery and ASP.NET. I wanted to expose the data used by autocomplete with a webservice (and will probably do that next). In the meantime, I got this working, but it seems a little hacky...</p> <p>In my page I have a text box:</p> <pre><code>&lt;input id="txtSearch" type="text" /&gt; </code></pre> <p>I am using jQuery autocomplete, set up per their example:</p> <pre><code>&lt;link rel="stylesheet" href="js/jquery.autocomplete.css" type="text/css" /&gt; &lt;script type="text/javascript" src="js/jquery.bgiframe.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery.dimensions.pack.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery.autocomplete.js"&gt;&lt;/script&gt; </code></pre> <p>Here is where it starts to get hacky... I call a page instead of a webservice:</p> <pre><code> &lt;script type="text/javascript"&gt; $(document).ready(function(){ $("#txtSearch").autocomplete('autocompletetagdata.aspx'); }); &lt;/script&gt; </code></pre> <p>In the page I stripped out ALL of the html and just have this (otherwise, various HTML bits show up in the autocomplete dropdown):</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="autocompletetagdata.aspx.cs" Inherits="autocompletetagdata" %&gt; </code></pre> <p>And in my autocompletetagdata.aspx, I am using SubSonic to query, format and return data from the database (one data item per line):</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { // Note the query strings passed by jquery autocomplete: //QueryString: {q=a&amp;limit=150&amp;timestamp=1227198175320} LookupTagCollection tags = Select.AllColumnsFrom&lt;LookupTag&gt;() .Top(Request.QueryString["limit"]) .Where(LookupTag.Columns.TagDescription).Like(Request.QueryString["q"] + "%") .OrderAsc(LookupTag.Columns.TagDescription) .ExecuteAsCollection&lt;LookupTagCollection&gt;(); StringBuilder sb = new StringBuilder(); foreach (LookupTag tag in tags) { sb.Append(tag.TagDescription).Append("\n"); } Response.Write(sb.ToString()); } </code></pre> <p>If you don't do a LIKE query, then it returns everything that contains a match for the character(s) you type -- e.g., typing "a" will include "Ask" and "Answer" as well as "March" and "Mega." I just wanted it to do a starts with match.</p> <p>Anyway, it works and it's pretty easy to set up, but is there a better way?</p>
[ { "answer_id": 306037, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 6, "selected": true, "text": "<script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"#txtSearch\").autocomplete('autocompletetagdata.ashx');\n }); \n</script>\n\n[WebService(Namespace = \"http://www.yoursite.com/\")]\n[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\npublic class AutocompleteTagData : IHttpHandler\n{\n public void ProcessRequest(HttpContext context)\n {\n // Note the query strings passed by jquery autocomplete:\n //QueryString: {q=a&limit=150&timestamp=1227198175320}\n\n LookupTagCollection tags = Select.AllColumnsFrom<LookupTag>()\n .Top(context.Request.QueryString[\"limit\"])\n .Where(LookupTag.Columns.TagDescription).Like(context.Request.QueryString[\"q\"] + \"%\")\n .OrderAsc(LookupTag.Columns.TagDescription)\n .ExecuteAsCollection<LookupTagCollection>();\n\n foreach (LookupTag tag in tags)\n {\n context.Response.Write(tag.TagDescription + Environment.NewLine);\n }\n }\n\n public bool IsReusable\n {\n get\n {\n return false;\n }\n }\n}\n" }, { "answer_id": 306070, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "[OperationContract]\n[WebInvoke(RequestFormat=WebMessageFormat.Json,\n ResponseFormat=WebMessageFormat.Json)]\npublic LookupTagCollection LookupTags( int limit, string q )\n{\n return Select.AllColumnsFrom<LookupTag>()\n .Top(limit)\n .Where(LookupTag.Columns.TagDescription)\n .Like(q+ \"%\")\n .OrderAs(LookupTag.Columns.TagDescription)\n .ExecuteAsCollection<LookupTagCollection>(); \n}\n" }, { "answer_id": 917460, "author": "Zachary", "author_id": 64741, "author_profile": "https://Stackoverflow.com/users/64741", "pm_score": 3, "selected": false, "text": " $(\"#<%= TextBox1.ClientID %>\").autocomplete(\"/Demo/WebSvc.asmx/SuggestCustomers\", {\n parse: function(data) {\n var parsed = [];\n\n $(data).find(\"string\").each(function() {\n parsed[parsed.length] = {\n data: [$(this).text()],\n value: $(this).text(),\n result: [$(this).text()]\n };\n });\n return parsed;\n },\n dataType: \"xml\"\n });\n" }, { "answer_id": 8797887, "author": "anthonyvscode", "author_id": 79254, "author_profile": "https://Stackoverflow.com/users/79254", "pm_score": 2, "selected": false, "text": "$(function () {\n $(\"#autocomplete\").autocomplete({\n source: \"/pathtohandler/handler.ashx\",\n minLength: 1,\n select: function (event, ui) {\n $(this).val(ui.item.value);\n }\n });\n});\n public class SearchHandler : IHttpHandler\n{\n public void ProcessRequest(HttpContext context)\n {\n var term = context.Request.QueryString[\"term\"].ToString();\n\n context.Response.Clear();\n context.Response.ContentType = \"application/json\";\n\n var search = //TODO implement select logic based on the term above\n\n JavaScriptSerializer jsSerializer = new JavaScriptSerializer();\n string json = jsSerializer.Serialize(search);\n context.Response.Write(json);\n context.Response.End();\n }\n\n public bool IsReusable\n {\n get\n {\n return false;\n }\n }\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/305994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38787/" ]
306,012
<p>There is an actual running Java ServerPages (JSP) application within a *NIX box which I somewhat administer with kind of good permissions. The idea is to create a new but dead simple JSP page to control some Korn Shell scripts I've got running there. So the goal is to make some sort of HTML form that will be writing some kind of scriptStatus.on / scriptStatus.off file:</p> <pre><code>#!usr/bin/ksh # coolScript.sh # This is my cool script that is being launched by cron every 10 minutes. if [ -e scriptStatus.off ] then # monitor disabled else # monitor enabled fi </code></pre> <p>which then can be checked for existence within the running script, therefore allowing to easily activate / deactivate it without actually have do deal with cron. Please let me know if all this makes sense and do not hesitate to ask as many questions as needed.</p> <p>Thanks much in advance! </p>
[ { "answer_id": 306083, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": true, "text": "File flag = new File(\"/path/scriptStatus.off\");\nString message;\nif (flag.delete())\n message = \"Script enabled.\";\nelse if (flag.createNewFile()) \n message = \"Script disabled.\";\nelse\n /* Maybe missing directory, wrong permissions, race condition. */\n message = \"Error: script state unknown.\";\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
306,013
<p>My form does not go to recipient when submitted! I changed the file mail.tpl.txt to direct to my own email address as a test and I got the email just fine.</p> <p>Client has checked junk mail folder as well and he is just not getting information.</p> <p>Below is the form code, followed by the code from mail.tpl.txt and then the form's index.php code.</p> <p>Everything looks okay to me, so I am asking if someone has any idea why he wouldn't be getting the form. He uses qwest for email if that helps any.</p> <p>Here's the form code:</p> <pre><code>&lt;form id="contactForm" name="form" action="form/index.php" method="post"&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;font color="#000000"&gt;&lt;strong&gt;Please fill out the form below if you have any questions.&lt;/strong&gt;&lt;/font&gt;&lt;/legend&gt; &lt;div&gt; &lt;label for="name"&gt;Name:* &lt;/label&gt; &lt;input type="text" size="30" name="name" class="txt" id="name" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="label"&gt;Phone: &lt;/label&gt; &lt;input type="text" size="30" name="phone" class="txt" id="label" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="email"&gt;Email:* &lt;/label&gt; &lt;input type="text" size="30" name="email" class="txt" id="email" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="message"&gt;Message: &lt;/label&gt; &lt;textarea rows="6" name="message" id="message" cols="40" class="txt"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;input type="hidden" name="thanks" value="../thanks.php" /&gt; &lt;input type="hidden" name="email_fields" value="email" /&gt; &lt;input type="hidden" name="required_fields" value="name, email" /&gt; &lt;input type="hidden" name="html_template" value="form.tpl.html" /&gt; &lt;input type="hidden" name="mail_template" value="mail.tpl.txt" /&gt; &lt;div class="submit"&gt; &lt;input type="submit" class="btn" value="Send Message" name="Submit" id="Submit" /&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>Now the mail.tpl.text code: (I have taken out my client's full address and domain name for the post.)</p> <pre><code> To: "xxxxxxx Custom Homes" &lt;xxxxxxx@q.com&gt; From: "{name}" {phone} &lt;{email}&gt; &lt;{message}&gt; MIME-Version: 1.0 Content-type: text/plain; charset={txt_charset} Subject: Online Contact Request from Freese Custom Homes Contact Information: {name} {phone} Email Address: {email} Contact Message: {message} Lastly, here's the form's index.php code: (Again, I have taken out my client's domain name for the post) &lt;?php $script_root = './'; $referring_server = ''; // Example: $referring_server = 'xxxxxxx.com, www.xxxxxxx.com'; $language = 'en'; // (see folder 'languages') $ip_banlist = ''; $ip_address_count = '0'; $ip_address_duration = '48'; $show_limit_errors = 'yes'; // (yes, no) $log_messages = 'no'; // (yes, no) -- make folder "temp" writable with: chmod 777 temp $text_wrap = '72'; $show_error_messages = 'yes'; $attachment = 'no'; // (yes, no) -- make folder "temp" writable with: chmod 777 temp $attachment_files = 'jpg, gif,png, zip, txt, pdf, doc, ppt, tif, bmp, mdb, xls, txt'; $attachment_size = 9000000; $captcha = 'no'; // (yes, no) -- make folder "temp" writable with: chmod 777 temp $path['logfile'] = $script_root . 'logfile/logfile.txt'; $path['templates'] = $script_root . 'templates/'; $file['default_html'] = 'form.tpl.html'; $file['default_mail'] = 'mail.tpl.txt'; /***************************************************** ** Add further words, text, variables and stuff ** that you want to appear in the templates here. ** The values are displayed in the HTML output and ** the e-mail. *****************************************************/ $add_text = array( 'txt_additional' =&gt; 'Additional', // {txt_additional} 'txt_more' =&gt; 'More' // {txt_more} ); /***************************************************** ** Do not edit below this line - Ende der Einstellungen *****************************************************/ /***************************************************** ** Send safety signal to included files *****************************************************/ define('IN_SCRIPT', 'true'); /***************************************************** ** Load formmail script code *****************************************************/ include($script_root . 'inc/formmail.inc.php'); echo $f6l_output; ?&gt; </code></pre>
[ { "answer_id": 1077429, "author": "Basher", "author_id": 132187, "author_profile": "https://Stackoverflow.com/users/132187", "pm_score": 1, "selected": false, "text": "From: \"{name}\" {phone} <{email}> <{message}> \n From: \"{name} {phone}\" <{email}>\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30043/" ]
306,017
<p>I realize that far is compiler specific, but my expectation is that the placement of the far specifier should make sense to those who really understand pointers.</p> <p>So, I have two applications that share the processor's entire memory space.</p> <p>App A needs to call function foo that exists in app B.</p> <p>I know the memory location of function foo.</p> <p>So this should work, in app A:</p> <pre><code>typedef int (* __far MYFP)(int input); void somefunc(void) { int returnvalue; MYFP foo; foo = (MYFP) 0xFFFFFA; returnvalue = foo(39); } </code></pre> <ul> <li>Is the __far in the right spot in the typedef?</li> <li>Do I need to add __far to the (MYFP) cast?</li> <li>Some information suggests that the call to foo doesn't need to be dereferenced, what is your experience?</li> <li><p>What else about this looks incorrect, or might I try to accomplish this?</p></li> <li><p>Is there a better way to do this?</p></li> </ul> <p>Edit:</p> <p>This is on an embedded device (Freescale S12XEQ device) using Code Warrior. It's a 16 bit device with 24 bit memory space, so yes, it is segmented/banked.</p> <p>-Adam</p>
[ { "answer_id": 306067, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 3, "selected": false, "text": "__far" }, { "answer_id": 306321, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 1, "selected": false, "text": "void softSerial0SR(unsigned16);\nvoid (__far *softHandler)(unsigned16);\n softHandler = softSerial0SR;\n" }, { "answer_id": 306342, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": true, "text": "foo = (MYFP)0xFFFFFA;\nreturnvalue = foo(39); // 1\nreturnvalue = (*foo)(39); // 2\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
306,062
<p>I need a CSS selector that can find the 2nd div of 2 that has the same class. I've looked at <code>nth-child()</code> but it's not what I want since I can't see a way to further clarify what class I want. These 2 divs will be siblings in the document if that helps.</p> <p>My HTML looks something like this:</p> <pre><code>&lt;div class="foo"&gt;...&lt;/div&gt; &lt;div class="bar"&gt;...&lt;/div&gt; &lt;div class="baz"&gt;...&lt;/div&gt; &lt;div class="bar"&gt;...&lt;/div&gt; </code></pre> <p>And I want the 2nd div.bar (or the last div.bar would work too).</p>
[ { "answer_id": 306087, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 6, "selected": false, "text": ".bar:nth-child(2)\n" }, { "answer_id": 306127, "author": "Seamus", "author_id": 30443, "author_profile": "https://Stackoverflow.com/users/30443", "pm_score": 4, "selected": false, "text": ".foo:nth-child(2)\n <div>\n <div class=\"foo\"></div>\n <div class=\"foo\">Find me</div>\n...\n</div>\n <div>\n <div class=\"other\"></div>\n <div class=\"foo\"></div>\n <div class=\"foo\">Find me</div>\n ...\n</div>\n" }, { "answer_id": 306177, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 6, "selected": true, "text": "nth-of-type .bar:nth-of-type(2) // set style:\n$$('div.theclassname')[1].setStyle({ backgroundColor: '#900', fontSize: '1.2em' });\n// OR add class name:\n$$('div.theclassname')[1].addClassName('secondclass'); // pun intentded...\n" }, { "answer_id": 306184, "author": "One Crayon", "author_id": 38666, "author_profile": "https://Stackoverflow.com/users/38666", "pm_score": 2, "selected": false, "text": ".foo <div class=\"foo\"></div>\n<div class=\"foo last\"></div>\n\n.foo {}\n.foo.last {}\n" }, { "answer_id": 6468344, "author": "Timon", "author_id": 814125, "author_profile": "https://Stackoverflow.com/users/814125", "pm_score": 3, "selected": false, "text": "$('.foo:eq(1)').css('color', 'red');\n <div>\n <div class=\"other\"></div>\n <div class=\"foo\"></div>\n <div class=\"foo\">Find me</div>\n ... \n" }, { "answer_id": 12649142, "author": "Eric Hendrickson", "author_id": 1707615, "author_profile": "https://Stackoverflow.com/users/1707615", "pm_score": 2, "selected": false, "text": ".parent_class div:first-child + div\n div +" }, { "answer_id": 12652010, "author": "mhelvens", "author_id": 681588, "author_profile": "https://Stackoverflow.com/users/681588", "pm_score": 6, "selected": false, "text": ":nth-of-type div div.bar:nth-of-type(2) div:nth-of-type(2).bar div bar .bar ~ .bar\n .bar:nth-of-type(2)\n .bar .bar ~ .bar\n" }, { "answer_id": 35982560, "author": "Surya R Praveen", "author_id": 714707, "author_profile": "https://Stackoverflow.com/users/714707", "pm_score": 4, "selected": false, "text": "<h1> Target Bar Elements </h1>\n\n<div class=\"foo\">Foo Element</div>\n<div class=\"bar\">Bar Element</div>\n<div class=\"baz\">Baz Element</div>\n<div class=\"bar\">Bar Second Element</div>\n<div class=\"jar\">Jar Element</div>\n<div class=\"kar\">Kar Element</div>\n<div class=\"bar\">Bar Third Element</div>\n .bar {background:red;}\n.bar~.bar {background:green;}\n.bar~.bar~.bar {background:yellow;}\n" }, { "answer_id": 59351096, "author": "amir22", "author_id": 3855682, "author_profile": "https://Stackoverflow.com/users/3855682", "pm_score": 1, "selected": false, "text": ":nth-of-type(n) #topmenu li:nth-of-type(2) ul.childUl {\n #topmenu li <ul id=\"topmenu\">\n <li>\n <ul class=\"childUl\">\n <li></li>\n <li></li>\n <li></li>\n </ul>\n </li>\n <li>\n <ul class=\"childUl\">\n <li></li>\n <li></li>\n <li></li>\n </ul>\n </li>\n <li>\n <ul class=\"childUl\">\n <li></li>\n <li></li>\n <li></li>\n </ul>\n </li>\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12094/" ]
306,065
<p>Currently i have a NotInheritable class in App_Code that hold some variables that need to be access thur-out the application but i don't think it's a good way to manage global variables. </p>
[ { "answer_id": 306197, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": 0, "selected": false, "text": "Settings.Default.PortalName" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
306,075
<p>Is there a cookie automatically placed on the user's machine? Or is it somehow associated with the requester's IP address? Or maybe in the ViewState? Elementary question, I know, but I've had a hard time finding an answer.</p>
[ { "answer_id": 306084, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "ASP.NET_SessionId ASP.NET_SessionId=kxt1dee1laeuq445pyzjvv55; path=/; domain=localhost; HttpOnly\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767/" ]
306,080
<p>After following the advice in <a href="https://stackoverflow.com/questions/302560/wix-custom-actions-with-wixuiminimal">this question</a> successfully, I added a couple additional lines of code for another custom action. This one is intended to call regsvr32 on the copy of capicom which I've tried to put in the user's system folder. However, I'm getting error 2721, which seems to be a custom action not found error, from what I've seen. Any suggestions? I'm trying to maintain consistency with previous iterations of my installer by calling regsvr, rather than just adding the registry entries during install, which could be a good idea instead. :::shrug:::</p> <pre><code>&lt;Directory Id="SystemFolder" Name="Sys"&gt; ... &lt;component ...&gt; ... &lt;File Id="CapiCom.Dll" LongName="CapiCom.Dll" Name="CAPICOM.DLL" Source=... /&gt; &lt;/component&gt; &lt;/directory&gt; ... &lt;CustomAction Id="REGCAPICOM" ExeCommand='regsvr32.exe "[SystemFolder]capicom.dll"' Return = "ignore" Execute="deferred" /&gt; ... &lt;InstallExecuteSequence&gt; ... &lt;Custom Action="REGCAPICOM" After="InstallFiles" /&gt; &lt;/InstallExecuteSequence&gt; </code></pre> <p>Edit: Yes, using regsvr32 as an installer is ugly. But when I downloaded the Capicom SDK, that is what MS said to do in order to install it. Searching around has found many people saying that this is a stupid way to do it...but it's also mechanism MS provided. I'll listen to suggestions for a better way. I don't consider it a big deal if Capicom being left behind when my application is uninstalled, considering that it's a standard windows component.</p> <p>Edit: Hmmm. Apparently, one of the things running selfreg on the dll does is to create a random seed to add to the registry. Not sure what mechanism it uses to generate this seed but I suspect it would be considered in poor taste to just generate one myself, especially if I gave all the users the same seed. Not sure.... Apparently if I skip this Capicom does it on its own, so I'm fine.</p>
[ { "answer_id": 306409, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 0, "selected": false, "text": "heat file [Path\\Capicom.dll] -template:product -out capicom.wxs\n <ComponentGroup Id=\"capicom\">\n <ComponentRef Id=\"capicom.dll\"/>\n</ComponentGroup>\n <Feature Id=\"PRODUCTFEATURE\">\n <ComponentGroupRef Id=\"capicom\" />\n ... [Other components or ComponentGroups references]\n</Feature>\n" }, { "answer_id": 447152, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 3, "selected": true, "text": "<CustomAction Id=\"RegisterCapicom\" Directory=\"SystemFolder\" ExeCommand=\"regsvr32.exe /s &quot;[SystemFolder]Capicom.dll&quot;\" Return=\"check\" Execute=\"deferred\" />\n...\n<InstallExecuteSequence>\n <Custom Action=\"RegisterCapicom\" After=\"InstallFiles\" />\n</InstallExecuteSequence>\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18192/" ]
306,097
<p>We determined in a <a href="https://stackoverflow.com/questions/303810/variable-dynamic-option-lists-in-html-select-using-ie">previous question</a> that many features of HTML SELECTs are not supported in IE. Is there an alternative widget that you would recommend from your experience that meets the following requirements?</p> <ol> <li>Respects the <code>contentEditable</code> property (does not allow selection changes if true)</li> <li>Respects the <code>disabled</code> property of individual OPTIONs (shows them "grayed out" or with strike-through font, and makes them un-selectable)</li> <li>Supports Option Groups (<code>OPTGROUP</code> elements)</li> <li>Supports <code>style</code> options such as <code>border</code> and <code>margin</code> in the <code>SELECT</code> and all sub-elements</li> <li>Supports dynamic add and delete of <code>OPTION</code> and <code>OPTGROUP</code> elements</li> <li>Supports the above in IE version 6 and above</li> </ol> <p>EDIT: As noted by @Joel Coehoorn, items 3 and 5 above are currently supported in IE. They are included here to make sure they are not overlooked in a replacement widget.</p>
[ { "answer_id": 306125, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<optgroup label=\"--\"></optgroup>\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26671/" ]
306,130
<p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
[ { "answer_id": 306196, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 3, "selected": false, "text": "def logger(myFunc):\n def new(*args, **keyargs):\n print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)\n return myFunc(*args, **keyargs)\n\n return new\n\nclass C(object):\n def f(self):\n pass\nC.f = logger(C.f)\nC().f()\n C = wrapClass(C)\n" }, { "answer_id": 306260, "author": "Asa Ayers", "author_id": 35247, "author_profile": "https://Stackoverflow.com/users/35247", "pm_score": 3, "selected": false, "text": "def logger(myFunc):\n def new(self, *args, **keyargs):\n print 'Entering %s.%s' % (self.__class__.__name__, myFunc.__name__)\n return myFunc(self, *args, **keyargs)\n\n return new \n\nclass C(object):\n @logger\n def f(self):\n pass\nC().f()\n self.__name__ self.__class__.__name__" }, { "answer_id": 306277, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 7, "selected": true, "text": "self from functools import wraps # use this to preserve function signatures and docstrings\ndef logger(func):\n @wraps(func)\n def with_logging(*args, **kwargs):\n print \"Entering %s.%s\" % (args[0].__class__.__name__, func.__name__)\n return func(*args, **kwargs)\n return with_logging\n\nclass C(object):\n @logger\n def f(self):\n pass\n\nC().f()\n class B(C):\n pass\n\nb = B()\nb.f()\n Entering B.f Entering C.f" }, { "answer_id": 306295, "author": "Andrew Beyer", "author_id": 38691, "author_profile": "https://Stackoverflow.com/users/38691", "pm_score": 0, "selected": false, "text": "new.instancemethod()" }, { "answer_id": 307263, "author": "ianb", "author_id": 20218, "author_profile": "https://Stackoverflow.com/users/20218", "pm_score": 5, "selected": false, "text": "C.f C.f.im_class is C self.__class__.__name__ class logger(object):\n def __init__(self, func):\n self.func = func\n def __get__(self, obj, type=None):\n return self.__class__(self.func.__get__(obj, type))\n def __call__(self, *args, **kw):\n print 'Entering %s' % self.func\n return self.func(*args, **kw)\n\nclass C(object):\n @logger\n def f(self, x, y):\n return x+y\n\nC().f(1, 2)\n# => Entering <bound method C.f of <__main__.C object at 0x...>>\n getattr(self.func, 'im_class', None)" }, { "answer_id": 3300907, "author": "user398139", "author_id": 398139, "author_profile": "https://Stackoverflow.com/users/398139", "pm_score": 3, "selected": false, "text": "inspect import inspect\n\ndef logger(myFunc):\n classname = inspect.getouterframes(inspect.currentframe())[1][3]\n def new(*args, **keyargs):\n print 'Entering %s.%s' % (classname, myFunc.__name__)\n return myFunc(*args, **keyargs)\n return new\n\nclass C(object):\n @logger\n def f(self):\n pass\n\nC().f()\n inspect" }, { "answer_id": 3412743, "author": "Denis Ryzhkov", "author_id": 350937, "author_profile": "https://Stackoverflow.com/users/350937", "pm_score": 4, "selected": false, "text": "inspect.getouterframes args[0].__class__.__name__ __get__ @wraps @wraps method_decorator functools.wraps() pip install method_decorator\nfrom method_decorator import method_decorator\n\nclass my_decorator(method_decorator):\n # ...\n method_decorator class method_decorator(object):\n\n def __init__(self, func, obj=None, cls=None, method_type='function'):\n # These defaults are OK for plain functions\n # and will be changed by __get__() for methods once a method is dot-referenced.\n self.func, self.obj, self.cls, self.method_type = func, obj, cls, method_type\n\n def __get__(self, obj=None, cls=None):\n # It is executed when decorated func is referenced as a method: cls.func or obj.func.\n\n if self.obj == obj and self.cls == cls:\n return self # Use the same instance that is already processed by previous call to this __get__().\n\n method_type = (\n 'staticmethod' if isinstance(self.func, staticmethod) else\n 'classmethod' if isinstance(self.func, classmethod) else\n 'instancemethod'\n # No branch for plain function - correct method_type for it is already set in __init__() defaults.\n )\n\n return object.__getattribute__(self, '__class__')( # Use specialized method_decorator (or descendant) instance, don't change current instance attributes - it leads to conflicts.\n self.func.__get__(obj, cls), obj, cls, method_type) # Use bound or unbound method with this underlying func.\n\n def __call__(self, *args, **kwargs):\n return self.func(*args, **kwargs)\n\n def __getattribute__(self, attr_name): # Hiding traces of decoration.\n if attr_name in ('__init__', '__get__', '__call__', '__getattribute__', 'func', 'obj', 'cls', 'method_type'): # Our known names. '__class__' is not included because is used only with explicit object.__getattribute__().\n return object.__getattribute__(self, attr_name) # Stopping recursion.\n # All other attr_names, including auto-defined by system in self, are searched in decorated self.func, e.g.: __module__, __class__, __name__, __doc__, im_*, func_*, etc.\n return getattr(self.func, attr_name) # Raises correct AttributeError if name is not found in decorated self.func.\n\n def __repr__(self): # Special case: __repr__ ignores __getattribute__.\n return self.func.__repr__()\n" }, { "answer_id": 48491127, "author": "aurzenligl", "author_id": 7249587, "author_profile": "https://Stackoverflow.com/users/7249587", "pm_score": 0, "selected": false, "text": "class decorated(object):\n def __init__(self, func, type_=None):\n self.func = func\n self.type = type_\n\n def __get__(self, obj, type_=None):\n return self.__class__(self.func.__get__(obj, type_), type_)\n\n def __call__(self, *args, **kwargs):\n name = '%s.%s' % (self.type.__name__, self.func.__name__)\n print('called %s with args=%s kwargs=%s' % (name, args, kwargs))\n return self.func(*args, **kwargs)\n\nclass Foo(object):\n @decorated\n def foo(self, a, b):\n pass\n __get__ __call__ >>> Foo().foo(1, b=2)\ncalled Foo.foo with args=(1,) kwargs={'b': 2}\n" }, { "answer_id": 54316672, "author": "tyrion", "author_id": 641317, "author_profile": "https://Stackoverflow.com/users/641317", "pm_score": 2, "selected": false, "text": "__qualname__ >>> def logger(myFunc):\n... def new(*args, **keyargs):\n... print('Entering %s' % myFunc.__qualname__)\n... return myFunc(*args, **keyargs)\n... \n... return new\n... \n>>> class C(object):\n... @logger\n... def f(self):\n... pass\n... \n>>> C().f()\nEntering C.f\n >>> class C:\n... def f(): pass\n... class D:\n... def g(): pass\n...\n>>> C.__qualname__\n'C'\n>>> C.f.__qualname__\n'C.f'\n>>> C.D.__qualname__\n'C.D'\n>>> C.D.g.__qualname__\n'C.D.g'\n im_class object.__set_name__" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
306,132
<p>I have a site made with php which uses server side sessions throughout the site.<br> In fact, it's a site with a user login which depends on session variables and if there were a problem with <em>all</em> session variables, no pages would load at all. </p> <p>On the site, there's an iframe that holds a feed of little messages from other users.<br> Those little messages have clickable photos next to them that open the user's profile.<br> Now, each page requires some formatting to open the user's profile on that specific page...there's really only a few <em>problem</em> pages, but those pages have to have the onclick functions formatted a little differently or they break the page.<br> So I set a session variable on each page (<code>$_SESSION["current_page"]</code>) that lets the feed know how to format the clickable photos. Now Firefox, Opera, Chrome, Safari all work as they are supposed to.<br> But IE6 and IE7 are having problems on the pages that require special formatting.<br> So after pulling my hair out a bit, I eventually got around to printing my session variables form the server.<br> And lo and behold, on the special pages, (<code>$_SESSION["current_page"]</code>) is always set to "main" instead of "special1" or "special2". </p> <p>I printed the same session variable in Firefox and all the other browsers I mentioned and they print out "special1" or "special2" as they're supposed to.<br> Can anyone think of something - possibly related to the fact that the feed is in an iframe??? - that would cause IE to treat server side session variables differently or somehow launch page "main" silently in the background?<br> I have checked the feed very carefully for any reference to page "main" - it doesn't seem like there's any ways it's loading that page. </p> <p>this doesn't make sense to me. </p>
[ { "answer_id": 310288, "author": "seans", "author_id": 39385, "author_profile": "https://Stackoverflow.com/users/39385", "pm_score": 3, "selected": true, "text": "<img src= \"\" >" }, { "answer_id": 2146737, "author": "dotcolor", "author_id": 260047, "author_profile": "https://Stackoverflow.com/users/260047", "pm_score": 0, "selected": false, "text": "session.cookie_lifetime session.cookie_lifetime: 4500 session.cookie_lifetime:0" }, { "answer_id": 2955720, "author": "RAT", "author_id": 263217, "author_profile": "https://Stackoverflow.com/users/263217", "pm_score": 2, "selected": false, "text": "header('P3P: CP=”NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM”');\n header('P3P: CP=”NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM”');\n\nheader('Set-Cookie: SIDNAME=ronty; path=/; secure');\n\nheader('Cache-Control: no-cache');\n\nheader('Pragma: no-cache');\n header('location: land_for_sale.php?phpSESSID='.session_id());\n" }, { "answer_id": 4071460, "author": "David Stone", "author_id": 493868, "author_profile": "https://Stackoverflow.com/users/493868", "pm_score": 2, "selected": false, "text": "header('P3P: CP=\"CAO PSA OUR\"');" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39385/" ]
306,136
<p>I know I could do this with closures (<code>var self = this</code>) if object was a function:</p> <pre><code>&lt;a href=&quot;#&quot; id=&quot;x&quot;&gt;click here&lt;/a&gt; &lt;script type=&quot;text/javascript&quot;&gt; var object = { y : 1, handle_click : function (e) { alert('handling click'); //want to access y here return false; }, load : function () { document.getElementById('x').onclick = this.handle_click; } }; object.load(); &lt;/script&gt; </code></pre>
[ { "answer_id": 306151, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "var object = { \n y : 1, \n handle_click : function (e) {\n alert('handling click');\n\n //want to access y here \n alert(this.y); \n\n return false; \n }, \n load : function () { \n var that = this; \n document.getElementById('x').onclick = function(e) {\n that.handle_click(e); // pass-through the event object\n }; \n } \n}; \nobject.load();\n" }, { "answer_id": 306225, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "handle_click var self=this;\n document.getElementById('x').onclick = \n function(e) { return self.handle_click(e) };\n bind : function(fn)\n{\n var self = this;\n // copy arguments into local array\n var args = Array.prototype.slice.call(arguments, 0); \n // returned function replaces first argument with event arg,\n // calls fn with composite arguments\n return function(e) { args[0] = e; return fn.apply(self, args); };\n},\n document.getElementById('x').onclick = this.bind(this.handle_click, \n \"this parameter is passed to handle_click()\",\n \"as is this one\");\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
306,139
<p>I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using <code>#!/usr/bin/env groovy</code> at the top of my script. </p>
[ { "answer_id": 306168, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 6, "selected": true, "text": "this.getClass().classLoader.rootLoader.addURL(new File(\"file.jar\").toURL())\n" }, { "answer_id": 8945888, "author": "Patrick", "author_id": 54396, "author_profile": "https://Stackoverflow.com/users/54396", "pm_score": 6, "selected": false, "text": "#!/usr/bin/env groovy #! #!/usr/bin/env groovy -d /usr/bin/env groovy -d groovy d #!/bin/bash \n//usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml \"$0\" $@; exit $?\n\nimport org.springframework.class.from.jar\n//other groovy code\nprintln 'Hello'\n bash bash bash # // / bash /usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml \"$0\" $@ \"$0\" $@ bash bash exit $?1" }, { "answer_id": 9692013, "author": "Spina", "author_id": 170587, "author_profile": "https://Stackoverflow.com/users/170587", "pm_score": 5, "selected": false, "text": "@Grab(group='com.google.collections', module='google-collections', version='1.0')\n" }, { "answer_id": 30503877, "author": "Maarten Boekhold", "author_id": 1023458, "author_profile": "https://Stackoverflow.com/users/1023458", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n//bin/true && OPTS=\"-cp blah.jar -Dmyopt=value\"\n//bin/true && OPTS=\"$OPTS -Dmoreopts=value2\"\n//usr/bin/env groovy $OPTS \"$0\" $@; exit $?\n\nprintln \"inside my groovy script\"\n" }, { "answer_id": 34416832, "author": "Jim Hurne", "author_id": 106189, "author_profile": "https://Stackoverflow.com/users/106189", "pm_score": 3, "selected": false, "text": "#!/bin/bash\n// 2>/dev/null; SCRIPT_DIR=\"$( cd \"$( dirname \"$0\" )\" && pwd )\"\n// 2>/dev/null; OPTS=\"-cp $SCRIPT_DIR/lib/extra.jar:$SCRIPT_DIR/lib/spring.jar\"\n// 2>/dev/null; OPTS=\"$OPTS -d\"\n// 2>/dev/null; OPTS=\"$OPTS -Dlog4j.configuration=file:/etc/myapp/log4j.xml\"\n// 2>/dev/null; exec groovy $OPTS \"$0\" \"$@\"; exit $?\n\nimport org.springframework.class.from.jar\n//other groovy code\nprintln 'Hello'\n // // /dev/null exec ps exit $? exec groovy" }, { "answer_id": 35587413, "author": "Andreas Covidiot", "author_id": 1915920, "author_profile": "https://Stackoverflow.com/users/1915920", "pm_score": 2, "selected": false, "text": "import // printEmployees.groovy\nthis.class.classLoader.rootLoader.addURL(\n new URL(\"file:///C:/app/Dustin/product/11.1.0/db_1/jdbc/lib/ojdbc6.jar\"))\nimport groovy.sql.Sql\nsql = Sql.newInstance(\"jdbc:oracle:thin:@localhost:1521:orcl\", \"hr\", \"hr\",\n \"oracle.jdbc.pool.OracleDataSource\")\nsql.eachRow(\"SELECT employee_id, last_name, first_name FROM employees\")\n{\n println \"The employee's name is ${it.first_name} ${it.last_name}.\"\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14481/" ]
306,144
<p>I am having trouble deleting orphan nodes using JPA with the following mapping</p> <pre><code>@OneToMany (cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "owner") private List&lt;Bikes&gt; bikes; </code></pre> <p>I am having the issue of the orphaned roles hanging around the database.</p> <p>I can use the annotation <code>org.hibernate.annotations.Cascade</code> Hibernate specific tag but obviously I don't want to tie my solution into a Hibernate implementation.</p> <p><strong>EDIT</strong>: It seems JPA 2.0 will include support for this.</p>
[ { "answer_id": 307203, "author": "Varun Mehta", "author_id": 31537, "author_profile": "https://Stackoverflow.com/users/31537", "pm_score": 8, "selected": true, "text": "CascadeType.DELETE_ORPHAN CascadeType.ALL @OneToMany(mappedBy=\"foo\", orphanRemoval=true)\n" }, { "answer_id": 2928481, "author": "Kango_V", "author_id": 174884, "author_profile": "https://Stackoverflow.com/users/174884", "pm_score": 7, "selected": false, "text": "orphanRemoval=true @xxxToMany CascadeType.DELETE_ORPHAN" }, { "answer_id": 3872221, "author": "Valéry Stroeder", "author_id": 1219782, "author_profile": "https://Stackoverflow.com/users/1219782", "pm_score": 3, "selected": false, "text": "@OneToMany(cascade = CascadeType.ALL, targetEntity = MyClass.class, mappedBy = \"xxx\", fetch = FetchType.LAZY, orphanRemoval = true) \n" }, { "answer_id": 4416620, "author": "Kohan95", "author_id": 514612, "author_profile": "https://Stackoverflow.com/users/514612", "pm_score": 2, "selected": false, "text": "@OneToMany(cascade = CascadeType.ALL, mappedBy = \"xxx\", fetch = FetchType.LAZY, orphanRemoval = true)" }, { "answer_id": 6623538, "author": "reshma", "author_id": 835242, "author_profile": "https://Stackoverflow.com/users/835242", "pm_score": 3, "selected": false, "text": "@OneToMany(mappedBy = \"masterData\", cascade = {\n CascadeType.ALL })\n@PrivateOwned\nprivate List<Data> dataList;\n" }, { "answer_id": 19645397, "author": "Sergii Shevchyk", "author_id": 946224, "author_profile": "https://Stackoverflow.com/users/946224", "pm_score": 6, "selected": false, "text": "╔═════════════╦═════════════════════╦═════════════════════╗\n║ Action ║ orphanRemoval=true ║ CascadeType.ALL ║\n╠═════════════╬═════════════════════╬═════════════════════╣\n║ delete ║ deletes parent ║ deletes parent ║\n║ parent ║ and orphans ║ and orphans ║\n╠═════════════╬═════════════════════╬═════════════════════╣\n║ change ║ ║ ║\n║ children ║ deletes orphans ║ nothing ║\n║ list ║ ║ ║\n╚═════════════╩═════════════════════╩═════════════════════╝\n" }, { "answer_id": 33465120, "author": "Bevor", "author_id": 319773, "author_profile": "https://Stackoverflow.com/users/319773", "pm_score": 2, "selected": false, "text": "@OneToMany(mappedBy = \"menuPlan\", cascade = CascadeType.ALL, orphanRemoval = true)\nprivate List<Dish> dishes = new ArrayList<>();\n EntityManager.find(...) EntityManager.remove(...)" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050/" ]
306,169
<p>In our web applications, we seperate our Data Access Layers out into their own projects.</p> <p>This creates some problems related to settings. </p> <p>Because the DAL will eventually need to be consumed from perhaps more than one application, web.config does not seem like a good place to keep the connection strings and some of the other DAL-related settings.</p> <p>To solve this, on some of our recent projects we introduced a third project just for settings. We put the setting in a system of .Setting files... With a simple wrapper, the ability to have different settings for various enviroments (Dev, QA, Staging, Production, etc) was easy to achieve.</p> <p>The only problem there is that the settings project (including the .Settings class) compiles into an assembly, so you can't change it without doing a build/deployment, and some of our customers want to be able to configure their projects without Visual Studio.</p> <p>So, is there a best practice for this? I have that sense that I'm reinventing the wheel.</p> <p>Some solutions such as storing settings in a fixed directory on the server in, say, our own XML format occurred to us. But again, I would rather avoid having to re-create encryption for sensitive values and so on. And I would rather keep the solution self-contained if possible.</p> <p><strong>EDIT:</strong> The original question did not contain the really penetrating reason that we can't (I think) use web.config ... That puts a few (very good) answers out of context, my bad.</p>
[ { "answer_id": 306309, "author": "Chris", "author_id": 34942, "author_profile": "https://Stackoverflow.com/users/34942", "pm_score": 2, "selected": false, "text": "string connString = ConfigurationManager\n .ConnectionStrings[\"myConnString\"]\n .ConnectionString;\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16082/" ]
306,176
<p>I am following a VB tutorial to do some <a href="http://blogs.msdn.com/bethmassi/archive/2008/04/25/querying-html-with-linq-to-xml.aspx" rel="nofollow noreferrer">HTML manipulation using LINQ</a> </p> <p>It has the following construct</p> <pre><code>Imports &lt;xmlns="http://www.w3.org/1999/xhtml"&gt; </code></pre> <p>How do I do the same in C#?</p> <p>There appears to be something called an XMLNamespaceManager that may hold the solution, but I am too foolish to understand how to work it, and I am not sure it is the correct tree to bark up.</p> <p>Got any advice?</p>
[ { "answer_id": 306216, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "XML Literals" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5552/" ]
306,191
<p>I have a list of error codes I need to reference, kinda like this:</p> <pre><code>Code / Error Message A01 = whatever error U01 = another error U02 = yet another error type </code></pre> <p>I get the Code returned to me via a web service call and I need to display or get the readable error. So I need a function when passed a Code that returns the readable description. I was just going to do a select case but thought their might be a better way. What is the best way / most effieient way to do this?</p>
[ { "answer_id": 306201, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "// Initialize this once, and store it in the ASP.NET Cache.\nDictionary<String,String> errorCodes = new Dictionary<String,String>();\n\nerrorCodes.Add(\"A01\", \"Whatever Error\");\nerrorCodes.Add(\"U01\", \"Another Error\");\n\n\n// And to get your error code:\n\nstring ErrCode = errorCodes[ErrorCodeFromWS];\n" }, { "answer_id": 306224, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public static class ErrorCodes\n{\n private static Dictonary<string, string> s_codes = new Dicontary<string, string>();\n static ErrorCodes()\n {\n s_codes[\"code\"] = \"Description\";\n s_codes[\"code2\"] = \"Description2\";\n }\n\n public static string GetDesc(string code)\n {\n return s_codes[code];\n }\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34548/" ]
306,233
<p>I have several deployment projects. In order to deploy an application, I need to do several tasks, one of them is to change each deployment project's product version and product code.</p> <p>I can't find a way to programmatically change them.</p> <p>Since it's a Deployment project (which finally produces an executable installer), I'm not able to work with MSBuild, instead I'm using the Devenv from the command prompt.</p>
[ { "answer_id": 398093, "author": "TheCodeMonk", "author_id": 28956, "author_profile": "https://Stackoverflow.com/users/28956", "pm_score": 5, "selected": true, "text": "static void Main(string[] args) \n{\n string setupFileName = @\"<Replace the path to vdproj file>\"; \n StreamReader reader = File.OpenText(setupFileName); \n string file = string.Empty; \n\n try \n { \n Regex expression = new Regex(@\"(?:\\\"\"ProductCode\\\"\" = \n \\\"\"8.){([\\d\\w-]+)}\"); \n Regex expression1 = new Regex(@\"(?:\\\"\"UpgradeCode\\\"\" = \n \\\"\"8.){([\\d\\w-]+)}\"); \n file = reader.ReadToEnd(); \n\n file = expression.Replace(file, \"\\\"ProductCode\\\" = \\\"8:{\" + \n Guid.NewGuid().ToString().ToUpper() + \"}\"); \n file = expression1.Replace(file, \"\\\"UpgradeCode\\\" = \\\"8:{\" \n + Guid.NewGuid().ToString().ToUpper() + \"}\"); \n } \n finally \n { \n // Close the file otherwise the compile may not work \n reader.Close(); \n } \n\n TextWriter tw = new StreamWriter(setupFileName); \n try \n { \n tw.Write(file); \n } \n finally \n { \n // close the stream \n tw.Close(); \n } \n }\n" }, { "answer_id": 398183, "author": "bsruth", "author_id": 23504, "author_profile": "https://Stackoverflow.com/users/23504", "pm_score": 3, "selected": false, "text": "/////////////////////////////////////////////////////////////////////////////\n//\n// Version\n//\n\nVS_VERSION_INFO VERSIONINFO\n FILEVERSION FILE_VER\n PRODUCTVERSION PROD_VER\n FILEFLAGSMASK 0x3fL\n#ifdef _DEBUG\n FILEFLAGS 0x1L\n#else\n FILEFLAGS 0x0L\n#endif\n FILEOS 0x4L\n FILETYPE 0x1L\n FILESUBTYPE 0x0L\nBEGIN\n BLOCK \"StringFileInfo\"\n BEGIN\n BLOCK \"040904e4\"\n BEGIN\n VALUE \"CompanyName\", \"MyCompany\"\n VALUE \"FileDescription\", \"Software Description\"\n VALUE \"FileVersion\", 1,0,0,1\n VALUE \"InternalName\", \"FileName.exe\"\n VALUE \"LegalCopyright\", \"(c) 2008 My Company. All rights reserved.\"\n VALUE \"OriginalFilename\", \"FileName.exe\"\n VALUE \"ProductName\", \"Product Name\"\n VALUE \"ProductVersion\", 1,0,0,1\n END\n END\n BLOCK \"VarFileInfo\"\n BEGIN\n VALUE \"Translation\", 0x409, 1252\n END\nEND\n #pragma once\n\n//major release version of the program, increment only when major changes are made\n#define VER_MAJOR 2\n\n//minor release version of the program, increment if any new features are added\n#define VER_MINOR 0\n\n//any bugfix updates, no new features\n#define VER_REV 0\n\n//if this is some special release (e.g. Alpha 1) put the special release string here\n#define STR_SPECIAL_REL \"Alpha 1\"\n\n\n#define FILE_VER VER_MAJOR,VER_MINOR,VER_REV\n#define PROD_VER FILE_VER\n\n//these are special macros that convert numerical version tokens into string tokens\n//we can't use actual int and string types because they won't work in the RC files\n#define STRINGIZE2(x) #x\n#define STRINGIZE(x) STRINGIZE2(x)\n\n#define STR_FILE_VER STRINGIZE(VER_MAJOR) \".\" STRINGIZE(VER_MINOR) \".\" STRINGIZE(VER_REV)\n#define STR_PROD_VER STR_FILE_VER \" \" STR_SPECIAL_REL\n\n#define STR_COPYRIGHT_INFO \"©\" BuildYear \" Your Company. All rights reserved.\"\n #include \"VersionInfo.h\"\n/////////////////////////////////////////////////////////////////////////////\n//\n// Version\n//\n\n<no changes>\n VALUE \"FileVersion\", STR_FILE_VER\n <no changes>\n VALUE \"LegalCopyright\", STR_COPYRIGHT_INFO\n <no changes>\n VALUE \"ProductVersion\", STR_PROD_VER\n<no changes>\n #define CurrentBuildNumber \"20081020P1525\" \n echo Generating Build Number\n @For /F \"tokens=2,3,4 delims=/ \" %%A in ('Date /t') do @(\n Set Month=%%A\n Set Day=%%B\n Set Year=%%C\n )\n\n @For /F \"tokens=1,2,3 delims=/M: \" %%A in ('Time /t') do @(\n Set Hour=%%A\n Set Minute=%%B\n Set AmPm=%%C\n )\n\n @echo #define CurrentBuildNumber \"%Year%%Month%%Day%%AmPm%%Hour%%Minute%\" > \"$(ProjectDir)\\build_number.incl\"\n @echo #define BuildYear \"%Year%\" >> \"$(ProjectDir)\\build_number.incl\"\n echo ----------------------------------------------------------------------\n" }, { "answer_id": 629293, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": ".vdproj prebuildevent msi postbuildevent" }, { "answer_id": 31957619, "author": "Scott C", "author_id": 4096939, "author_profile": "https://Stackoverflow.com/users/4096939", "pm_score": 0, "selected": false, "text": "Function CreateGuid()\n CreateGuid = Left(CreateObject(\"Scriptlet.TypeLib\").Guid,38)\nEnd Function\n\nConst ForReading = 1, ForWriting = 2, ForAppending = 8\n\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\nSet RegEx = CreateObject(\"VBScript.RegExp\")\n\nFor Each file in fso.GetFolder(\".\").Files\n if (fso.GetExtensionName(file.Name) = \"vdproj\") then\n WScript.Echo \"Updating: \" + file.Name\n Set oFile = fso.OpenTextFile(file.Name, ForReading, True)\n fileContents = oFile.ReadAll\n oFile.Close\n RegEx.Pattern = \"\"\"ProductCode\"\" = \"\"8:{.*-.*-.*-.*-.*}\"\n fileContents=Regex.Replace(fileContents, \"\"\"ProductCode\"\" = \"\"8:\" & CreateGuid)\n Set oFile = fso.OpenTextFile(file.Name, ForWriting, True)\n oFile.Write fileContents\n oFile.Close\n end if\nNext\n cd $(SolutionDir)\\CustomWebSetup\ncscript -nologo UpdateProductCode.vbs\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30339/" ]
306,252
<p>This is one of the minor CSS problems that plague me constantly.</p> <p>How do folks around Stack Overflow vertically align <em><strong><code>checkboxes</code></strong></em> and their <em><strong><code>labels</code></strong></em> consistently <strong>cross-browser</strong>?</p> <p>Whenever I align them correctly in Safari (usually using <code>vertical-align: baseline</code> on the <code>input</code>), they're completely off in Firefox and IE.</p> <p>Fix it in Firefox, and Safari and IE are inevitably messed up. I waste time on this every time I code a form.</p> <p>Here's the standard code that I work with:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt; &lt;div&gt; &lt;label&gt;&lt;input type="checkbox" /&gt; Label text&lt;/label&gt; &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>I usually use Eric Meyer's reset, so form elements are relatively clean of overrides. Looking forward to any tips or tricks that you have to offer!</p>
[ { "answer_id": 306266, "author": "digitalsanctum", "author_id": 22436, "author_profile": "https://Stackoverflow.com/users/22436", "pm_score": 7, "selected": false, "text": "vertical-align: middle <form>\n <div>\n <input id=\"blah\" type=\"checkbox\"><label for=\"blah\">Label text</label>\n </div>\n</form>" }, { "answer_id": 306593, "author": "One Crayon", "author_id": 38666, "author_profile": "https://Stackoverflow.com/users/38666", "pm_score": 11, "selected": true, "text": "label {\n display: block;\n padding-left: 15px;\n text-indent: -15px;\n}\ninput {\n width: 13px;\n height: 13px;\n padding: 0;\n margin:0;\n vertical-align: bottom;\n position: relative;\n top: -1px;\n *overflow: hidden;\n} <form>\n <div>\n <label><input type=\"checkbox\" /> Label text</label>\n </div>\n</form> *overflow vertical-align vertical-align: bottom overflow: hidden" }, { "answer_id": 306613, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 3, "selected": false, "text": "<form>\n <div>\n <input type=\"checkbox\" id=\"cb\" /> <label for=\"cb\">Label text</label>\n </div>\n</form>\n" }, { "answer_id": 306889, "author": "Bryan A", "author_id": 29707, "author_profile": "https://Stackoverflow.com/users/29707", "pm_score": 5, "selected": false, "text": "label {\n line-height: 18px;\n}\ninput {\n width: 13px;\n height: 18px;\n font-size: 12px;\n line-height: 12px;\n} <form>\n <div>\n <label><input type=\"checkbox\" /> Label text</label>\n </div>\n</form>" }, { "answer_id": 395870, "author": "Waleed Eissa", "author_id": 676066, "author_profile": "https://Stackoverflow.com/users/676066", "pm_score": 5, "selected": false, "text": "* {\n padding: 0px;\n margin: 0px;\n}\n#wb {\n width: 15px;\n height: 15px;\n float: left;\n}\n#somelabel {\n float: left;\n padding-left: 3px;\n} <div>\n <input id=\"wb\" type=\"checkbox\" />\n <label for=\"wb\" id=\"somelabel\">Web Browser</label>\n</div>" }, { "answer_id": 494922, "author": "Nathan Bowers", "author_id": 60453, "author_profile": "https://Stackoverflow.com/users/60453", "pm_score": 8, "selected": false, "text": ".checkboxes label {\n display: inline-block;\n padding-right: 10px;\n white-space: nowrap;\n}\n.checkboxes input {\n vertical-align: middle;\n}\n.checkboxes label span {\n vertical-align: middle;\n} <form>\n <div class=\"checkboxes\">\n <label><input type=\"checkbox\"> <span>Label text x</span></label>\n <label><input type=\"checkbox\"> <span>Label text y</span></label>\n <label><input type=\"checkbox\"> <span>Label text z</span></label>\n </div>\n</form> .checkboxes label {\n display: block;\n padding-right: 10px;\n padding-left: 22px;\n text-indent: -22px;\n}\n.checkboxes input {\n vertical-align: middle;\n}\n.checkboxes label span {\n vertical-align: middle;\n} <form>\n <div class=\"checkboxes\">\n <label><input type=\"checkbox\"> <span>Label text x so long that it will probably wrap so let's see how it goes with the proposed CSS (expected: two lines are aligned nicely)</span></label>\n <label><input type=\"checkbox\"> <span>Label text y</span></label>\n <label><input type=\"checkbox\"> <span>Label text z</span></label>\n </div>\n</form>" }, { "answer_id": 494950, "author": "dylanfm", "author_id": 38795, "author_profile": "https://Stackoverflow.com/users/38795", "pm_score": 3, "selected": false, "text": "fieldset {\n text-align:left;\n border:none\n}\nfieldset ol, fieldset ul {\n padding:0;\n list-style:none\n}\nfieldset li {\n padding-bottom:1.5em;\n float:none;\n clear:left\n}\nlabel {\n float:left;\n width:7em;\n margin-right:1em\n}\nfieldset.checkboxes li {\n clear:both;\n padding:.75em\n}\nfieldset.checkboxes label {\n margin:0 0 0 1em;\n width:20em\n}\nfieldset.checkboxes input {\n float:left\n} <form>\n <fieldset class=\"checkboxes\">\n <ul>\n <li>\n <input type=\"checkbox\" name=\"happy\" value=\"yep\" id=\"happy\" />\n <label for=\"happy\">Happy?</label>\n </li>\n <li>\n <input type=\"checkbox\" name=\"hungry\" value=\"yep\" id=\"hungry\" />\n <label for=\"hungry\">Hungry?</label>\n </li>\n </ul>\n </fieldset>\n</form>" }, { "answer_id": 663098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "input {\n width: 13px;\n height: 13px;\n padding: 0;\n margin:0;\n vertical-align: top;\n position: relative;\n *top: 1px;\n *overflow: hidden;\n}\nlabel {\n display: block;\n padding: 0;\n padding-left: 15px;\n text-indent: -15px;\n border: 0px solid;\n margin-left: 5px;\n vertical-align: top;\n}\n" }, { "answer_id": 719545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": ".font2 {font-family:Arial; font-size:32px} /* Sample font */\n\ninput[type=checkbox], input[type=radio] {\n vertical-align: middle;\n position: relative;\n bottom: 1px;\n}\n\ninput[type=radio] { \n bottom: 2px; \n} <label><input type=\"checkbox\" /> Label text</label>\n<p class=\"font2\">\n <label><input type=\"checkbox\"/> Label text</label>\n</p> bottom bottom: .08em; .font2, .font2 input {font-family:Arial; font-size:32px} /* Sample font */\n\ninput[type=checkbox], input[type=radio] {\n vertical-align: middle; \n position: relative;\n bottom: .08em; /* this is a better value for different fonts! */\n} <label><input type=\"checkbox\" /> Label text</label> \n\n<p class=\"font2\">\n <label><input type=\"checkbox\"/> Label text</label>\n</p>" }, { "answer_id": 2063445, "author": "Matijs", "author_id": 88097, "author_profile": "https://Stackoverflow.com/users/88097", "pm_score": 2, "selected": false, "text": "<label for=\"id\" class=\"checkbox\">\n <input type=\"checkbox\" id=\"id\">\n <span>The Label</span>\n</label>\n label.checkbox {\n display: block;\n}\n.checkbox input {\n float: left;\n height: 18px;\n vertical-align: middle;\n}\n.checkbox span {\n float: left;\n line-height: 18px;\n margin: 0 0 0 20px;\n}\n" }, { "answer_id": 2318340, "author": "James", "author_id": 279488, "author_profile": "https://Stackoverflow.com/users/279488", "pm_score": -1, "selected": false, "text": "input {\n margin: 0;\n}\n" }, { "answer_id": 2806786, "author": "Frank Schwieterman", "author_id": 32203, "author_profile": "https://Stackoverflow.com/users/32203", "pm_score": 7, "selected": false, "text": "input {\n vertical-align: -2px;\n}\n" }, { "answer_id": 3200615, "author": "rene", "author_id": 386229, "author_profile": "https://Stackoverflow.com/users/386229", "pm_score": 2, "selected": false, "text": "vertical-align: middle\n style=\"position:relative;top:2px;\" 2px" }, { "answer_id": 3959628, "author": "Bob Fanger", "author_id": 19165, "author_profile": "https://Stackoverflow.com/users/19165", "pm_score": 2, "selected": false, "text": "position: relative; input[type=checkbox], input[type=radio] {\n vertical-align: baseline;\n position: relative;\n top: 3px;\n margin: 0 3px 0 0;\n padding: 0px;\n}\ninput.ie7[type=checkbox], input.ie7[type=radio] {\n vertical-align: middle;\n position: static;\n margin-bottom: -2px;\n height: 13px;\n width: 13px;\n}\n $(document).ready(function () {\n if ($.browser.msie && $.browser.version <= 7) {\n $('input[type=checkbox]').addClass('ie7');\n $('input[type=radio]').addClass('ie7');\n }\n});\n <label>" }, { "answer_id": 4566182, "author": "albert", "author_id": 401672, "author_profile": "https://Stackoverflow.com/users/401672", "pm_score": 0, "selected": false, "text": "<fieldset class=\"checks\">\n <legend>checks for whatevers</legend>\n <input type=\"\" id=\"x\" />\n <label for=\"x\">Label</label>\n <input type=\"\" id=\"y\" />\n <label for=\"y\">Label</label>\n <input type=\"\" id=\"z\" />\n <label for=\"z\">Label</label>\n</fieldset>\n fieldset.checks {\n width:200px\n}\n.checks input, .checks label {\n display:block;\n}\n.checks input {\n float:right;\n width:10px;\n margin-right:5px\n}\n.checks label {\n float:left;\n width:180px;\n margin-left:5px;\n text-align:left;\n text-indent:5px\n}\n" }, { "answer_id": 6930648, "author": "Rama Subba Reddy M", "author_id": 868917, "author_profile": "https://Stackoverflow.com/users/868917", "pm_score": 3, "selected": false, "text": "<asp:CheckBoxList> float:left .CheckboxList\n{\n font-size: 14px;\n color: #333333;\n}\n.CheckboxList input\n{\n float: left;\n clear: both;\n}\n <asp:CheckBoxList runat=\"server\" ID=\"c1\" RepeatColumns=\"2\" CssClass=\"CheckboxList\">\n</asp:CheckBoxList>\n" }, { "answer_id": 7277345, "author": "Carlo Pires", "author_id": 236499, "author_profile": "https://Stackoverflow.com/users/236499", "pm_score": 4, "selected": false, "text": "<form>\n <div>\n <label style=\"display: inline-block\">\n <input style=\"vertical-align: middle\" type=\"checkbox\" />\n <span style=\"vertical-align: middle\">Label text</span>\n </label>\n </div>\n</form>" }, { "answer_id": 9530612, "author": "Philip Bevan", "author_id": 1235458, "author_profile": "https://Stackoverflow.com/users/1235458", "pm_score": 2, "selected": false, "text": ".threeCol .listItem {\n width:13.9em;\n padding:.2em;\n margin:.2em;\n float:left;\n border-bottom:solid #f3f3f3 1px;\n}\n.threeCol input {\n float:left;\n width:auto;\n margin:.2em .2em .2em 0;\n border:none;\n background:none;\n}\n.threeCol label {\n float:left;\n margin:.1em 0 .1em 0;\n}\n <div class=\"threeCol\">\n <div class=\"listItem\">\n <input type=\"checkbox\" name=\"name\" id=\"id\" value=\"checkbox1\" />\n <label for=\"name\">This is your checkBox</label>\n </div>\n</div>\n" }, { "answer_id": 13535861, "author": "user966939", "author_id": 966939, "author_profile": "https://Stackoverflow.com/users/966939", "pm_score": -1, "selected": false, "text": "<label class=\"boxfix\"><input type=\"radio\">Label</label>\n .boxfix {\n vertical-align: bottom;\n}\n.boxfix input {\n margin: 0;\n vertical-align: bottom;\n position: relative;\n top: 1.999px; /* the inputs are slightly more centered in IE at 1px (they don't interpret the .999 here), and Opera will round it to 2px with three decimals */\n}\n" }, { "answer_id": 15854531, "author": "Sunil D.", "author_id": 398606, "author_profile": "https://Stackoverflow.com/users/398606", "pm_score": 2, "selected": false, "text": "checkbox <label> <label class=\"checkbox\">\n <input type=\"checkbox\"> Remember me\n</label>\n" }, { "answer_id": 16063190, "author": "Patrick", "author_id": 1359306, "author_profile": "https://Stackoverflow.com/users/1359306", "pm_score": 5, "selected": false, "text": "<label class=\"checkbox\"><input type=\"checkbox\" value=\"0000\">0000 - 0100</label>\n 24px line-height 24px vertical-align: top; vertical-align: bottom; input[type=\"checkbox\"] {\n width: 24px;\n height: 24px;\n vertical-align: bottom;\n}\nlabel.checkbox {\n vertical-align: top;\n line-height: 24px;\n margin: 2px 0;\n display: block;\n height: 24px;\n} <label class=\"checkbox\"><input type=\"checkbox\" value=\"0000\">0000 - 0100</label>\n<label class=\"checkbox\"><input type=\"checkbox\" value=\"0100\">0100 - 0200</label>\n<label class=\"checkbox\"><input type=\"checkbox\" value=\"0200\">0200 - 0300</label>\n<label class=\"checkbox\"><input type=\"checkbox\" value=\"0300\">0300 - 0400</label>" }, { "answer_id": 16825097, "author": "Geoff Kendall", "author_id": 1416104, "author_profile": "https://Stackoverflow.com/users/1416104", "pm_score": 1, "selected": false, "text": ".checkboxlabel {\n width: 100%;\n vertical-align: middle;\n}\n.checkbox {\n width: 20px !important;\n}\n <label for='acheckbox' class='checkboxlabel'>\n <input name=\"acheckbox\" id='acheckbox' type=\"checkbox\" class='checkbox'>Contact me</label>\n" }, { "answer_id": 17934915, "author": "Milche Patern", "author_id": 845310, "author_profile": "https://Stackoverflow.com/users/845310", "pm_score": -1, "selected": false, "text": "button, checkbox, input, radio, textarea, submit, reset, search, any-form-field {\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n}\n" }, { "answer_id": 18323580, "author": "MusikAnimal", "author_id": 604142, "author_profile": "https://Stackoverflow.com/users/604142", "pm_score": 3, "selected": false, "text": "div.checkbox {\n position: relative;\n font-family: Arial;\n font-size: 13px;\n}\nlabel {\n position: relative;\n padding-left: 16px;\n}\nlabel::before {\n content :\"\";\n display: inline-block;\n width: 10px;\n height: 10px;\n background-color: white;\n border: solid 1px #9C9C9C;\n position: absolute;\n top: 1px;\n left: 0px;\n}\nlabel::after {\n content:\"\";\n width: 8px;\n height: 8px;\n background-color: #666666;\n position: absolute;\n left: 2px;\n top: 3px;\n display: none;\n}\ninput[type=checkbox] {\n visibility: hidden;\n position: absolute;\n}\ninput[type=checkbox]:checked + label::after {\n display: block;\n}\ninput[type=checkbox]:active + label::before {\n background-color: #DDDDDD;\n} <form>\n <div class=\"checkbox\">\n <input id=\"check_me\" type=checkbox />\n <label for=\"check_me\">Label for checkbox</label>\n </div>\n</form>" }, { "answer_id": 20093185, "author": "Web Designer cum Promoter", "author_id": 1012591, "author_profile": "https://Stackoverflow.com/users/1012591", "pm_score": -1, "selected": false, "text": "input[type=\"checkbox\"] {\n -moz-appearance: checkbox;\n -webkit-appearance: checkbox;\n margin-left:3px;\n border:0;\n vertical-align: middle;\n top: -1px;\n bottom: 1px;\n *overflow: hidden;\n box-sizing: border-box; /* 1 */\n *height: 13px; /* Removes excess padding in IE 7 */\n *width: 13px;\n background: #fff;\n}\n" }, { "answer_id": 20117094, "author": "gidzior", "author_id": 655102, "author_profile": "https://Stackoverflow.com/users/655102", "pm_score": 4, "selected": false, "text": "input {\n position: relative;\n top: 1px;\n} <form>\n <div>\n <label><input type=\"checkbox\" /> Label text</label>\n </div>\n<form>" }, { "answer_id": 24059879, "author": "NinjaKC", "author_id": 584147, "author_profile": "https://Stackoverflow.com/users/584147", "pm_score": 2, "selected": false, "text": "<label><div class=\"checkbox\"><input type=\"checkbox\" /></div> Label text</label>\n <label><input type=\"checkbox\" /><div class=\"checkbox\"></div>Label text</label>\n" }, { "answer_id": 26781309, "author": "waterplea", "author_id": 2706426, "author_profile": "https://Stackoverflow.com/users/2706426", "pm_score": 4, "selected": false, "text": "vertical-align: sub" }, { "answer_id": 28704154, "author": "Buzogany Laszlo", "author_id": 407621, "author_profile": "https://Stackoverflow.com/users/407621", "pm_score": 5, "selected": false, "text": "input[type=checkbox], input[type=radio] {\n vertical-align: -2px;\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 31720808, "author": "Marco Sulla", "author_id": 1763602, "author_profile": "https://Stackoverflow.com/users/1763602", "pm_score": 2, "selected": false, "text": "vertical-align: sub <div class=\"checkboxes\">\n <label for=\"check1\">Test</label>\n <input id=\"check1\" type=\"checkbox\"></input>\n</div>\n .checkboxes input {\n vertical-align: sub;\n}\n" }, { "answer_id": 32610826, "author": "Henrik Erlandsson", "author_id": 343825, "author_profile": "https://Stackoverflow.com/users/343825", "pm_score": 2, "selected": false, "text": "input, label {display:block;float:left;height:1em;line-height:1em;}\n #myform input, #myform label {font-size:20px;}\n" }, { "answer_id": 38558007, "author": "Bryan Willis", "author_id": 1728524, "author_profile": "https://Stackoverflow.com/users/1728524", "pm_score": 4, "selected": false, "text": "<style>\nlabel {\n display: flex;\n align-items: center;\n}\ninput[type=radio], input[type=checkbox]{\n flex: none;\n}\n</style>\n<form>\n <div>\n <label><input type=\"checkbox\" /> Label text</label>\n </div>\n</form>\n label {\n display: -webkit-box;\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -webkit-align-items: center;\n -ms-flex-align: center;\n align-items: center;\n}\ninput[type=radio], \ninput[type=checkbox] {\n -webkit-box-flex: 0;\n -webkit-flex: none;\n -ms-flex: none;\n flex: none;\n margin-right: 10px; \n}\n/* demo only (to show alignment) */\nform {\n max-width: 200px\n} <form>\n <label>\n <input type=\"radio\" checked>\n I am an aligned radio and label\n </label>\n <label>\n <input type=\"checkbox\" checked>\n I am an aligned checkbox and label\n </label>\n</form>" }, { "answer_id": 44532070, "author": "Prime", "author_id": 1379440, "author_profile": "https://Stackoverflow.com/users/1379440", "pm_score": 2, "selected": false, "text": "input[type=checkbox]\n{\n vertical-align: middle;\n} <input id=\"testCheckbox\" name=\"testCheckbox\" type=\"checkbox\">\n<label for=\"testCheckbox\">I should align</label>" }, { "answer_id": 52067228, "author": "dsharhon", "author_id": 3670638, "author_profile": "https://Stackoverflow.com/users/3670638", "pm_score": 1, "selected": false, "text": "<label style=\"display:block\">\n <input style=\"vertical-align:middle\" type=\"checkbox\">\n <span style=\"vertical-align:middle\">Label</span>\n</label>\n" }, { "answer_id": 54451651, "author": "vladiim", "author_id": 688791, "author_profile": "https://Stackoverflow.com/users/688791", "pm_score": 0, "selected": false, "text": "div {\n clear: both;\n float: none;\n position: relative;\n}\n\ninput {\n left: 5px;\n position: absolute;\n top: 3px;\n}\n\nlabel {\n display: block;\n margin-left: 20px;\n}\n" }, { "answer_id": 56558431, "author": "YakovL", "author_id": 3995261, "author_profile": "https://Stackoverflow.com/users/3995261", "pm_score": 4, "selected": false, "text": "vertical-align: middle .checkbox-custom {\n opacity: 0;\n position: absolute;\n}\n.checkbox-custom,\n.checkbox-custom-label {\n display: inline-block;\n vertical-align: middle;\n margin: 5px;\n cursor: pointer;\n}\n.checkbox-custom + .checkbox-custom-label:before {\n content: '';\n display: inline-block;\n background: #fff;\n border-radius: 5px;\n border: 2px solid #ddd;\n vertical-align: middle;\n width: 10px;\n height: 10px;\n padding: 2px;\n margin-right: 10px;\n text-align: center;\n}\n.checkbox-custom:checked + .checkbox-custom-label:before {\n width: 1px;\n height: 5px;\n border: solid blue;\n border-width: 0 3px 3px 0;\n transform: rotate(45deg);\n -webkit-transform: rotate(45deg);\n -ms-transform: rotate(45deg);\n border-radius: 0px;\n margin: 0px 15px 5px 5px;\n} <div>\n <input id=\"checkbox-1\" class=\"checkbox-custom\" name=\"checkbox-1\" type=\"checkbox\">\n <label for=\"checkbox-1\" class=\"checkbox-custom-label\">First Choice</label>\n</div>\n<div>\n <input id=\"checkbox-2\" class=\"checkbox-custom\" name=\"checkbox-2\" type=\"checkbox\">\n <label for=\"checkbox-2\" class=\"checkbox-custom-label\">Second Choice</label>\n</div> input {\n zoom: 10;\n box-shadow: 0 0 1px inset #999;\n} <input type=checkbox> zoom zoom scale input {\n transform: scale(10) translate(50%, 50%);\n box-shadow: 0 0 1px inset #999;\n} <input type=checkbox> width height size zoom scale zoom scale size width height vertical-align middle baseline top input[type=\"checkbox\"] {\n height: 0.95em;\n width: 0.95em;\n}\nlabel, input {\n vertical-align: top;\n} <label><input type=\"checkbox\">label</label>" }, { "answer_id": 61733681, "author": "J. Jerez", "author_id": 8000120, "author_profile": "https://Stackoverflow.com/users/8000120", "pm_score": 0, "selected": false, "text": "label {\n display: inline-block;\n padding-right: 10px;\n}\ninput[type=checkbox] {\n position: relative;\n top: 2px;\n}\n" }, { "answer_id": 70004468, "author": "ALeX inSide", "author_id": 1085386, "author_profile": "https://Stackoverflow.com/users/1085386", "pm_score": 1, "selected": false, "text": "input {\n vertical-align: text-top;\n}" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38666/" ]
306,271
<p>I'd like some advice on designing a REST API which will allow clients to add/remove large numbers of objects to a collection efficiently.</p> <p>Via the API, clients need to be able to add items to the collection and remove items from it, as well as manipulating existing items. In many cases the client will want to make bulk updates to the collection, e.g. adding 1000 items and deleting 500 different items. It feels like the client should be able to do this in a single transaction with the server, rather than requiring 1000 separate POST requests and 500 DELETEs. </p> <p>Does anyone have any info on the best practices or conventions for achieving this?</p> <p>My current thinking is that one should be able to PUT an object representing the change to the collection URI, but this seems at odds with the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6" rel="noreferrer">HTTP 1.1 RFC</a>, which seems to suggest that the data sent in a PUT request should be interpreted independently from the data already present at the URI. This implies that the client would have to send a complete description of the new state of the collection in one go, which may well be very much larger than the change, or even be more than the client would know when they make the request.</p> <p>Obviously, I'd be happy to deviate from the RFC if necessary but would prefer to do this in a conventional way if such a convention exists.</p>
[ { "answer_id": 340161, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 0, "selected": false, "text": "If-Unmodified-Since" }, { "answer_id": 59979381, "author": "Shyam", "author_id": 4527664, "author_profile": "https://Stackoverflow.com/users/4527664", "pm_score": 0, "selected": false, "text": "Pass Only Id Array of Deletable Objects from Front End Application To Web API\n 2. Then You have Two Options: \n 2.1 Web API Way : Find All Collections/Entities using Id arrays and Delete in API , but you need to take care of Dependant entities like Foreign Key Relational Table Data too\n 2.2. Database Way : Pass Ids to your database side, find all records in Foreign Key Tables and Primary Key Tables and Delete in same order i.e. F-Key Table records then P-Key Table records\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20011/" ]
306,272
<p>Say I have a class with a private dispatch table. </p> <pre><code>$this-&gt;dispatch = array( 1 =&gt; $this-&gt;someFunction, 2 =&gt; $this-&gt;anotherFunction ); </code></pre> <p>If I then call </p> <pre><code>$this-&gt;dispatch[1](); </code></pre> <p>I get an error that the method is not a string. When I make it a string like this: </p> <pre><code>$this-&gt;dispatch = array( 1 =&gt; '$this-&gt;someFunction' ); </code></pre> <p>This produces <strong>Fatal error: Call to undefined function $this->someFunction()</strong></p> <p>I have also tried using:</p> <pre><code>call_user_func(array(SomeClass,$this-&gt;dispatch[1])); </code></pre> <p>Resulting in <strong>Message: call_user_func(SomeClass::$this->someFunction) [function.call-user-func]: First argument is expected to be a valid callback</strong>.</p> <p><strong>Edit:</strong> I realized that this didn't really make sense since it is calling SomeClass::$this when $this is SomeClass. I have tried this a few ways, with the array containing </p> <pre><code>array($this, $disptach[1]) </code></pre> <p>This still does not accomplish what I need.</p> <p><strong>End edit</strong></p> <p>This works if I do not have a class and just have a dispatch file with some functions. For example, this works:</p> <pre><code>$dispatch = array( 1 =&gt; someFunction, 2 =&gt; anotherFunction ); </code></pre> <p>I'm wondering if there is a way that I can still keep these as private methods in the class yet still use them with the dispatch table.</p>
[ { "answer_id": 306302, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 4, "selected": true, "text": "$this->dispatch = array('somemethod', 'anothermethod');\n $method = $this->dispatch[1];\n$this->$method();\n" }, { "answer_id": 306358, "author": "Waquo", "author_id": 34149, "author_profile": "https://Stackoverflow.com/users/34149", "pm_score": 3, "selected": false, "text": "$this->dispatch = array('somemethod', 'anothermethod');\n...\ncall_user_func(array($this,$this->dispatch[1]));\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797/" ]
306,284
<p>So, I have a pair of typeclasses that I'll be using a lot together, and I want to avoid specifying both each time. Basically, instead of putting</p> <pre><code>:: (Ord a, Fractional a, Ord b, Fractional b, ... Ord z, Fractional z) =&gt; </code></pre> <p>at the beginning of all my type specifications, I'd rather put</p> <pre><code>:: (OrdFractional a, OrdFractional b, ... OrdFractional z) </code></pre> <p>So, my initial idea on how to do this was to just declare a new typeclass</p> <pre><code>module Example where class (Fractional a, Ord a) =&gt; OrdFractional a example :: (OrdFractional a, OrdFractional b) =&gt; (a,b) -&gt; (a,b) -&gt; (a,b) -&gt; Bool example (x1,y1) (x2,y2) (x3,y3) = (x1/x2 &lt; x2/x3) &amp;&amp; (y1/y2 &lt; y2/y3) </code></pre> <p>But this didn't work as automagically as I wished it would:</p> <pre><code>% ghci Prelude&gt; :l Example.hs Ok, modules loaded: Example. Prelude Example&gt; example (1::Float,3::Float) (2,2) (3,1) &lt;interactive&gt;:1:0: No instance for (OrdFractional Float) arising from a use of `example' at &lt;interactive&gt;:1:0-39 Possible fix: add an instance declaration for (OrdFractional Float) In the expression: example (1 :: Float, 3 :: Float) (2, 2) (3, 1) In the definition of `it': it = example (1 :: Float, 3 :: Float) (2, 2) (3, 1) </code></pre> <p>Manually creating instances seems like a drag so, next, I thought I might try to automatically create instances:</p> <pre><code>module Example where class OrdFractional a instance (Fractional a, Ord a) =&gt; OrdFractional a example :: (OrdFractional a, OrdFractional b) =&gt; (a,b) -&gt; (a,b) -&gt; (a,b) -&gt; Bool example (x1,y1) (x2,y2) (x3,y3) = (x1/x2 &lt; x2/x3) &amp;&amp; (y1/y2 &lt; y2/y3) </code></pre> <p>But the compiler didn't like that:</p> <pre><code>ghc -c Example.hs Example.hs:4:0: Illegal instance declaration for `OrdFractional a' (All instance types must be of the form (T a1 ... an) where a1 ... an are type *variables*, and each type variable appears at most once in the instance head. Use -XFlexibleInstances if you want to disable this.) In the instance declaration for `OrdFractional a' </code></pre> <p>So is there a way I can do this?</p>
[ { "answer_id": 1077908, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "Use -XFlexibleInstances {-# LANGUAGE FlexibleInstances #-}\n {-# LANGUAGE FlexibleInstances, UndecidableInstances #-}\n => OrdFractional a Fractional a Ord a a" }, { "answer_id": 13621000, "author": "javawizard", "author_id": 992720, "author_profile": "https://Stackoverflow.com/users/992720", "pm_score": 6, "selected": true, "text": "Constraint {-# LANGUAGE ConstraintKinds #-}\n\ntype OrdFractional a = (Ord a, Fractional a)\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9859/" ]
306,288
<p>I've been trying to create a custom control that works exactly like the Panel control except surrounded by a few divs and such to create a rounded box look. I haven't been able to find a decent example of how to do this. </p> <p>I need to be able to place text and controls inside the control and access it directly without referencing the panel (exactly the way the Panel control works).</p> <p>Does anyone have any examples of this?</p>
[ { "answer_id": 306299, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": true, "text": "INamingContainer public class RoundedCornersPanel : System.Web.UI.WebControls.Panel\n{\n public override RenderBeginTag (HtmlTextWriter writer)\n {\n writer.Write(\"Your rounded corner opening markup\");\n base.RenderBeginTag(writer);\n }\n\n public override RenderEndTag (HtmlTextWriter writer)\n {\n base.RenderEndTag(writer);\n writer.Write(\"Your rounded corner closing markup\"); \n }\n}\n" }, { "answer_id": 306310, "author": "baretta", "author_id": 30052, "author_profile": "https://Stackoverflow.com/users/30052", "pm_score": 2, "selected": false, "text": "protected override void Render ( HtmlTextWriter output )\n{\n output.Write ( \"<div>\" );\n RenderChildren ( output );\n output.Write ( \"</div>\" );\n}\n" }, { "answer_id": 306327, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": -1, "selected": false, "text": "public class myCustomPanel : Panel\n{\n public override void RenderBeginTag(HtmlTextWriter writer)\n {\n writer.AddAttribute(HtmlTextWriterAttribute.Class, \"top_left_corner\");\n writer.RenderBeginTag(HtmlTextWriterTag.Div);\n base.RenderBeginTag(writer);\n }\n\n public override void RenderEndTag(HtmlTextWriter writer)\n {\n base.RenderEndTag(writer);\n writer.RenderEndTag();\n }\n\n}\n" }, { "answer_id": 9393535, "author": "niaher", "author_id": 111438, "author_profile": "https://Stackoverflow.com/users/111438", "pm_score": 4, "selected": false, "text": "using System.ComponentModel;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\n[ToolboxData(\"<{0}:SimpleContainer runat=server></{0}:SimpleContainer>\")]\n[ParseChildren(true, \"Content\")]\npublic class SimpleContainer : WebControl, INamingContainer\n{\n [PersistenceMode(PersistenceMode.InnerProperty)]\n [TemplateContainer(typeof(SimpleContainer))]\n [TemplateInstance(TemplateInstance.Single)]\n public virtual ITemplate Content { get; set; }\n\n public override void RenderBeginTag(HtmlTextWriter writer)\n {\n // Do not render anything.\n }\n\n public override void RenderEndTag(HtmlTextWriter writer)\n {\n // Do not render anything.\n }\n\n protected override void RenderContents(HtmlTextWriter output)\n {\n output.Write(\"<div class='container'>\");\n this.RenderChildren(output);\n output.Write(\"</div>\");\n }\n\n protected override void OnInit(System.EventArgs e)\n {\n base.OnInit(e);\n\n // Initialize all child controls.\n this.CreateChildControls();\n this.ChildControlsCreated = true;\n }\n\n protected override void CreateChildControls()\n {\n // Remove any controls\n this.Controls.Clear();\n\n // Add all content to a container.\n var container = new Control();\n this.Content.InstantiateIn(container);\n\n // Add container to the control collection.\n this.Controls.Add(container);\n }\n}\n <MyControls:SimpleContainer\n ID=\"container1\"\n runat=\"server\">\n <Content>\n <asp:TextBox\n ID=\"txtName\"\n runat=\"server\" />\n\n <asp:Button\n ID=\"btnSubmit\"\n runat=\"server\"\n Text=\"Submit\" />\n </Content>\n</MyControls:SimpleContainer>\n this.btnSubmit.Text = \"Click me!\";\nthis.txtName.Text = \"Jack Sparrow\";\n" }, { "answer_id": 20487498, "author": "SynBiotik", "author_id": 450499, "author_profile": "https://Stackoverflow.com/users/450499", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace Syn.Test\n{\n [DefaultProperty(\"Text\")]\n [ToolboxData(\"<{0}:MultiPanel runat=server></{0}:MultiPanel>\")]\n [ParseChildren(true)]\n [PersistChildren(false)]\n public class MultiPanel : WebControl, INamingContainer\n {\n public ContentContainer LeftContent { get; set; }\n\n public ContentContainer RightContent { get; set; }\n\n protected override void CreateChildControls()\n {\n base.CreateChildControls();\n }\n\n protected override void Render(HtmlTextWriter output)\n {\n output.AddStyleAttribute(\"width\", \"600px\");\n output.RenderBeginTag(HtmlTextWriterTag.Div);\n\n output.AddStyleAttribute(\"float\", \"left\");\n output.AddStyleAttribute(\"width\", \"280px\");\n output.AddStyleAttribute(\"padding\", \"10px\");\n output.RenderBeginTag(HtmlTextWriterTag.Div);\n LeftContent.RenderControl(output);\n output.RenderEndTag();\n\n output.AddStyleAttribute(\"float\", \"left\");\n output.AddStyleAttribute(\"width\", \"280px\");\n output.AddStyleAttribute(\"padding\", \"10px\");\n output.RenderBeginTag(HtmlTextWriterTag.Div);\n RightContent.RenderControl(output);\n output.RenderEndTag();\n\n output.RenderEndTag();\n }\n }\n\n [ParseChildren(false)]\n public class ContentContainer : Control, INamingContainer\n {\n }\n}\n" }, { "answer_id": 27281108, "author": "Hutch", "author_id": 2661556, "author_profile": "https://Stackoverflow.com/users/2661556", "pm_score": 2, "selected": false, "text": "[ParseChildren(false)] false [ToolboxData(\"<{0}:RoundedBox runat=server></{0}:RoundedBox>\")]\n[ParseChildren(false)]\npublic class RoundedBox : WebControl, INamingContainer\n{\n public override void RenderBeginTag(HtmlTextWriter writer)\n {\n writer.Write(\"<div class='roundedbox'>\");\n }\n\n public override void RenderEndTag(HtmlTextWriter writer)\n {\n writer.Write(\"</div>\");\n }\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18234/" ]
306,291
<p>Is there a 4 byte unsigned int data type in MS SQL Server?</p> <p>Am I forced to use a bigint?</p>
[ { "answer_id": 306300, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "int 2^31-1" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
306,305
<p>I am trying to do positioning in JavaScript. I am using a cumulative position function based on the <a href="http://www.quirksmode.org/js/findpos.html" rel="noreferrer" title="Find position">classic quirksmode function</a> that sums <code>offsetTop</code> and <code>offsetLeft</code> for each <code>offsetParent</code> until the top node.</p> <p>However, I am running into an issue where the element I'm interested in has no <code>offsetParent</code> in Firefox. In IE <code>offsetParent</code> exists, but <code>offsetTop</code> and <code>offsetLeft</code> all sum up to 0, so it has the same problem in effect as in Firefox.</p> <p>What would cause an element that is clearly visible and usable on the screen to not have an <code>offsetParent</code>? Or, more practically, how can I find the position of this element in order to place a drop-down beneath it?</p> <p><strong>Edit</strong>: Here's how to reproduce one particular instance of this (not solved by the currently-accepted answer):</p> <ol> <li>Open the <a href="http://stackoverflow.com">home page of Stack Overflow</a>.</li> <li><p>Run the following code in the Console of the web browser (e.g. Chromev21):</p> <pre class="lang-js prettyprint-override"><code>var e = document.querySelector('div'); console.log(e); // &lt;div id="notify-container"&gt;&lt;/div&gt; do{ var s = getComputedStyle(e); console.log(e.tagName,s.display,s.visibility,s.position,e.offsetParent); } while(e=e.parentElement) // DIV block visible fixed null // BODY block visible static null // HTML block visible static null </code></pre></li> </ol> <p><strong>Why is the <code>offsetParent</code> of that element <code>null</code>?</strong></p>
[ { "answer_id": 3313095, "author": "Norman", "author_id": 302971, "author_profile": "https://Stackoverflow.com/users/302971", "pm_score": 0, "selected": false, "text": "<div id=\"parent\">\n <div id=\"element1\">some stuff</div>\n <div id=\"element2\" style=\"display: none\">some hidden stuff</div>\n <div id=\"element3\">child whose offset we want</div>\n</div>\n" }, { "answer_id": 4702011, "author": "David Rivers", "author_id": 224192, "author_profile": "https://Stackoverflow.com/users/224192", "pm_score": 2, "selected": false, "text": "offsetParent" }, { "answer_id": 11639664, "author": "Phrogz", "author_id": 405017, "author_profile": "https://Stackoverflow.com/users/405017", "pm_score": 6, "selected": false, "text": "position display visibility <body> offsetParent position:fixed display:none display:none <body> offsetParent==null" }, { "answer_id": 59772377, "author": "t.animal", "author_id": 3340992, "author_profile": "https://Stackoverflow.com/users/3340992", "pm_score": 0, "selected": false, "text": "offsetParent null offsetParent" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3078/" ]
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
[ { "answer_id": 306347, "author": "Amit", "author_id": 29120, "author_profile": "https://Stackoverflow.com/users/29120", "pm_score": 4, "selected": false, "text": "id In [1]: id(255)\nOut[1]: 146349024\n\nIn [2]: id(255)\nOut[2]: 146349024\n\nIn [3]: id(257)\nOut[3]: 146802752\n\nIn [4]: id(257)\nOut[4]: 148993740\n\nIn [5]: a=255\n\nIn [6]: b=255\n\nIn [7]: c=257\n\nIn [8]: d=257\n\nIn [9]: id(a), id(b), id(c), id(d)\nOut[9]: (146349024, 146349024, 146783024, 146804020)\n <= 255" }, { "answer_id": 306353, "author": "Cybis", "author_id": 32998, "author_profile": "https://Stackoverflow.com/users/32998", "pm_score": 10, "selected": true, "text": ">>> a = 256\n>>> b = 256\n>>> id(a)\n9987148\n>>> id(b)\n9987148\n>>> a = 257\n>>> b = 257\n>>> id(a)\n11662816\n>>> id(b)\n11662828\n -5 256" }, { "answer_id": 306377, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 6, "selected": false, "text": "is In [29]: a = 3\nIn [30]: b = 3\nIn [31]: id(a)\nOut[31]: 500729144\nIn [32]: id(b)\nOut[32]: 500729144\n == __eq__ __ne__" }, { "answer_id": 306603, "author": "Angel", "author_id": 23285, "author_profile": "https://Stackoverflow.com/users/23285", "pm_score": 5, "selected": false, "text": "==" }, { "answer_id": 15522094, "author": "Yann Vernier", "author_id": 379311, "author_profile": "https://Stackoverflow.com/users/379311", "pm_score": 3, "selected": false, "text": "is id(a) == id(b) === x == y and type(x) == type(y) is __eq__ class Unequal:\n def __eq__(self, other):\n return False\n Now time.time() == is isinstance numbers.Number import numpy, numbers\nassert not issubclass(numpy.int16,numbers.Number)\nassert issubclass(int,numbers.Number)\n PyNumber_Check number? is === is" }, { "answer_id": 28864111, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 7, "selected": false, "text": "is == != >>> a = 1000\n>>> a == 1000 # Test integers like this,\nTrue\n>>> a != 5000 # or this!\nTrue\n>>> a is 1000 # Don't do this! - Don't use `is` to test integers!!\nFalse\n is is is not x is y x is not y >>> a is b\n>>> id(a) == id(b)\n id id() id is None is is not >>> a = 256\n>>> b = 256\n>>> a is b\nTrue # This is an expected result\n 256 a b >>> a = 257\n>>> b = 257\n>>> a is b\nFalse # What happened here? Why is this False?\n 257 >>> 257 is 257\nTrue # Yet the literal numbers compare properly\n == is is id id >>> a is b\n >>> id(a) == id(b)\n is None is SENTINEL_SINGLETON = object() # this will only be created one time.\n\ndef foo(keyword_argument=None):\n if keyword_argument is None:\n print('no argument given to foo')\n bar()\n bar(keyword_argument)\n bar('baz')\n\ndef bar(keyword_argument=SENTINEL_SINGLETON):\n # SENTINEL_SINGLETON tells us if we were not passed anything\n # as None is a legitimate potential argument we could get.\n if keyword_argument is SENTINEL_SINGLETON:\n print('no argument given to bar')\n else:\n print('argument to bar: {0}'.format(keyword_argument))\n\nfoo()\n no argument given to foo\nno argument given to bar\nargument to bar: None\nargument to bar: baz\n is bar None is" }, { "answer_id": 33130014, "author": "sobolevn", "author_id": 4842742, "author_profile": "https://Stackoverflow.com/users/4842742", "pm_score": 2, "selected": false, "text": ">>> s = b = 'somestr'\n>>> s == b, s is b, id(s), id(b)\n(True, True, 4555519392, 4555519392)\n >>> s = 'somestr'\n>>> b = 'somestr'\n>>> s == b, s is b, id(s), id(b)\n(True, True, 4555519392, 4555519392)\n >>> s1 = b1 = 'somestrdaasd ad ad asd as dasddsg,dlfg ,;dflg, dfg a'\n>>> s1 == b1, s1 is b1, id(s1), id(b1)\n(True, True, 4555308080, 4555308080)\n\n>>> s1 = 'somestrdaasd ad ad asd as dasddsg,dlfg ,;dflg, dfg a'\n>>> b1 = 'somestrdaasd ad ad asd as dasddsg,dlfg ,;dflg, dfg a'\n>>> s1 == b1, s1 is b1, id(s1), id(b1)\n(True, False, 4555308176, 4555308272)\n" }, { "answer_id": 34964030, "author": "Dimitris Fasarakis Hilliard", "author_id": 4952130, "author_profile": "https://Stackoverflow.com/users/4952130", "pm_score": 6, "selected": false, "text": "int PyLong_FromLong(long v) Objects PyLong_FromLong long longobject.c PyObject *\nPyLong_FromLong(long ival)\n{\n // omitting declarations\n\n CHECK_SMALL_INT(ival);\n\n if (ival < 0) {\n /* negate: cant write this as abs_ival = -ival since that\n invokes undefined behaviour when ival is LONG_MIN */\n abs_ival = 0U-(unsigned long)ival;\n sign = -1;\n }\n else {\n abs_ival = (unsigned long)ival;\n }\n\n /* Fast path for single-digit ints */\n if (!(abs_ival >> PyLong_SHIFT)) {\n v = _PyLong_New(1);\n if (v) {\n Py_SIZE(v) = sign;\n v->ob_digit[0] = Py_SAFE_DOWNCAST(\n abs_ival, unsigned long, digit);\n }\n return (PyObject*)v; \n}\n CHECK_SMALL_INT(ival); #define CHECK_SMALL_INT(ival) \\\n do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \\\n return get_small_int((sdigit)ival); \\\n } while(0)\n get_small_int ival if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS)\n NSMALLNEGINTS NSMALLPOSINTS #ifndef NSMALLPOSINTS\n#define NSMALLPOSINTS 257\n#endif\n#ifndef NSMALLNEGINTS\n#define NSMALLNEGINTS 5\n#endif\n if (-5 <= ival && ival < 257) get_small_int get_small_int PyObject *v;\nassert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);\nv = (PyObject *)&small_ints[ival + NSMALLNEGINTS];\nPy_INCREF(v);\n PyObject v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];\n small_ints /* Small integers are preallocated in this array so that they\n can be shared.\n The integers that are preallocated are those in the range\n -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).\n*/\nstatic PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];\n int [NSMALLNEGINTS, NSMALLPOSINTS) id() is _PyLong_Init for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {\n 257 is 257 >>> 257 is 257\n PyLongObject 257 >>> codeObj = compile(\"257 is 257\", \"blah!\", \"exec\")\n>>> codeObj.co_consts\n(257, None)\n >>> import dis\n>>> dis.dis(codeObj)\n 1 0 LOAD_CONST 0 (257) # dis\n 3 LOAD_CONST 0 (257) # dis again\n 6 COMPARE_OP 8 (is)\n is True" }, { "answer_id": 49472348, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 4, "selected": false, "text": "tuple str bytes >>> a = ()\n>>> b = ()\n>>> a is b\nTrue\n >>> c = 257\n>>> d = 257\n>>> c is d\nFalse\n>>> e, f = 258, 258\n>>> e is f\nTrue\n int >>> g, h = 42.23e100, 42.23e100\n>>> g is h\nTrue\n float 42.23e100 int float str bytes c d e f e, f = 128, 128 dis.dis (128, 128) >>> def f(): i, j = 258, 258\n>>> dis.dis(f)\n 1 0 LOAD_CONST 2 ((128, 128))\n 2 UNPACK_SEQUENCE 2\n 4 STORE_FAST 0 (i)\n 6 STORE_FAST 1 (j)\n 8 LOAD_CONST 0 (None)\n 10 RETURN_VALUE\n>>> f.__code__.co_consts\n(None, 128, (128, 128))\n>>> id(f.__code__.co_consts[1], f.__code__.co_consts[2][0], f.__code__.co_consts[2][1])\n4305296480, 4305296480, 4305296480\n 128 >>> k, l = (1, 2), (1, 2)\n>>> k is l\nFalse\n dis co_consts 1 2 (1, 2) 1 2 ((1, 2), (1, 2)) >>> m = 'abc'\n>>> n = 'abc'\n>>> m is n\nTrue\n str x is y x == y x is not y x != y is None _sentinel = object()" }, { "answer_id": 57641343, "author": "cclauss", "author_id": 2420341, "author_profile": "https://Stackoverflow.com/users/2420341", "pm_score": 2, "selected": false, "text": "is is not == !=" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893/" ]
306,316
<p>I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectangles will exist parallel to the x and the y axis, that is all of their edges will have slopes of 0 or infinity.</p> <p>I've tried to implement what is mentioned in <a href="https://stackoverflow.com/questions/115426">this</a> question but I am not having very much luck.</p> <p>My current implementation does the following:</p> <pre><code>// Gets all the vertices for Rectangle 1 and stores them in an array -&gt; arrRect1 // point 1 x: arrRect1[0], point 1 y: arrRect1[1] and so on... // Gets all the vertices for Rectangle 2 and stores them in an array -&gt; arrRect2 // rotated edge of point a, rect 1 int rot_x, rot_y; rot_x = -arrRect1[3]; rot_y = arrRect1[2]; // point on rotated edge int pnt_x, pnt_y; pnt_x = arrRect1[2]; pnt_y = arrRect1[3]; // test point, a from rect 2 int tst_x, tst_y; tst_x = arrRect2[0]; tst_y = arrRect2[1]; int value; value = (rot_x * (tst_x - pnt_x)) + (rot_y * (tst_y - pnt_y)); cout &lt;&lt; "Value: " &lt;&lt; value; </code></pre> <p>However I'm not quite sure if (a) I've implemented the algorithm I linked to correctly, or if I did exactly how to interpret this?</p> <p>Any suggestions?</p>
[ { "answer_id": 306332, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 11, "selected": true, "text": "if (RectA.Left < RectB.Right && RectA.Right > RectB.Left &&\n RectA.Top > RectB.Bottom && RectA.Bottom < RectB.Top ) \n if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&\n RectA.Y1 > RectB.Y2 && RectA.Y2 < RectB.Y1) \n Not (A or B or C or D) Not A And Not B And Not C And Not D RectA.Left < RectB.Right RectA.Right > RectB.Left RectA.Top > RectB.Bottom RectA.Bottom < RectB.Top < > <= >=" }, { "answer_id": 306379, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 7, "selected": false, "text": "struct rect\n{\n int x;\n int y;\n int width;\n int height;\n};\n\nbool valueInRange(int value, int min, int max)\n{ return (value >= min) && (value <= max); }\n\nbool rectOverlap(rect A, rect B)\n{\n bool xOverlap = valueInRange(A.x, B.x, B.x + B.width) ||\n valueInRange(B.x, A.x, A.x + A.width);\n\n bool yOverlap = valueInRange(A.y, B.y, B.y + B.height) ||\n valueInRange(B.y, A.y, A.y + A.height);\n\n return xOverlap && yOverlap;\n}" }, { "answer_id": 306414, "author": "baretta", "author_id": 30052, "author_profile": "https://Stackoverflow.com/users/30052", "pm_score": 0, "selected": false, "text": "public bool Intersects ( Rectangle rect )\n{\n float ulx = Math.Max ( x, rect.x );\n float uly = Math.Max ( y, rect.y );\n float lrx = Math.Min ( x + width, rect.x + rect.width );\n float lry = Math.Min ( y + height, rect.y + rect.height );\n\n return ulx <= lrx && uly <= lry;\n}\n" }, { "answer_id": 306421, "author": "coryan", "author_id": 33325, "author_profile": "https://Stackoverflow.com/users/33325", "pm_score": 3, "selected": false, "text": "struct Rectangle { int x; int y; int width; int height; };\n\nbool is_left_of(Rectangle const & a, Rectangle const & b) {\n if (a.x + a.width <= b.x) return true;\n return false;\n}\nbool is_right_of(Rectangle const & a, Rectangle const & b) {\n return is_left_of(b, a);\n}\n\nbool not_intersect( Rectangle const & a, Rectangle const & b) {\n if (is_left_of(a, b)) return true;\n if (is_right_of(a, b)) return true;\n // Do the same for top/bottom...\n }\n\nbool intersect(Rectangle const & a, Rectangle const & b) {\n return !not_intersect(a, b);\n}\n" }, { "answer_id": 306434, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 5, "selected": false, "text": "struct Rect\n{\n Rect(int x1, int x2, int y1, int y2)\n : x1(x1), x2(x2), y1(y1), y2(y2)\n {\n assert(x1 < x2);\n assert(y1 < y2);\n }\n\n int x1, x2, y1, y2;\n};\n\nbool\noverlap(const Rect &r1, const Rect &r2)\n{\n // The rectangles don't overlap if\n // one rectangle's minimum in some dimension \n // is greater than the other's maximum in\n // that dimension.\n\n bool noOverlap = r1.x1 > r2.x2 ||\n r2.x1 > r1.x2 ||\n r1.y1 > r2.y2 ||\n r2.y1 > r1.y2;\n\n return !noOverlap;\n}\n" }, { "answer_id": 306556, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 2, "selected": false, "text": "struct Rect\n{\n Rect(int x1, int x2, int y1, int y2)\n : x1(x1), x2(x2), y1(y1), y2(y2)\n {\n assert(x1 < x2);\n assert(y1 < y2);\n }\n\n int x1, x2, y1, y2;\n};\n\n//some area of the r1 overlaps r2\nbool overlap(const Rect &r1, const Rect &r2)\n{\n return r1.x1 < r2.x2 && r2.x1 < r1.x2 &&\n r1.y1 < r2.y2 && r2.x1 < r1.y2;\n}\n\n//either the rectangles overlap or the edges touch\nbool touch(const Rect &r1, const Rect &r2)\n{\n return r1.x1 <= r2.x2 && r2.x1 <= r1.x2 &&\n r1.y1 <= r2.y2 && r2.x1 <= r1.y2;\n}\n" }, { "answer_id": 306558, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 1, "selected": false, "text": "bool bOverlap = !((A.Left >= B.Right || B.Left >= A.Right)\n && (A.Bottom >= B.Top || B.Bottom >= A.Top));\n" }, { "answer_id": 2696876, "author": "anony", "author_id": 323947, "author_profile": "https://Stackoverflow.com/users/323947", "pm_score": 1, "selected": false, "text": "max(r1.x1, r2.x1) min(r1.x2, r2.x2) min(r1.x2, r2.x2) - max(r1.x1, r2.x1) area = (max(r1.x1, r2.x1) - min(r1.x2, r2.x2)) * (max(r1.y1, r2.y1) - min(r1.y2, r2.y2))\n area = 0" }, { "answer_id": 4098512, "author": "Björn Kechel", "author_id": 497366, "author_profile": "https://Stackoverflow.com/users/497366", "pm_score": 5, "selected": false, "text": "(r1.x + r1.width < r2.x)\n (r1.x > r2.x + r2.width)\n (r1.y + r1.height < r2.y)\n (r1.y > r2.y + r2.height)\n function checkOverlap(r1, r2) : Boolean\n{ \n return !(r1.x + r1.width < r2.x || r1.y + r1.height < r2.y || r1.x > r2.x + r2.width || r1.y > r2.y + r2.height);\n}\n" }, { "answer_id": 7871987, "author": "Lyle", "author_id": 1010353, "author_profile": "https://Stackoverflow.com/users/1010353", "pm_score": 2, "selected": false, "text": "public boolean intersects(Rectangle r) {\n int tw = this.width;\n int th = this.height;\n int rw = r.width;\n int rh = r.height;\n if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {\n return false;\n }\n int tx = this.x;\n int ty = this.y;\n int rx = r.x;\n int ry = r.y;\n rw += rx;\n rh += ry;\n tw += tx;\n th += ty;\n // overflow || intersect\n return ((rw < rx || rw > tx) &&\n (rh < ry || rh > ty) &&\n (tw < tx || tw > rx) &&\n (th < ty || th > ry));\n}\n" }, { "answer_id": 11247696, "author": "sachinr", "author_id": 1395413, "author_profile": "https://Stackoverflow.com/users/1395413", "pm_score": 1, "selected": false, "text": "if(!(dx > Wa+Wb)||!(dy > Ha+Hb)) returns true\n" }, { "answer_id": 21168760, "author": "Anwit", "author_id": 2212869, "author_profile": "https://Stackoverflow.com/users/2212869", "pm_score": 0, "selected": false, "text": "four points of A be (xAleft,yAtop),(xAleft,yAbottom),(xAright,yAtop),(xAright,yAbottom)\nfour points of A be (xBleft,yBtop),(xBleft,yBbottom),(xBright,yBtop),(xBright,yBbottom)\n\nA.width = abs(xAleft-xAright);\nA.height = abs(yAleft-yAright);\nB.width = abs(xBleft-xBright);\nB.height = abs(yBleft-yBright);\n\nC.width = max(xAleft,xAright,xBleft,xBright)-min(xAleft,xAright,xBleft,xBright);\nC.height = max(yAtop,yAbottom,yBtop,yBbottom)-min(yAtop,yAbottom,yBtop,yBbottom);\n\nA and B does not overlap if\n(C.width >= A.width + B.width )\nOR\n(C.height >= A.height + B.height) \n" }, { "answer_id": 23869015, "author": "Zar E Ahmer", "author_id": 3496570, "author_profile": "https://Stackoverflow.com/users/3496570", "pm_score": 1, "selected": false, "text": "/**\n * Check if two rectangles collide\n * x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle\n * x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle\n */\nboolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2)\n{\n return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);\n}\n" }, { "answer_id": 27624434, "author": "hkBattousai", "author_id": 245376, "author_profile": "https://Stackoverflow.com/users/245376", "pm_score": 3, "selected": false, "text": "class Vector2D\n{\n public:\n Vector2D(int x, int y) : x(x), y(y) {}\n ~Vector2D(){}\n int x, y;\n};\n\nbool DoRectanglesOverlap( const Vector2D & Pos1,\n const Vector2D & Size1,\n const Vector2D & Pos2,\n const Vector2D & Size2)\n{\n if ((Pos1.x < Pos2.x + Size2.x) &&\n (Pos1.y < Pos2.y + Size2.y) &&\n (Pos2.x < Pos1.x + Size1.x) &&\n (Pos2.y < Pos1.y + Size1.y))\n {\n return true;\n }\n return false;\n}\n DoRectanglesOverlap(Vector2D(3, 7),\n Vector2D(8, 5),\n Vector2D(6, 4),\n Vector2D(9, 4));\n if if ((Pos1.x < Pos2.x + Size2.x) &&\n (Pos1.y < Pos2.y + Size2.y) &&\n (Pos2.x < Pos1.x + Size1.x) &&\n (Pos2.y < Pos1.y + Size1.y))\n ↓ \nif (( 3 < 6 + 9 ) &&\n ( 7 < 4 + 4 ) &&\n ( 6 < 3 + 8 ) &&\n ( 4 < 7 + 5 ))\n" }, { "answer_id": 31760639, "author": "anchan42", "author_id": 5180369, "author_profile": "https://Stackoverflow.com/users/5180369", "pm_score": 0, "selected": false, "text": "import java.util.Scanner;\n\npublic class ProgrammingEx3_28 {\npublic static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n\n System.out\n .print(\"Enter r1's center x-, y-coordinates, width, and height:\");\n double x1 = input.nextDouble();\n double y1 = input.nextDouble();\n double w1 = input.nextDouble();\n double h1 = input.nextDouble();\n w1 = w1 / 2;\n h1 = h1 / 2;\n System.out\n .print(\"Enter r2's center x-, y-coordinates, width, and height:\");\n double x2 = input.nextDouble();\n double y2 = input.nextDouble();\n double w2 = input.nextDouble();\n double h2 = input.nextDouble();\n w2 = w2 / 2;\n h2 = h2 / 2;\n\n // Calculating range of r1 and r2\n double x1max = x1 + w1;\n double y1max = y1 + h1;\n double x1min = x1 - w1;\n double y1min = y1 - h1;\n double x2max = x2 + w2;\n double y2max = y2 + h2;\n double x2min = x2 - w2;\n double y2min = y2 - h2;\n\n if (x1max == x2max && x1min == x2min && y1max == y2max\n && y1min == y2min) {\n // Check if the two are identicle\n System.out.print(\"r1 and r2 are indentical\");\n\n } else if (x1max <= x2max && x1min >= x2min && y1max <= y2max\n && y1min >= y2min) {\n // Check if r1 is in r2\n System.out.print(\"r1 is inside r2\");\n } else if (x2max <= x1max && x2min >= x1min && y2max <= y1max\n && y2min >= y1min) {\n // Check if r2 is in r1\n System.out.print(\"r2 is inside r1\");\n } else if (x1max < x2min || x1min > x2max || y1max < y2min\n || y2min > y1max) {\n // Check if the two overlap\n System.out.print(\"r2 does not overlaps r1\");\n } else {\n System.out.print(\"r2 overlaps r1\");\n }\n\n}\n}\n" }, { "answer_id": 38810616, "author": "Kok How Teh", "author_id": 1635450, "author_profile": "https://Stackoverflow.com/users/1635450", "pm_score": 0, "selected": false, "text": "bool Square::IsOverlappig(Square &other)\n{\n bool result1 = other.x >= x && other.y >= y && other.x <= (x + width) && other.y <= (y + height); // other's top left falls within this area\n bool result2 = other.x >= x && other.y <= y && other.x <= (x + width) && (other.y + other.height) <= (y + height); // other's bottom left falls within this area\n bool result3 = other.x <= x && other.y >= y && (other.x + other.width) <= (x + width) && other.y <= (y + height); // other's top right falls within this area\n bool result4 = other.x <= x && other.y <= y && (other.x + other.width) >= x && (other.y + other.height) >= y; // other's bottom right falls within this area\n return result1 | result2 | result3 | result4;\n}\n" }, { "answer_id": 45663581, "author": "mchiasson", "author_id": 1620670, "author_profile": "https://Stackoverflow.com/users/1620670", "pm_score": 1, "selected": false, "text": "#include <cmath> // for fabsf(float)\n\nstruct Rectangle\n{\n float centerX, centerY, halfWidth, halfHeight;\n};\n\nbool isRectangleOverlapping(const Rectangle &a, const Rectangle &b)\n{\n return (fabsf(a.centerX - b.centerX) <= (a.halfWidth + b.halfWidth)) &&\n (fabsf(a.centerY - b.centerY) <= (a.halfHeight + b.halfHeight)); \n}\n" }, { "answer_id": 60477518, "author": "Edward Karak", "author_id": 2469027, "author_profile": "https://Stackoverflow.com/users/2469027", "pm_score": 0, "selected": false, "text": "struct point { int x, y; };\n\nstruct rect { point tl, br; }; // top left and bottom right points\n\n// return true if rectangles overlap\nbool overlap(const rect &a, const rect &b)\n{\n return a.tl.x <= b.br.x && a.br.x >= b.tl.x && \n a.tl.y >= b.br.y && a.br.y <= b.tl.y;\n}\n" }, { "answer_id": 62852710, "author": "Pedro Gimeno", "author_id": 2428487, "author_profile": "https://Stackoverflow.com/users/2428487", "pm_score": 4, "selected": false, "text": "return std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right)\n && std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom);\n return std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom)\n && std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right);\n return std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right)\n & std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom);\n && &" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135/" ]
306,381
<p>How do you create a custom control (not an ASCX control) and, more importantly, use it in your project? I'd prefer not to create a separate project for it or compile it as a DLL</p>
[ { "answer_id": 306388, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": 1, "selected": false, "text": "<%@ Register Assembly=\"NAME_OF_THE_ASSEMBLY\" Namespace=\"NAMESPACE_OF_THE_CUSTOM_CONTROL\" TagPrefix=\"cc1\" %>\n <cc1:mycustompanel id=\"MyCustomPanel1\" runat=\"server\"><asp:TextBox id=\"TextBox1\" runat=\"server\"></asp:TextBox></cc1:mycustompanel>\n" }, { "answer_id": 306408, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "public class Hello : System.Web.UI.WebControl\n{\n public override Render(HtmlTextWriter writer)\n {\n writer.Write(\"Hello World\");\n base.Render(writer);\n }\n}\n <%@ Register TagPrefix=\"Example\" Namespace=\"CustomControls\" Assembly = \"CustomControls\" %>\n" }, { "answer_id": 780901, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<%@ Register TagPrefix=\"Example\" Namespace=\"CustomControls\" Assembly=\"CustomControls\" %>\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18234/" ]
306,387
<p>Delegates look like such a powerful language feature, but I've yet to find an opportunity to use them in anger (apart from in DALs I must say).</p> <p>How often do you use them, and under what circumstances do you find them most useful? </p>
[ { "answer_id": 306394, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 3, "selected": false, "text": "public delegate void MyDelegate(object sender, EventArgs e, string otherParameterIWant);\n//...Inside the class\npublic event MyDelegate myEvent;\n//...Inside a method\nif (myEvent != null)\n myEvent(this, new EventArgs(), \"Test for SO\");\n" }, { "answer_id": 306398, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "myList.Sort(a=> a.LastName);\n" }, { "answer_id": 306406, "author": "Brian Genisio", "author_id": 36687, "author_profile": "https://Stackoverflow.com/users/36687", "pm_score": 2, "selected": false, "text": "public delegate bool ItemFilterDelegate(MyItem item);\n\npublic IEnumerable<MyItem> FilterItems(ItemFilterDelegate filter)\n{\n var result = new List<MyItem>();\n\n foreach(MyItem item in AllItems)\n {\n if(filter(item))\n result.Add(item);\n }\n\n return item;\n} \n\npublic IEnumerable<MyItem> FilterByName(string name)\n{\n return FilterItems(item => item.Name == name);\n}\n" }, { "answer_id": 306436, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 3, "selected": true, "text": "someList.Select(item => item.Name);\n Func<Item, String> itemName = item => item.Name;\n...\nsomeList.Select(itemName);\n Dictionary<UserType, Action<User>> showControls;\nshowControls = new Dictionary<UserType, Action<User>>();\n\nshowControls.Add(SomeEnum.Admin, setControlsForAdmin);\nshowControls.Add(SomeEnum.Normal, setControlsForNormalUser);\nshowControls.Add(SomeEnum.Unregistered, setControlsForUnregisteredUser);\n showControls[user.UserType]();\n Action<User> neededMethod;\n\nneededMethod = showControls[user.UserType];\n\nSomeMethod(neededMethod);\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38522/" ]
306,400
<p>How do I retrieve an item at random from the following list?</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre>
[ { "answer_id": 306417, "author": "Pēteris Caune", "author_id": 5821, "author_profile": "https://Stackoverflow.com/users/5821", "pm_score": 13, "selected": true, "text": "random.choice() import random\n\nfoo = ['a', 'b', 'c', 'd', 'e']\nprint(random.choice(foo))\n secrets.choice() import secrets\n\nfoo = ['battery', 'correct', 'horse', 'staple']\nprint(secrets.choice(foo))\n secrets random.SystemRandom import random\n\nsecure_random = random.SystemRandom()\nprint(secure_random.choice(foo))\n" }, { "answer_id": 12373205, "author": "Juan Pablo Rinaldi", "author_id": 540477, "author_profile": "https://Stackoverflow.com/users/540477", "pm_score": 8, "selected": false, "text": "random.randrange from random import randrange\nrandom_index = randrange(len(foo))\nprint(foo[random_index])\n" }, { "answer_id": 14015085, "author": "Janek Olszak", "author_id": 492647, "author_profile": "https://Stackoverflow.com/users/492647", "pm_score": 4, "selected": false, "text": "import random\nfoo = ['a', 'b', 'c', 'd', 'e']\nprint int(random.random() * len(foo))\nprint foo[int(random.random() * len(foo))]\n" }, { "answer_id": 16514203, "author": "kiriloff", "author_id": 1141493, "author_profile": "https://Stackoverflow.com/users/1141493", "pm_score": 6, "selected": false, "text": "set choice s=set(range(1,6))\nimport random\n\nwhile len(s)>0:\n s.remove(random.choice(list(s)))\n print(s)\n >>> \nset([1, 3, 4, 5])\nset([3, 4, 5])\nset([3, 4])\nset([4])\nset([])\n>>> \nset([1, 2, 3, 5])\nset([2, 3, 5])\nset([2, 3])\nset([2])\nset([])\n\n>>> \nset([1, 2, 3, 5])\nset([1, 2, 3])\nset([1, 2])\nset([1])\nset([])\n" }, { "answer_id": 25133330, "author": "Abdul Majeed", "author_id": 5629004, "author_profile": "https://Stackoverflow.com/users/5629004", "pm_score": -1, "selected": false, "text": "from random import randint\nl= ['a','b','c']\n\ndef get_rand_element(l):\n if l:\n return l[randint(0,len(l)-1)]\n else:\n return None\n\nget_rand_element(l)\n" }, { "answer_id": 30441100, "author": "Liam", "author_id": 4879665, "author_profile": "https://Stackoverflow.com/users/4879665", "pm_score": 3, "selected": false, "text": "import random\n\nfoo = ['a', 'b', 'c', 'd', 'e']\nrandomindex = random.randint(0,len(foo)-1) \nprint (foo[randomindex])\n## print (randomindex)\n import random\n\nfoo = ['a', 'b', 'c', 'd', 'e']\nprint (foo[random.randint(0,len(foo)-1)])\n import random\n\nfoo = ['a', 'b', 'c', 'd', 'e']\nprint(random.choice(foo))\n" }, { "answer_id": 30488952, "author": "Paul", "author_id": 2109512, "author_profile": "https://Stackoverflow.com/users/2109512", "pm_score": 8, "selected": false, "text": "random.sample import random\ngroup_of_items = {'a', 'b', 'c', 'd', 'e'} # a sequence or set will work here.\nnum_to_select = 2 # set the number to select here.\nlist_of_random_items = random.sample(group_of_items, num_to_select)\nfirst_random_item = list_of_random_items[0]\nsecond_random_item = list_of_random_items[1] \n random.sample(some_list, 1)[0] random.choice(some_list) random.choice(tuple(some_set)) import secrets # imports secure module.\nsecure_random = secrets.SystemRandom() # creates a secure random object.\ngroup_of_items = {'a', 'b', 'c', 'd', 'e'} # a sequence or set will work here.\nnum_to_select = 2 # set the number to select here.\nlist_of_random_items = secure_random.sample(group_of_items, num_to_select)\nfirst_random_item = list_of_random_items[0]\nsecond_random_item = list_of_random_items[1]\n import random\nfirst_random_item, second_random_item = random.sample({'a', 'b', 'c', 'd', 'e'}, 2)\n" }, { "answer_id": 40979298, "author": "Chris_Rands", "author_id": 6260170, "author_profile": "https://Stackoverflow.com/users/6260170", "pm_score": 6, "selected": false, "text": "secrets random import secrets\nfoo = ['a', 'b', 'c', 'd', 'e']\nprint(secrets.choice(foo))\n print(secrets.randbelow(len(foo)))\n" }, { "answer_id": 44730691, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 4, "selected": false, "text": "foo = ['a', 'b', 'c', 'd', 'e'] \n secrets.choice >>> from secrets import choice # Python 3 only\n>>> choice(list('abcde'))\n'c'\n SystemRandom random choice >>> import random # Python 2 compatible\n>>> sr = random.SystemRandom()\n>>> foo = list('abcde')\n>>> foo\n['a', 'b', 'c', 'd', 'e']\n >>> sr.choice(foo)\n'd'\n>>> sr.choice(foo)\n'e'\n>>> sr.choice(foo)\n'a'\n>>> sr.choice(foo)\n'b'\n>>> sr.choice(foo)\n'a'\n>>> sr.choice(foo)\n'c'\n>>> sr.choice(foo)\n'c'\n choice Random >>> random.choice\n<bound method Random.choice of <random.Random object at 0x800c1034>>\n >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)\n('d', 'a', 'b')\n>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)\n('d', 'a', 'b')\n>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)\n('d', 'a', 'b')\n>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)\n('d', 'a', 'b')\n>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)\n('d', 'a', 'b')\n sr = random.SystemRandom(42) SystemRandom def seed(self, *args, **kwds):\n \"Stub method. Not used for a system random number generator.\"\n return None\n" }, { "answer_id": 47557650, "author": "Fardin Abdi", "author_id": 2288828, "author_profile": "https://Stackoverflow.com/users/2288828", "pm_score": 5, "selected": false, "text": "foo = ['a', 'b', 'c', 'd', 'e']\nnumber_of_samples = 1\n random_items = random.sample(population=foo, k=number_of_samples)\n random_items = random.choices(population=foo, k=number_of_samples)\n" }, { "answer_id": 51386126, "author": "C8H10N4O2", "author_id": 2573061, "author_profile": "https://Stackoverflow.com/users/2573061", "pm_score": 5, "selected": false, "text": "numpy.random.choice import random; random.choice() import numpy as np\nnp.random.choice(foo) # randomly selects a single item\n np.random.seed(123)\nnp.random.choice(foo) # first call will always return 'c'\n array size np.random.choice(foo, 5) # sample with replacement (default)\nnp.random.choice(foo, 5, False) # sample without replacement\n" }, { "answer_id": 52782969, "author": "Memin", "author_id": 2234161, "author_profile": "https://Stackoverflow.com/users/2234161", "pm_score": 4, "selected": false, "text": "random.sample sample import random\nlst = ['a', 'b', 'c', 'd', 'e']\nrandom.seed(0) # remove this line, if you want different results for each run\nrand_lst = random.sample(lst,3) # 3 is the number of sample you want to retrieve\nprint(rand_lst)\n\nOutput:['d', 'e', 'a']\n" }, { "answer_id": 57682492, "author": "Solomon Vimal", "author_id": 4383027, "author_profile": "https://Stackoverflow.com/users/4383027", "pm_score": 3, "selected": false, "text": "import random\n\nmy_list = [1, 2, 3, 4, 5]\nnum_selections = 2\n\nnew_list = random.sample(my_list, num_selections)\n randIndex = random.sample(range(len(my_list)), n_selections)\nrandIndex.sort()\nnew_list = [my_list[i] for i in randIndex]\n" }, { "answer_id": 62058049, "author": "Evan Schwartzentruber", "author_id": 13449866, "author_profile": "https://Stackoverflow.com/users/13449866", "pm_score": 3, "selected": false, "text": "from random import randint\n\nfoo = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n\nprint(foo[randint(0,4)])\n" }, { "answer_id": 64708525, "author": "Jax", "author_id": 14564211, "author_profile": "https://Stackoverflow.com/users/14564211", "pm_score": 2, "selected": false, "text": "random.shuffle import random\nfoo = ['a', 'b', 'c', 'd', 'e']\nrandom.shuffle(foo)\n" }, { "answer_id": 69267260, "author": "iacob", "author_id": 9067615, "author_profile": "https://Stackoverflow.com/users/9067615", "pm_score": 2, "selected": false, "text": "numpy from numpy.random import default_rng\n\nrng = default_rng()\nrng.choice(foo)\n" }, { "answer_id": 69782467, "author": "Pratik Thorat", "author_id": 12504575, "author_profile": "https://Stackoverflow.com/users/12504575", "pm_score": 4, "selected": false, "text": "import random\nfoo = ['a', 'b', 'c', 'd', 'e']\nprint(random.choice(foo))\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
306,410
<p>I have a following object model:</p> <pre> - Book -- Chapter 1 --- Page 1 ---- Image 1 ---- Image 2 ---- Text 1 --- Page 2 ... </pre> <p>Resources are way down at the page level. But, I need to know the full path to resources, from the resources' point of view. </p> <p>One way, is to have resources be aware of their parents. </p> <p>So my Image object could have a "parentPage" property, which in turn could have a "parentChapter" property. This way, I could access the complete path via currentImage.parentPage.parentChapter. Is there a better way?</p> <p>A couple of words on why I'd need to know the full path from a resource's point of view. I have an object model that gets walked and rendered on screen. The renderer descends from chapter level all the way down into the element/resource level (this is where the rendering occurs). However to display the resources, I need to know where they live (ie the actual path on disk) and this information is typically specified at the Chapter level.</p> <p>Thanks!</p> <p>-- Edit -- Just to clarify, is this parent.parent approach the best? It forces child objects to know about the parents, which makes me uncomfortable. Coupling?</p>
[ { "answer_id": 306448, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 3, "selected": false, "text": "class TreeNode {\n public TreeNode Parent { get; set; }\n public List<TreeNode> Children { get; set; }\n}\n\nclass Book : TreeNode {\n ... book attributes ...\n}\n\n... other classes ...\n class TreeNode<TParent, TChild> \n{\n public TParent Parent { get; set; }\n public List<TChild> Children { get; set; }\n}\n\nclass Book : TreeNode<object, Chapter> { }\nclass Chapter : TreeNode<Book, Page> { }\nclass Page : TreeNode<Chapter, object> { }\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38753/" ]
306,433
<p>I have a fairly huge database with a master table with a single column GUID (custom GUID like algorithm) as primary key and 8 child tables that have foreign key relationships with this GUID column. All the tables have approximately 3-8 million records. None of these tables have any BLOB/CLOB/TEXT or any other fancy data types just normal numbers, varchars, dates, and timestamps (about 15-45 columns in each table). No partitions or other indexes other than the primary and foreign keys.</p> <p>Now, the custom GUID algorithm has changed and though there are no collisions I would like to migrate all the old data to use GUIDs generated using the new algorithm. No other columns need to be changed. Number one priority is data integrity and performance is secondary.</p> <p>Some of the possible solutions that I could think of were (as you will probably notice they all revolve around one idea only)</p> <ol> <li>add new column ngu_id and populate with new gu_id; disable constraints; update child tables with ngu_id as gu_id; renaname ngu_id->gu_id; re-enable constraints</li> <li>read one master record and its dependent child records from child tables; insert into the same table with new gu_id; remove all records with old gu_ids</li> <li>drop constraints; add a trigger to the master table such that all the child tables are updated; start updating old gu_id's with new new gu_ids; re-enable constraints</li> <li>add a trigger to the master table such that all the child tables are updated; start updating old gu_id's with new new gu_ids</li> <li>create new column ngu_ids on all master and child tables; create foreign key constraints on ngu_id columns; add update trigger to the master table to cascade values to child tables; insert new gu_id values into ngu_id column; remove old foreign key constraints based on gu_id; remove gu_id column and rename ngu_id to gu_id; recreate constraints if necessary;</li> <li>use <code>on update cascade</code> if available?</li> </ol> <p>My questions are:</p> <ol> <li>Is there a better way? (Can't burrow my head in the sand, gotta do this)</li> <li>What is the most suitable way to do this? (I've to do this in Oracle, SQL server and mysql4 so, vendor-specific hacks are welcome)</li> <li>What are the typical points of failure for such an exercise and how to minimize them?</li> </ol> <p>If you are with me so far, thank you and hope you can help :)</p>
[ { "answer_id": 310611, "author": "George Eadon", "author_id": 30530, "author_profile": "https://Stackoverflow.com/users/30530", "pm_score": 0, "selected": false, "text": "CREATE TABLE AS SELECT" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7616/" ]
306,439
<p>I have this Trigger in Postgresql that I can't just get to work (does nothing). For understanding, there's how I defined it:</p> <pre><code>CREATE TABLE documents ( ... modification_time timestamp with time zone DEFAULT now() ); CREATE FUNCTION documents_update_mod_time() RETURNS trigger AS $$ begin new.modification_time := now(); return new; end $$ LANGUAGE plpgsql; CREATE TRIGGER documents_modification_time BEFORE INSERT OR UPDATE ON documents FOR EACH ROW EXECUTE PROCEDURE documents_update_mod_time(); </code></pre> <p>Now to make it a bit more interesting.. How do you debug triggers?</p>
[ { "answer_id": 306509, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 2, "selected": false, "text": "ALTER TABLE documents\n ALTER COLUMN modification_time SET DEFAULT clock_timestamp();\n" }, { "answer_id": 312866, "author": "Dave Vogt", "author_id": 35189, "author_profile": "https://Stackoverflow.com/users/35189", "pm_score": 3, "selected": false, "text": "RAISE NOTICE 'test'; -- either this\nRAISE EXCEPTION 'failed'; -- or that\n EXPLAIN ANALYZE UPDATE table SET foo='bar'; -- shows the called triggers\n" }, { "answer_id": 430070, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 7, "selected": true, "text": "RAISE NOTICE 'myplpgsqlval is currently %', myplpgsqlval; -- either this\nRAISE EXCEPTION 'failed'; -- or that\n EXPLAIN ANALYZE UPDATE table SET foo='bar'; -- shows the called triggers\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35189/" ]
306,443
<p>In designing a fluid layout, how do you use borders without ruining the layout.</p> <p>More specifically, I have a HTML widget which consists of five divs. I would like the five divs to take up all the room in the containing element. I would also like to have a 1px border around each.</p> <p>I tried: .box { float: left; height: 100%; width: 100%; border: 1px solid red; } This doesn't work: there will be an extra 10px in width causing the boxes to wrap. Reducing the width percentage doesn't work as it will not take up the correct amount of space and for certain page sizes, will still wrap.</p> <p>Whats the proper way to manage the interaction between these elements?</p>
[ { "answer_id": 306472, "author": "One Crayon", "author_id": 38666, "author_profile": "https://Stackoverflow.com/users/38666", "pm_score": 2, "selected": false, "text": "width: 100% <div class=\"one\">\n <div class=\"two\">\n <div class=\"three\">\n etc.\n </div>\n </div>\n</div>\n\n<style>\n.one {\n width: 100%;\n}\n.two {\n border: 1px solid red;\n padding: 1px;\n background: red;\n}\n.three {\n border: 1px solid red;\n background: white;\n}\n</style>\n" }, { "answer_id": 306947, "author": "Ola Tuvesson", "author_id": 6903, "author_profile": "https://Stackoverflow.com/users/6903", "pm_score": 0, "selected": false, "text": "<style>\nbody {\nwidth: 100%;\nheight: 100%;\nmargin: 0;\nposition: absolute; \n/* overflow: hidden; */\n}\ndiv.section {\nfloat: left;\nwidth: 19.95%;\nheight: 100%;\n}\n div.column {\n height: 100%;\n border: 1px solid blue;\n margin: 1em;\n padding: 2em;\n }\n</style>\n\n<div class=\"section\"><div class=\"column\">one</div></div>\n<div class=\"section\"><div class=\"column\">two</div></div>\n<div class=\"section\"><div class=\"column\">three</div></div>\n<div class=\"section\"><div class=\"column\">four</div></div>\n<div class=\"section\"><div class=\"column\">five</div></div>\n" }, { "answer_id": 577985, "author": "ЯegDwight", "author_id": 58792, "author_profile": "https://Stackoverflow.com/users/58792", "pm_score": 4, "selected": false, "text": "box-sizing: border-box;\n -moz-box-sizing: border-box; // for Mozilla\n-webkit-box-sizing: border-box; // for WebKit\n-ms-box-sizing: border-box; // for IE8\n .box { \n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n -ms-box-sizing: border-box;\n width:20%;\n border:1px solid red;\n float:left\n}\n" }, { "answer_id": 12325296, "author": "Mason Barge", "author_id": 1044602, "author_profile": "https://Stackoverflow.com/users/1044602", "pm_score": 2, "selected": false, "text": ".navitem {\nwidth: 16.57%;\nheight: 35px;\nfloat: left;\ntext-align: center;\nfont: 1em/35px arial,sans-serif;\nborder-right: 1px solid #eee;\nmargin: 0 auto 0 auto;\npadding: 0;\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
306,452
<p>Let's say I need to implement domain model for StackOverflow. </p> <p>If I am doing ORM, how can I define (and map) property for fetching "last comments" and other "last" things? It looks to me like this should be reflected in the domain model.</p> <p>Sometimes I might need "all comments" though...</p>
[ { "answer_id": 306472, "author": "One Crayon", "author_id": 38666, "author_profile": "https://Stackoverflow.com/users/38666", "pm_score": 2, "selected": false, "text": "width: 100% <div class=\"one\">\n <div class=\"two\">\n <div class=\"three\">\n etc.\n </div>\n </div>\n</div>\n\n<style>\n.one {\n width: 100%;\n}\n.two {\n border: 1px solid red;\n padding: 1px;\n background: red;\n}\n.three {\n border: 1px solid red;\n background: white;\n}\n</style>\n" }, { "answer_id": 306947, "author": "Ola Tuvesson", "author_id": 6903, "author_profile": "https://Stackoverflow.com/users/6903", "pm_score": 0, "selected": false, "text": "<style>\nbody {\nwidth: 100%;\nheight: 100%;\nmargin: 0;\nposition: absolute; \n/* overflow: hidden; */\n}\ndiv.section {\nfloat: left;\nwidth: 19.95%;\nheight: 100%;\n}\n div.column {\n height: 100%;\n border: 1px solid blue;\n margin: 1em;\n padding: 2em;\n }\n</style>\n\n<div class=\"section\"><div class=\"column\">one</div></div>\n<div class=\"section\"><div class=\"column\">two</div></div>\n<div class=\"section\"><div class=\"column\">three</div></div>\n<div class=\"section\"><div class=\"column\">four</div></div>\n<div class=\"section\"><div class=\"column\">five</div></div>\n" }, { "answer_id": 577985, "author": "ЯegDwight", "author_id": 58792, "author_profile": "https://Stackoverflow.com/users/58792", "pm_score": 4, "selected": false, "text": "box-sizing: border-box;\n -moz-box-sizing: border-box; // for Mozilla\n-webkit-box-sizing: border-box; // for WebKit\n-ms-box-sizing: border-box; // for IE8\n .box { \n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n -ms-box-sizing: border-box;\n width:20%;\n border:1px solid red;\n float:left\n}\n" }, { "answer_id": 12325296, "author": "Mason Barge", "author_id": 1044602, "author_profile": "https://Stackoverflow.com/users/1044602", "pm_score": 2, "selected": false, "text": ".navitem {\nwidth: 16.57%;\nheight: 35px;\nfloat: left;\ntext-align: center;\nfont: 1em/35px arial,sans-serif;\nborder-right: 1px solid #eee;\nmargin: 0 auto 0 auto;\npadding: 0;\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38325/" ]
306,459
<p>Is there a clever way to determine which field is causing 'string or binary data would be truncated' with LINQ.</p> <p>I've always ended up doing it manually by stepping through a debugger, but with a batch using 'SubmitChanges' I have to change my code to inserting a single row to find the culprit in a batch of rows. </p> <p>Am I missing something or in this day and age do I really have to still use a brute force method to find the problem.</p> <p>Please dont give me advice on avoiding this error in future (unless its something much cleverer than 'validate your data'). The source data is coming from a different system where I dont have full control anyway - plus I want to be lazy.</p> <p>PS. Does SQL Server 2008 actually tell me the field name. Please tell me it does! I'll upgrade!</p>
[ { "answer_id": 306540, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": -1, "selected": false, "text": "Record # 9999\nCaused \"string or binary data would be truncated\" error\nField1: \"Data\" Length: 55\nField2: 9999\netc.\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
306,462
<p>I'm using <a href="http://www.codeproject.com/KB/cs/lotusnoteintegrator.aspx" rel="nofollow noreferrer">Interop.Domino.dll</a> to retrieve E-mails from a Lotus "Database" (Term used loosely). I'm having some difficulty in retrieving certain fields and wonder how to do this properly. I've been using <code>NotesDocument.GetFirstItem</code> to retrieve Subject, From and Body. </p> <p>My issues in this regard are thus:</p> <ol> <li>How do I retrieve Reply-To address? Is there a list of "Items" to get somewhere? I can't find it.</li> <li>How do I retrieve friendly names for From and Reply-To addresses?</li> <li>When I retrieve Body this way, it's formatted wierdly with square bracket sets ([]) interspersed randomly across the message body, and parts of the text aren't where I expect them. </li> </ol> <p>Related code:</p> <pre><code>string ActualSubject = nDoc.GetFirstItem("Subject").Text, ActualFrom = nDoc.GetFirstItem("From").Text, ActualBody = nDoc.GetFirstItem("Body").Text; </code></pre>
[ { "answer_id": 306624, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 3, "selected": true, "text": "Object[] ni = (Object[])nDoc.Items;\nstring names_values = \"\";\nfor (int x = 0; x < ni.Length; x++)\n{\nNotesItem item = (NotesItem)ni[x];\nif (!string.IsNullOrEmpty(item.Name)) names_values += x.ToString() + \": \" + item.Name + \"\\t\\t\" + item.Text + \"\\r\\n\";\n}\n 0: Received from example.com ([192.168.0.1]) by host.example.com (Lotus Domino Release 6.5.4 HF182) with ESMTP id 2008111917343129-205078 ; Wed, 19 Nov 2008 17:34:31 -0500\n1: Received from example.com ([192.168.0.2]) by host2.example.com (Lotus Domino Release 6.5.4 HF182) with ESMTP id 2008111917343129-205078 ; Wed, 19 Nov 2008 17:34:31 -0500\n2: X_PGRTRKID 130057945714t\n3: X_PGRSRC IE\n4: ReplyTo \"example\" <name@email.example.com>\n5: Principal \"example\" <customerservice@email.example.com>\n6: From \"IE130057945714t\"<service@test.email.example.com>\n7: SendTo me@example.com\n8: Subject (Message subject redacted)\n9: PostedDate 11/19/2008 03:34:15 PM\n10: MIME_Version 1.0\n11: $Mailer SMTP DirectMail\n12: $MIMETrack Itemize by SMTP Server on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:31 PM;Serialize by Router on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:32 PM;Serialize complete at 11/19/2008 05:34:32 PM;MIME-CD by Router on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:32 PM;MIME-CD complete at 11/19/2008 05:34:32 PM;Itemize by Router on camp-db-05/example(Release 7.0.2 HF76|November 03, 2006) at 11/19/2008 05:34:32 PM;MIME-CD by Notes Client on MyName/Guest/example(Release 6.5.6|March 06, 2007) at 11/20/2008 12:46:25 PM;MIME-CD complete at 11/20/2008 12:46:25 PM\n13: Form Memo\n14: $UpdatedBy ;CN=xxxPT02-CORP/O=example\n15: $ExportHeadersConverted 1\n16: $MessageID <redacted@LocalDomain>\n17: RouteServers CN=xxxPT02-CORP/O=example;CN=camp-db-05/O=example\n18: RouteTimes 11/19/2008 03:34:31 PM-11/19/2008 03:34:32 PM;11/19/2008 03:34:32 PM-11/19/2008 03:34:32 PM\n19: $Orig 958F2E4E4B666AB585257506007C02A7\n20: Categories \n21: $Revisions \n22: DeliveredDate 11/19/2008 03:34:32 PM\n23: Body []exampleexample\n" }, { "answer_id": 306683, "author": "Ken Pespisa", "author_id": 30812, "author_profile": "https://Stackoverflow.com/users/30812", "pm_score": 1, "selected": false, "text": "Dim doc As NotesDocument\nDim rtitem As Variant\nDim plainText As String\nDim fileNum As Integer\n'...set value of doc...\nSet rtitem = doc.GetFirstItem( \"Body\" )\nIf ( rtitem.Type = RICHTEXT ) Then\n plainText = rtitem.GetFormattedText( False, 0 )\nEnd If\n' get a file number for the file\nfileNum = Freefile\n' open the file for writing\nOpen \"c:\\plane.txt\" For Output As fileNum\n' write the formatted text to the file\nPrint #fileNum, plainText\n' close the file\nClose #fileNum\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11112/" ]
306,463
<p>Is there any performance gain using a CTE over a derived table?</p>
[ { "answer_id": 306624, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 3, "selected": true, "text": "Object[] ni = (Object[])nDoc.Items;\nstring names_values = \"\";\nfor (int x = 0; x < ni.Length; x++)\n{\nNotesItem item = (NotesItem)ni[x];\nif (!string.IsNullOrEmpty(item.Name)) names_values += x.ToString() + \": \" + item.Name + \"\\t\\t\" + item.Text + \"\\r\\n\";\n}\n 0: Received from example.com ([192.168.0.1]) by host.example.com (Lotus Domino Release 6.5.4 HF182) with ESMTP id 2008111917343129-205078 ; Wed, 19 Nov 2008 17:34:31 -0500\n1: Received from example.com ([192.168.0.2]) by host2.example.com (Lotus Domino Release 6.5.4 HF182) with ESMTP id 2008111917343129-205078 ; Wed, 19 Nov 2008 17:34:31 -0500\n2: X_PGRTRKID 130057945714t\n3: X_PGRSRC IE\n4: ReplyTo \"example\" <name@email.example.com>\n5: Principal \"example\" <customerservice@email.example.com>\n6: From \"IE130057945714t\"<service@test.email.example.com>\n7: SendTo me@example.com\n8: Subject (Message subject redacted)\n9: PostedDate 11/19/2008 03:34:15 PM\n10: MIME_Version 1.0\n11: $Mailer SMTP DirectMail\n12: $MIMETrack Itemize by SMTP Server on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:31 PM;Serialize by Router on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:32 PM;Serialize complete at 11/19/2008 05:34:32 PM;MIME-CD by Router on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:32 PM;MIME-CD complete at 11/19/2008 05:34:32 PM;Itemize by Router on camp-db-05/example(Release 7.0.2 HF76|November 03, 2006) at 11/19/2008 05:34:32 PM;MIME-CD by Notes Client on MyName/Guest/example(Release 6.5.6|March 06, 2007) at 11/20/2008 12:46:25 PM;MIME-CD complete at 11/20/2008 12:46:25 PM\n13: Form Memo\n14: $UpdatedBy ;CN=xxxPT02-CORP/O=example\n15: $ExportHeadersConverted 1\n16: $MessageID <redacted@LocalDomain>\n17: RouteServers CN=xxxPT02-CORP/O=example;CN=camp-db-05/O=example\n18: RouteTimes 11/19/2008 03:34:31 PM-11/19/2008 03:34:32 PM;11/19/2008 03:34:32 PM-11/19/2008 03:34:32 PM\n19: $Orig 958F2E4E4B666AB585257506007C02A7\n20: Categories \n21: $Revisions \n22: DeliveredDate 11/19/2008 03:34:32 PM\n23: Body []exampleexample\n" }, { "answer_id": 306683, "author": "Ken Pespisa", "author_id": 30812, "author_profile": "https://Stackoverflow.com/users/30812", "pm_score": 1, "selected": false, "text": "Dim doc As NotesDocument\nDim rtitem As Variant\nDim plainText As String\nDim fileNum As Integer\n'...set value of doc...\nSet rtitem = doc.GetFirstItem( \"Body\" )\nIf ( rtitem.Type = RICHTEXT ) Then\n plainText = rtitem.GetFormattedText( False, 0 )\nEnd If\n' get a file number for the file\nfileNum = Freefile\n' open the file for writing\nOpen \"c:\\plane.txt\" For Output As fileNum\n' write the formatted text to the file\nPrint #fileNum, plainText\n' close the file\nClose #fileNum\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343291/" ]
306,466
<p>I'm writing a script to display the 10 most recently "active" WordPress blog posts (i.e. those with the most recent comments). Problem is, the list has a lot of duplicates. I'd like to weed out the duplicates. Is there an easy way to do this by changing the MySQL query (like IGNORE, WHERE) or some other means? Here's what I have so far:</p> <pre><code>&lt;?php function cd_recently_active() { global $wpdb, $comments, $comment; $number = 10; //how many recently active posts to display? enter here if ( !$comments = wp_cache_get( 'recent_comments', 'widget' ) ) { $comments = $wpdb-&gt;get_results("SELECT comment_date, comment_author, comment_author_url, comment_ID, comment_post_ID, comment_content FROM $wpdb-&gt;comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT $number"); wp_cache_add( 'recent_comments', $comments, 'widget' ); } ?&gt; </code></pre>
[ { "answer_id": 307002, "author": "55skidoo", "author_id": 34964, "author_profile": "https://Stackoverflow.com/users/34964", "pm_score": 0, "selected": false, "text": " if ( !$comments = wp_cache_get( 'recent_comments', 'widget' ) ) {\n $comments = $wpdb->get_results(\"SELECT comment_post_ID, comment_author, comment_date FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID ORDER BY comment_date_gmt DESC LIMIT $number\");\n wp_cache_add( 'recent_comments', $comments, 'widget' );\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34964/" ]
306,475
<p>In SharePoint MOSS 2007, I have created a custom content type that I will be applying to a document library. One of the required fields is "Incoming Date" and another is the "Due Date". </p> <p>The Due Date is always 10 working days from the Incoming Date. The Incoming Date is when the mail room received the letter, not necessarily when the document is posted to the library.</p> <p>From here: <a href="http://msdn.microsoft.com/en-us/library/bb862071.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb862071.aspx</a></p> <pre><code>=DATE(YEAR([Incoming Date]),MONTH([Incoming Date]),DAY([Incoming Date])+10) </code></pre> <p>adds 10 days, but how can I add 10 working days? I don't have the luxury of VS.NET either per the governance plan of our sharepoint rollout.</p> <p>Assume a human is responsible for the data entry, but I would like to make it easier for them.</p>
[ { "answer_id": 620739, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "C_Wknd =IF(TEXT(WEEKDAY([Complaint Created On]),\"ddd\")=\"Mon\",11,13)\n\nC_NYDay =IF(AND([Complaint Created On]<=DATE(2009,1,1),([Complaint Created On])+C_Wknd>=DATE(2009,1,1)),\"1\",\"0\")\n\nC_MLKDay =IF(AND([Complaint Created On]<=DATE(2009,1,19),([Complaint Created On])+C_Wknd>=DATE(2009,1,19)),\"1\",\"0\")\n\nC_MemDay =IF(AND([Complaint Created On]<=DATE(2009,5,25),([Complaint Created On])+C_Wknd>=DATE(2009,5,25)),\"1\",\"0\")\n\nC_PresDay =IF(AND([Complaint Created On]<=DATE(2009,2,16),([Complaint Created On])+C_Wknd>=DATE(2009,2,16)),\"1\",\"0\")\n\nC_IndDay =IF(AND([Complaint Created On]<=DATE(2009,7,4),([Complaint Created On])+C_Wknd>=DATE(2009,7,4)),\"1\",\"0\")\n\nC_LabDay =IF(AND([Complaint Created On]<=DATE(2009,9,7),([Complaint Created On])+C_Wknd>=DATE(2009,9,7)),\"1\",\"0\")\n\nC_ColDay =IF(AND([Complaint Created On]<=DATE(2009,10,12),([Complaint Created On])+C_Wknd>=DATE(2009,10,12)),\"1\",\"0\")\n\nC_VetDay =IF(AND([Complaint Created On]<=DATE(2009,11,11),([Complaint Created On])+C_Wknd>=DATE(2009,11,11)),\"1\",\"0\")\n\nC_ThxDay =IF(AND([Complaint Created On]<=DATE(2009,11,26),([Complaint Created On])+C_Wknd>=DATE(2009,11,26)),\"1\",\"0\")\n\nC_XmsDay =IF(AND([Complaint Created On]<=DATE(2009,12,25),([Complaint Created On])+C_Wknd>=DATE(2009,12,25)),\"1\",\"0\")\n\nC_GrossDte =[Complaint Created On]+C_Wknd+C_NYDay+C_MLKDay+C_MemDay+C_PresDay+C_IndDay+C_LabDay+C_ColDay+C_VetDay+C_ThxDay+C_XmsDay\n\nC_EndSat =IF(TEXT(WEEKDAY(C_GrossDte),\"ddd\")=\"Sat\",2,0)\n\nC_EndSun =IF(TEXT(WEEKDAY(C_GrossDte),\"ddd\")=\"Sun\",1,0)\n\nResolution Due =C_GrossDte+C_EndSat+C_EndSun\n" }, { "answer_id": 16196567, "author": "user1566694", "author_id": 1566694, "author_profile": "https://Stackoverflow.com/users/1566694", "pm_score": 2, "selected": false, "text": "=[Start Date]+[Days to Complete] \n+ ROUNDDOWN([Days to Complete]/5,0)*2 \n+ IF(WEEKDAY([Start Date])+MOD([Days to Complete],5)>=7,2,0)\n- ROUNDDOWN(WEEKDAY([Start Date])/7,0) \n+ IF(AND(MOD([Days to Complete],5)=0,WEEKDAY([Start Date])=1),-2,0) \n+ IF(AND(MOD([Days to Complete],5)=0,WEEKDAY([Start Date])=7),-2,0) \n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24229/" ]
306,477
<p>I am using the MFC class <code>CSocket</code>. Nothing complicated - open a connection to a server and send a short message. The code works fine when I link with MFC in a DLL. However, the call to <code>CSocket::Create()</code> crashes when I link to MFC in a static library.</p> <p>I would like to use MFC in a static library since it simplifies distribution.</p>
[ { "answer_id": 14278279, "author": "user1969975", "author_id": 1969975, "author_profile": "https://Stackoverflow.com/users/1969975", "pm_score": 2, "selected": false, "text": " void SocketThreadInit()\n {\n #ifndef _AFXDLL\n #define _AFX_SOCK_THREAD_STATE AFX_MODULE_THREAD_STATE\n #define _afxSockThreadState AfxGetModuleThreadState()\n\n _AFX_SOCK_THREAD_STATE* pState = _afxSockThreadState;\n if (pState->m_pmapSocketHandle == NULL)\n pState->m_pmapSocketHandle = new CMapPtrToPtr;\n if (pState->m_pmapDeadSockets == NULL)\n pState->m_pmapDeadSockets = new CMapPtrToPtr;\n if (pState->m_plistSocketNotifications == NULL)\n pState->m_plistSocketNotifications = new CPtrList;\n\n #endif\n }\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16582/" ]
306,482
<p>I have the following command which will loop over all the subdirectories in a specific location and output the full path:</p> <pre><code>for /d %i in ("E:\Test\*") do echo %i </code></pre> <p>Will give me:</p> <pre><code>E:\Test\One E:\Test\Two </code></pre> <p>But how do I get both the full path, and just the directory name, so the do command might be something like:</p> <pre><code>echo %i - %j </code></pre> <p>And the output might be something like:</p> <pre><code>E:\Test\One - One E:\Test\Two - Two </code></pre> <p>Thanks in advance!</p>
[ { "answer_id": 306507, "author": "Craig Lebakken", "author_id": 33130, "author_profile": "https://Stackoverflow.com/users/33130", "pm_score": 3, "selected": true, "text": "%~fI - expands %I to a fully qualified path name\n%~nI - expands %I to a file name only\n for /d %i in (\"E:\\Test*\") do echo %~fi - %~ni\n" }, { "answer_id": 306521, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 0, "selected": false, "text": "for /d %i in (\"E:\\Test\\*\") do echo %i - %~ni\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39428/" ]
306,497
<p>I would like to be a PHP/MySQL programmer </p> <p>What are the technologies that I must know?</p> <p>Like:</p> <ol> <li>Frameworks</li> <li>IDEs</li> <li>Template Engines</li> <li>Ajax and CSS Frameworks</li> </ol> <p>Please tell me the minimum requirements that I must know, and tell me your favourite things in the previous list?</p> <p>Thanks</p>
[ { "answer_id": 306657, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "echo $some_variable_that_seems_innocent htmlspecialchars() addslashes() json_encode() rawurlencode() escapeshellargs()" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22634/" ]
306,504
<p>I'm creating a multi-part web form in ASP.NET that uses Panels for the different steps, making only the Panel for the current step visible. On Step 1, I have a drop-down list that uses a Javascript function to reconfigure some of the fields in the same Panel via "onchange". Obviously, since the client-side script is only affecting the DOM, when I go to Step 2 and then back up to Step 1, the fields in Step 1 are back to their orignal configuration even though the same drop-down choice is selected.</p> <p>What is a good method for storing the visual state of the Panels between steps? I considered calling the drop-down's onchange function on page load, but that seemed clunky. Thanks!</p> <p>--</p> <p>Thanks for the quick answers - I think I'll try out the Wizard, but the AJAX solution also sounds like fun.</p>
[ { "answer_id": 306657, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "echo $some_variable_that_seems_innocent htmlspecialchars() addslashes() json_encode() rawurlencode() escapeshellargs()" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22761/" ]
306,527
<p>I have a bit of code that looks like this:</p> <pre><code>text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff)); </code></pre> <p>I need to pass in a 2nd parameter like this:</p> <pre><code>text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff, otherData)); </code></pre> <p>Is this possible, and what would be the best way to do this?</p>
[ { "answer_id": 306564, "author": "Daniel Plaisted", "author_id": 1509, "author_profile": "https://Stackoverflow.com/users/1509", "pm_score": 5, "selected": false, "text": "text = reg.Replace(text, match => MatchEvalStuff(match, otherData));\n" }, { "answer_id": 306629, "author": "Jon Tackabury", "author_id": 343, "author_profile": "https://Stackoverflow.com/users/343", "pm_score": 5, "selected": true, "text": "private string MyMethod(Match match, bool param1, int param2)\n{\n //Do stuff here\n}\n\nRegex reg = new Regex(@\"{regex goes here}\", RegexOptions.IgnoreCase);\nContent = reg.Replace(Content, new MatchEvaluator(delegate(Match match) { return MyMethod(match, false, 0); }));\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343/" ]
306,531
<p>I have written a KornShell (ksh) script that sets an array the following way:</p> <pre><code>set -A fruits Apple Orange Banana Strawberry </code></pre> <p>but when I am trying to run it from within cron, it raises the following error:</p> <pre><code>Your "cron" job on myhost /myScript.sh produced the following output: myScript.sh: -A: bad option(s) </code></pre> <p>I have tried many crontab syntax variants, such as:</p> <p>Attempt 1:</p> <pre><code>0,5,10,15,20,25,30,35,40,45,50,55 * * * * /path/to/script/myScript.sh </code></pre> <p>Attempt 2:</p> <pre><code>0,5,10,15,20,25,30,35,40,45,50,55 * * * * /path/to/script/./myScript.sh </code></pre> <p>Attempt 3:</p> <pre><code>0,5,10,15,20,25,30,35,40,45,50,55 * * * * cd /path/to/script &amp;&amp; ./myScript.sh </code></pre> <p>Any workaround would be sincerely appreciated. Thanks much in advance!</p>
[ { "answer_id": 306673, "author": "Nano Taboada", "author_id": 6992, "author_profile": "https://Stackoverflow.com/users/6992", "pm_score": 2, "selected": true, "text": "0,5,10,15,20,25,30,35,40,45,50,55 * * * * cd /path/to/script && ksh ./myScript.sh\n" }, { "answer_id": 306879, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "myScript.sh #!/bin/ksh\n" }, { "answer_id": 8308492, "author": "Mandar Pande", "author_id": 673018, "author_profile": "https://Stackoverflow.com/users/673018", "pm_score": 2, "selected": false, "text": "*/5 * * * * cd /path/to/script && ksh ./myScript.sh" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
306,533
<p>How do you get a list of files within a directory so each can be processed?</p>
[ { "answer_id": 306542, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": true, "text": "boost::filesystem" }, { "answer_id": 306917, "author": "Chris Kloberdanz", "author_id": 28714, "author_profile": "https://Stackoverflow.com/users/28714", "pm_score": 5, "selected": false, "text": "#include <dirent.h>\n\nDIR *dpdf;\nstruct dirent *epdf;\n\ndpdf = opendir(\"./\");\nif (dpdf != NULL){\n while (epdf = readdir(dpdf)){\n printf(\"Filename: %s\",epdf->d_name);\n // std::cout << epdf->d_name << std::endl;\n }\n}\nclosedir(dpdf);\n" }, { "answer_id": 307071, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 2, "selected": false, "text": "#include <windows.h>\n#include <tchar.h> \n#include <stdio.h>\n#include <strsafe.h>\n\nvoid ErrorHandler(LPTSTR lpszFunction);\n\nint _tmain(int argc, TCHAR *argv[])\n{\n WIN32_FIND_DATA ffd;\n LARGE_INTEGER filesize;\n TCHAR szDir[MAX_PATH];\n size_t length_of_arg;\n HANDLE hFind = INVALID_HANDLE_VALUE;\n DWORD dwError=0;\n\n // If the directory is not specified as a command-line argument,\n // print usage.\n\n if(argc != 2)\n {\n _tprintf(TEXT(\"\\nUsage: %s <directory name>\\n\"), argv[0]);\n return (-1);\n }\n\n // Check that the input path plus 2 is not longer than MAX_PATH.\n\n StringCchLength(argv[1], MAX_PATH, &length_of_arg);\n\n if (length_of_arg > (MAX_PATH - 2))\n {\n _tprintf(TEXT(\"\\nDirectory path is too long.\\n\"));\n return (-1);\n }\n\n _tprintf(TEXT(\"\\nTarget directory is %s\\n\\n\"), argv[1]);\n\n // Prepare string for use with FindFile functions. First, copy the\n // string to a buffer, then append '\\*' to the directory name.\n\n StringCchCopy(szDir, MAX_PATH, argv[1]);\n StringCchCat(szDir, MAX_PATH, TEXT(\"\\\\*\"));\n\n // Find the first file in the directory.\n\n hFind = FindFirstFile(szDir, &ffd);\n\n if (INVALID_HANDLE_VALUE == hFind) \n {\n ErrorHandler(TEXT(\"FindFirstFile\"));\n return dwError;\n } \n\n // List all the files in the directory with some info about them.\n\n do\n {\n if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)\n {\n _tprintf(TEXT(\" %s <DIR>\\n\"), ffd.cFileName);\n }\n else\n {\n filesize.LowPart = ffd.nFileSizeLow;\n filesize.HighPart = ffd.nFileSizeHigh;\n _tprintf(TEXT(\" %s %ld bytes\\n\"), ffd.cFileName, filesize.QuadPart);\n }\n }\n while (FindNextFile(hFind, &ffd) != 0);\n\n dwError = GetLastError();\n if (dwError != ERROR_NO_MORE_FILES) \n {\n ErrorHandler(TEXT(\"FindFirstFile\"));\n }\n\n FindClose(hFind);\n return dwError;\n}\n\n\nvoid ErrorHandler(LPTSTR lpszFunction) \n{ \n // Retrieve the system error message for the last-error code\n\n LPVOID lpMsgBuf;\n LPVOID lpDisplayBuf;\n DWORD dw = GetLastError(); \n\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | \n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n dw,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPTSTR) &lpMsgBuf,\n 0, NULL );\n\n // Display the error message and exit the process\n\n lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, \n (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); \n StringCchPrintf((LPTSTR)lpDisplayBuf, \n LocalSize(lpDisplayBuf) / sizeof(TCHAR),\n TEXT(\"%s failed with error %d: %s\"), \n lpszFunction, dw, lpMsgBuf); \n MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT(\"Error\"), MB_OK); \n\n LocalFree(lpMsgBuf);\n LocalFree(lpDisplayBuf);\n}\n" }, { "answer_id": 1932861, "author": "Andreas Bonini", "author_id": 95135, "author_profile": "https://Stackoverflow.com/users/95135", "pm_score": 6, "selected": false, "text": "/* Returns a list of files in a directory (except the ones that begin with a dot) */\n\nvoid GetFilesInDirectory(std::vector<string> &out, const string &directory)\n{\n#ifdef WINDOWS\n HANDLE dir;\n WIN32_FIND_DATA file_data;\n\n if ((dir = FindFirstFile((directory + \"/*\").c_str(), &file_data)) == INVALID_HANDLE_VALUE)\n return; /* No files found */\n\n do {\n const string file_name = file_data.cFileName;\n const string full_file_name = directory + \"/\" + file_name;\n const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;\n\n if (file_name[0] == '.')\n continue;\n\n if (is_directory)\n continue;\n\n out.push_back(full_file_name);\n } while (FindNextFile(dir, &file_data));\n\n FindClose(dir);\n#else\n DIR *dir;\n class dirent *ent;\n class stat st;\n\n dir = opendir(directory);\n while ((ent = readdir(dir)) != NULL) {\n const string file_name = ent->d_name;\n const string full_file_name = directory + \"/\" + file_name;\n\n if (file_name[0] == '.')\n continue;\n\n if (stat(full_file_name.c_str(), &st) == -1)\n continue;\n\n const bool is_directory = (st.st_mode & S_IFDIR) != 0;\n\n if (is_directory)\n continue;\n\n out.push_back(full_file_name);\n }\n closedir(dir);\n#endif\n} // GetFilesInDirectory\n" }, { "answer_id": 1932864, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "HANDLE WINAPI FindFirstFile(\n __in LPCTSTR lpFileName,\n __out LPWIN32_FIND_DATA lpFindFileData\n);\n" }, { "answer_id": 17437528, "author": "Enders", "author_id": 2544579, "author_profile": "https://Stackoverflow.com/users/2544579", "pm_score": 0, "selected": false, "text": "#include <windows.h>\n\nint main() { \nsystem(\"dir /b > test.txt\");\n}\n" }, { "answer_id": 23506213, "author": "sam", "author_id": 3610162, "author_profile": "https://Stackoverflow.com/users/3610162", "pm_score": -1, "selected": false, "text": "void getFilesList(String filePath,String extension, vector<string> & returnFileName)\n{\n WIN32_FIND_DATA fileInfo;\n HANDLE hFind; \n String fullPath = filePath + extension;\n hFind = FindFirstFile(fullPath.c_str(), &fileInfo);\n if (hFind == INVALID_HANDLE_VALUE){return;} \n else {\n return FileName.push_back(filePath+fileInfo.cFileName);\n while (FindNextFile(hFind, &fileInfo) != 0){\n return FileName.push_back(filePath+fileInfo.cFileName);}\n }\n }\n\n\n String optfileName =\"\"; \n String inputFolderPath =\"\"; \n String extension = \"*.jpg*\";\n getFilesList(inputFolderPath,extension,filesPaths);\n vector<string>::const_iterator it = filesPaths.begin();\n while( it != filesPaths.end())\n {\n frame = imread(*it);//read file names\n //doyourwork here ( frame );\n sprintf(buf, \"%s/Out/%d.jpg\", optfileName.c_str(),it->c_str());\n imwrite(buf,frame); \n it++;\n }\n" }, { "answer_id": 24550404, "author": "mystack", "author_id": 1490489, "author_profile": "https://Stackoverflow.com/users/1490489", "pm_score": 0, "selected": false, "text": "CString dirpath=\"d:\\\\mydir\"\nDWORD errVal = ERROR_SUCCESS;\nHANDLE dir;\nWIN32_FIND_DATA file_data;\nCString file_name,full_file_name;\nif ((dir = FindFirstFile((dirname+ \"/*\"), &file_data)) == INVALID_HANDLE_VALUE)\n{\n errVal=ERROR_INVALID_ACCEL_HANDLE;\n return errVal;\n}\n\nwhile (FindNextFile(dir, &file_data)) {\n file_name = file_data.cFileName;\n full_file_name = dirname+ file_name;\n if (strcmp(file_data.cFileName, \".\") != 0 && strcmp(file_data.cFileName, \"..\") != 0)\n {\n m_List.AddTail(full_file_name);\n }\n}\n" }, { "answer_id": 31055801, "author": "Bad", "author_id": 4383472, "author_profile": "https://Stackoverflow.com/users/4383472", "pm_score": 2, "selected": false, "text": "boost::filesystem #include <string>\n#include <iostream>\n#include <boost/filesystem.hpp>\nusing namespace std;\nusing namespace boost::filesystem;\n\nint main()\n{\n path p(\"D:/AnyFolder\");\n for (auto i = directory_iterator(p); i != directory_iterator(); i++)\n {\n if (!is_directory(i->path())) //we eliminate directories in a list\n {\n cout << i->path().filename().string() << endl;\n }\n else\n continue;\n }\n}\n file1.txt\nfile2.dat\n" }, { "answer_id": 37908517, "author": "Jean Knapp", "author_id": 5806143, "author_profile": "https://Stackoverflow.com/users/5806143", "pm_score": 1, "selected": false, "text": "#include <atlstr.h>\n\nvoid getFiles(CString directory) {\n HANDLE dir;\n WIN32_FIND_DATA file_data;\n CString file_name, full_file_name;\n if ((dir = FindFirstFile((directory + \"/*\"), &file_data)) == INVALID_HANDLE_VALUE)\n {\n // Invalid directory\n }\n\n while (FindNextFile(dir, &file_data)) {\n file_name = file_data.cFileName;\n full_file_name = directory + file_name;\n if (strcmp(file_data.cFileName, \".\") != 0 && strcmp(file_data.cFileName, \"..\") != 0)\n {\n std::string fileName = full_file_name.GetString();\n // Do stuff with fileName\n }\n }\n}\n getFiles(\"i:\\\\Folder1\");\n" }, { "answer_id": 46105710, "author": "AdrianEddy", "author_id": 1007890, "author_profile": "https://Stackoverflow.com/users/1007890", "pm_score": 3, "selected": false, "text": "#include <dirent.h>\n\nif (auto dir = opendir(\"some_dir/\")) {\n while (auto f = readdir(dir)) {\n if (!f->d_name || f->d_name[0] == '.')\n continue; // Skip everything that starts with a dot\n\n printf(\"File: %s\\n\", f->d_name);\n }\n closedir(dir);\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370/" ]
306,541
<p>I've had this problem many times before, and I've never had a solution I felt good about. </p> <p>Let's say I have a Transaction base class and two derived classes AdjustmentTransaction and IssueTransaction.</p> <p>I have a list of transactions in the UI, and each transaction is of the concrete type AdjustmentTransaction or IssueTransaction.</p> <p>When I select a transaction, and click an "Edit" button, I need to decide whether to show an AdjustmentTransactionEditorForm or an IssueTransactionEditorForm.</p> <p>The question is how do I go about doing this in an OO fashion without having to use a switch statement on the type of the selected transaction? The switch statement works but feels kludgy. I feel like I should be able to somehow exploit the parallel inheritance hierarchy between Transactions and TransactionEditors.</p> <p>I could have an EditorForm property on my Transaction, but that is a horrible mixing of my UI peanut butter with my Model chocolate.</p> <p>Thanks in advance.</p>
[ { "answer_id": 306565, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": true, "text": "Dictionary <Type,Type> typeMapper = new Dictionary<Type,Type>();\ntypeMapper.Add(typeof(AdjustTransaction), typeof(AdjustTransactionForm));\n// etc, in this example, I'm populating it by hand, \n// in real life, I'd use a key/value pair mapping config file, \n// and populate it at runtime.\n Type formToGet;\nif (typeMapper.TryGetValue(CurrentTransaction.GetType(), out formToGet))\n{\n Form newForm = (Form)Activator.CreateInstance(formToGet);\n}\n" }, { "answer_id": 306569, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 1, "selected": false, "text": "Editing AdujustmentTransaction = AdjustmentTransactionEditorForm\nEditing IssueTransaction = IssueTransactionEditorForm\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3285/" ]
306,545
<p>With WinForms, I can use <code>Control.Scale</code> to scale a control larger. When I do that, all child controls are repositioned and scaled correctly, but font size remains the same.</p> <p>Is there an easy way to force font to scale up/down, or is the only way to manually update font for all controls when control is being scaled?</p> <p>Background: I'm working on a program in which I need to support zoom in/out to make labels, textboxs, etc. more readable for users with poor eyesight.</p>
[ { "answer_id": 306768, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 2, "selected": false, "text": " public partial class Form1 : Form {\n float mDesignSize;\n int mIncrement;\n public Form1() {\n InitializeComponent();\n mDesignSize = this.Font.SizeInPoints;\n }\n private void adjustFont() {\n float size = mDesignSize * (1 + mIncrement / 7f);\n this.Font = new Font(this.Font.FontFamily, size);\n }\n private void btnIncreaseFontSize_Click(object sender, EventArgs e) {\n mIncrement += 1;\n adjustFont();\n }\n private void btnDecreateFontSize_Click(object sender, EventArgs e) {\n mIncrement -= 1;\n adjustFont();\n }\n }\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124/" ]
306,551
<p>I am in a Windows Desktop application and I have a data stream and a mime type in the database. Is there a better way than writing it to a temp folder and launching the default editor for it?</p> <p>If I have to use the temp folder how can I get the file extension from the MIME type in a C# Windows Desktop application? </p>
[ { "answer_id": 306597, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 3, "selected": true, "text": "HKEY_CLASSES_ROOT\\MIME\\Database\\Content Type file" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30099/" ]
306,559
<p>I'm trying to figure out how to write this function:</p> <pre><code>template &lt;typename Bound&gt; Bound::result_type callFromAnyList(Bound b, list&lt;any&gt; p) { } </code></pre> <p>Then, if I had some function:</p> <pre><code>double myFunc(string s, int i) { return -3.0; } </code></pre> <p>I could call it by doing something like this:</p> <pre><code>list&lt;any&gt; p; p.push_back((string)"Hello"); p.push_back(7); double result = callFromAnyList(bind(myFunc, _1, _2), p); </code></pre> <p>Is it possible to write something like my <code>callFromAnyList</code> function? Can you inspect the result type and the parameter types from the type returned from <code>bind</code>? And then call <code>any_cast&lt;P1&gt;(*p.begin())</code>, etc? I've tried to understand the bind code, but it's a little hard to follow, and it doesn't appear as though they wrote it with inspection in mind.</p>
[ { "answer_id": 306691, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": true, "text": "template<typename>\nstruct return_of;\n\ntemplate<typename R>\nstruct return_of<R(*)()> {\n typedef R type;\n};\n\ntemplate<typename R, typename P1>\nstruct return_of<R(*)(P1)> {\n typedef R type;\n typedef P1 parameter_1;\n};\n\nvoid foo(int);\n\ntemplate<typename Func>\ntypename return_of<Func>::parameter_1 bar(Func f) {\n return 42;\n}\n\n// call: bar(foo);\n" }, { "answer_id": 306874, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 0, "selected": false, "text": "void invoke(void (f)(), list<any>& params)\n{\n f();\n}\n\ntemplate <typename R>\nvoid invoke(R (f)(), list<any>& params)\n{\n params.push_front(f());\n}\n\ntemplate <typename T0>\nvoid invoke(void (f)(T0), list<any>& params)\n{\n T0 t0 = any_cast<T0>(*params.begin()); params.pop_front();\n f(t0);\n}\n\ntemplate <typename R, typename T0>\nvoid invoke(R (f)(T0), list<any>& params)\n{\n T0 t0 = any_cast<T0>(*params.begin()); params.pop_front();\n params.push_front(f(t0));\n}\n\ntemplate <typename T0, typename T1>\nvoid invoke(void (f)(T0, T1), list<any>& params)\n{\n T0 t0 = any_cast<T0>(*params.begin()); params.pop_front();\n T1 t1 = any_cast<T1>(*params.begin()); params.pop_front();\n f(t0, t1);\n}\n\ntemplate <typename R, typename T0, typename T1>\nvoid invoke(R (f)(T0, T1), list<any>& params)\n{\n T0 t0 = any_cast<T0>(*params.begin()); params.pop_front();\n T1 t1 = any_cast<T1>(*params.begin()); params.pop_front();\n params.push_front(f(t0, t1));\n}\n\ntemplate <typename T0, typename T1, typename T2>\nvoid invoke(void (f)(T0, T1, T2), list<any>& params)\n{\n T0 t0 = any_cast<T0>(*params.begin()); params.pop_front();\n T1 t1 = any_cast<T1>(*params.begin()); params.pop_front();\n T2 t2 = any_cast<T2>(*params.begin()); params.pop_front();\n f(t0, t1, t2);\n}\n\ntemplate <typename R, typename T0, typename T1, typename T2>\nvoid invoke(R (f)(T0, T1, T2), list<any>& params)\n{\n T0 t0 = any_cast<T0>(*params.begin()); params.pop_front();\n T1 t1 = any_cast<T1>(*params.begin()); params.pop_front();\n T2 t2 = any_cast<T2>(*params.begin()); params.pop_front();\n params.push_front(f(t0, t1, t2));\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8643/" ]
306,572
<p>I recently started building a console version of a web application. I copied my custom sections from my web.config. to my app.config. When I go to get config information i get this error:</p> <p>An error occurred creating the configuration section handler for x/y: Could not load type 'x' from assembly 'System.Configuration</p> <p>The line that it is not liking is:</p> <p>return ConfigurationManager.GetSection("X/Y") as Z;</p> <p>Anyone run into something like this?</p> <p>I was able to add </p> <pre><code>&lt;add key="IsReadable" value="0"/&gt; </code></pre> <p>in the appSettings and read it.</p> <p>Addition:</p> <p>I do actually have this defined about the custom section:</p> <pre><code> &lt;configSections&gt; &lt;sectionGroup name="x"&gt; &lt;section name="y" type="zzzzz"/&gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; </code></pre>
[ { "answer_id": 306575, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": true, "text": "<configSection>\n <section\n name=\"YOUR_CLASS_NAME_HERE\"\n type=\"YOUR.NAMESPACE.CLASSNAME, YOUR.NAMESPACE, Version=1.1.0.0, Culture=neutral, PublicKeyToken=PUBLIC_TOKEN_ID_FROM_ASSEMBLY\"\n allowLocation=\"true\"\n allowDefinition=\"Everywhere\"\n />\n</configSection>\n" }, { "answer_id": 306582, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 0, "selected": false, "text": "<configuration>\n <configSections>\n <sectionGroup name=\"x\">\n <section name=\"y\" type=\"a, b\"/>\n </sectionGroup>\n <configSections>\n</configuration>\n" }, { "answer_id": 306619, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "public class XmlConfigurator : IConfigurationSectionHandler\n {\n public object Create(object parent, object configContext, XmlNode section)\n {\n if (section == null) return null;\n Type sectionType = Type.GetType((string)(section.CreateNavigator()).Evaluate(\"string(@configType)\"));\n XmlSerializer xs = new XmlSerializer(sectionType);\n return xs.Deserialize(new XmlNodeReader(section));\n }\n }\n <section name=\"NameofConfigSection\" type=\"NameSpace.XmlConfigurator, NameSpace.Assembly\"/>\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n\n<NameofConfigSection configType=\"NameSpace.NameofTypeToDeserializeInto, Namespace.Assembly\" >\n\n ... \n\n</NameofConfigSection>\n" }, { "answer_id": 1562609, "author": "Alexis Abril", "author_id": 133753, "author_profile": "https://Stackoverflow.com/users/133753", "pm_score": 2, "selected": false, "text": "<configSection>\n <section\n name=\"yourClassName\"\n type=\"your.namespace.className, your.assembly\"\n allowLocation=\"true\"\n allowDefinition=\"Everywhere\" />\n</configSection>\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
306,573
<p>Is it possible to have a file belong to multiple subpackages? For example:</p> <pre><code>/** * Name * * Desc * * @package Core * @subpackage Sub1 * @subpackage Sub2 */ </code></pre> <p>Thanks!</p>
[ { "answer_id": 11404615, "author": "E Brent Nelson", "author_id": 1513307, "author_profile": "https://Stackoverflow.com/users/1513307", "pm_score": 2, "selected": false, "text": "* @package popcap\\system\\cache\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538/" ]
306,579
<p>I would like to be able to Serialize a DateTime with a specific Time Zone that is not the server, nor is it client time. Basically, any time zone. Is it possible to override the DateTime serialization, in .Net2.0 webservices?</p> <p>I compile an xmlschema using xsd.exe, so I made an attempt using XmlSchemaImporter.</p> <p>The OnSerialize examples show value changes, but not changes to the output format.</p> <p>XmlSchemaImporter, loaded it into the gac, ran xsd.exe, and generated code that has the class I want... but that class is an attribute, which end up not being able to be reflected.</p> <blockquote> <p>[InvalidOperationException: Cannot serialize member 'metadataDateTime' of type Cuahsi.XmlOverrides.W3CDateTime. XmlAttribute/XmlText cannot be used to encode complex types.]</p> </blockquote> <p>Generated code</p> <pre><code>[System.Xml.Serialization.XmlAttributeAttribute()] public Cuahsi.XmlOverrides.W3CDateTime dateTime { get { return this.dateTimeField; } set { this.dateTimeField = value; } } </code></pre> <p>XmlSchemaImporter</p> <pre><code>public class ImportW3CTime : System.Xml.Serialization.Advanced.SchemaImporterExtension { public override string ImportSchemaType(string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (XmlSchema.Namespace == ns) { switch (name) { case "dateTime": string codeTypeName = typeof(W3CDateTime).FullName; CodeTypeDeclaration cls = new CodeTypeDeclaration("W3CDateTime"); cls.IsStruct = true; cls.Attributes = MemberAttributes.Public; cls.BaseTypes.Add("dateTime"); mainNamespace.Types.Add(cls); return codeTypeName; default: return null; } } else { return null; } } } </code></pre> <p><strong>Addendum 1:</strong> I just tired DateTimeoffset, and that still causes an error when the class is tagged like:</p> <pre><code>[System.Xml.Serialization.XmlAttributeAttribute(DataType = "dateTime")] public System.DateTimeOffset metadataDateTime { get { return this.metadataDateTimeField; } set { this.metadataDateTimeField = value; } } </code></pre>
[ { "answer_id": 7140219, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 2, "selected": false, "text": "DateTimeOffset // Don't serialize this one\n[System.Xml.Serialization.XmlIgnore]\npublic System.DateTimeOffset metadataDateTime\n{\n get { ... }\n set { ... }\n}\n\n\n// Serialize this one instead\n[System.Xml.Serialization.XmlAttribute(\"metadataDateTime\")]\npublic string metadataDateTimeXml\n{\n get { /* format metadataDateTime to custom format */ }\n set { /* parse metadataDateTime from custom format */ }\n}\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36627/" ]
306,583
<p>I have a layout similar to this:</p> <pre><code>&lt;div id="..."&gt;&lt;img src="..."&gt;&lt;/div&gt; </code></pre> <p>and would like to use a jQuery selector to select the child <code>img</code> inside the <code>div</code> on click.</p> <p>To get the <code>div</code>, I've got this selector:</p> <pre><code>$(this) </code></pre> <p>How can I get the child <code>img</code> using a selector?</p>
[ { "answer_id": 306608, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 5, "selected": false, "text": "$(this).children()[0]\n" }, { "answer_id": 306632, "author": "Adam", "author_id": 36324, "author_profile": "https://Stackoverflow.com/users/36324", "pm_score": 5, "selected": false, "text": "$(\"#\"+$(this).attr(\"id\")+\" img:first\")\n" }, { "answer_id": 306892, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 9, "selected": false, "text": "$(this).find('img');\n img div" }, { "answer_id": 306904, "author": "Simon", "author_id": 33036, "author_profile": "https://Stackoverflow.com/users/33036", "pm_score": 13, "selected": true, "text": "context jQuery(\"img\", this);\n .find() jQuery(this).find(\"img\");\n .children() jQuery(this).children(\"img\");\n" }, { "answer_id": 6425986, "author": "Roccivic", "author_id": 201232, "author_profile": "https://Stackoverflow.com/users/201232", "pm_score": 6, "selected": false, "text": "$(this).next();\n" }, { "answer_id": 6781092, "author": "rakslice", "author_id": 60422, "author_profile": "https://Stackoverflow.com/users/60422", "pm_score": 7, "selected": false, "text": "img $(this).children(\"img:first\")\n" }, { "answer_id": 11511772, "author": "Rayron Victor", "author_id": 1296336, "author_profile": "https://Stackoverflow.com/users/1296336", "pm_score": 6, "selected": false, "text": "$('> .child-class', this)\n" }, { "answer_id": 15565496, "author": "Lalit Kumar Maurya", "author_id": 1637683, "author_profile": "https://Stackoverflow.com/users/1637683", "pm_score": 6, "selected": false, "text": "img $(this).find('img') or $(this).children('img')\n img $(this).children('img:nth(n)') \n// where n is the child place in parent list start from 0 onwards\n img $(this).find(\"img\").attr(\"alt\")\n OR\n $(this).children(\"img\").attr(\"alt\")\n img <div class=\"mydiv\">\n <img src=\"test.png\" alt=\"3\">\n <img src=\"test.png\" alt=\"4\">\n</div>\n $(this).find(\"img:last-child\").attr(\"alt\")\n OR\n $(this).children(\"img:last-child\").attr(\"alt\")\n <div class=\"mydiv\">\n <img class='first' src=\"test.png\" alt=\"3\">\n <img class='second' src=\"test.png\" alt=\"4\">\n</div>\n $(this).find(\".first\").attr(\"alt\")\n $(this).find(\"img.first\").attr(\"alt\")\n" }, { "answer_id": 17314282, "author": "Thirumalai murugan", "author_id": 538669, "author_profile": "https://Stackoverflow.com/users/538669", "pm_score": 5, "selected": false, "text": "each <div id=\"test\">\n <img src=\"testing.png\"/>\n <img src=\"testing1.png\"/>\n</div>\n\n$('#test img').each(function(){\n console.log($(this).attr('src'));\n});\n" }, { "answer_id": 24965114, "author": "Dennis R", "author_id": 3485999, "author_profile": "https://Stackoverflow.com/users/3485999", "pm_score": 4, "selected": false, "text": "$(' > img', this).attr(\"src\");\n $(this) img div $('#divid > img').attr(\"src\");\n" }, { "answer_id": 28135547, "author": "Oskar", "author_id": 2534288, "author_profile": "https://Stackoverflow.com/users/2534288", "pm_score": 5, "selected": false, "text": "$(this).find(\"img\"); // any img tag child or grandchild etc... \n$(this).children(\"img\"); //any img tag child that is direct descendant \n$(this).find(\"img:first\") //any img tag first child or first grandchild etc...\n$(this).children(\"img:first\") //the first img tag child that is direct descendant \n$(this).children(\"img:nth-child(1)\") //the img is first direct descendant child\n$(this).next(); //the img is first direct descendant child\n" }, { "answer_id": 30960095, "author": "tetutato", "author_id": 5001158, "author_profile": "https://Stackoverflow.com/users/5001158", "pm_score": 4, "selected": false, "text": "$(\"#id img\")\n" }, { "answer_id": 32008999, "author": "Mike Clark", "author_id": 4261022, "author_profile": "https://Stackoverflow.com/users/4261022", "pm_score": 5, "selected": false, "text": "$(this).find('img');\n $(this).children('img');\n" }, { "answer_id": 41367463, "author": "RPichioli", "author_id": 5885146, "author_profile": "https://Stackoverflow.com/users/5885146", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n // When you click the DIV, you take it with \"this\"\n $('#my_div').click(function() {\n console.info('Initializing the tests..');\n console.log('Method #1: '+$(this).children('img'));\n console.log('Method #2: '+$(this).find('img'));\n // Here, i'm selecting the first ocorrence of <IMG>\n console.log('Method #3: '+$(this).find('img:eq(0)'));\n });\n}); .the_div{\n background-color: yellow;\n width: 100%;\n height: 200px;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n<div id=\"my_div\" class=\"the_div\">\n <img src=\"...\">\n</div>" }, { "answer_id": 42608899, "author": "Sumit Lahiri", "author_id": 6243681, "author_profile": "https://Stackoverflow.com/users/6243681", "pm_score": 2, "selected": false, "text": "$(document).ready(function() {\n // When you click the DIV, you take it with \"this\"\n $('#my_div').click(function() {\n console.info('Initializing the tests..');\n console.log('Method #1: '+$(this).children('img'));\n console.log('Method #2: '+$(this).find('img'));\n // Here, i'm selecting the first ocorrence of <IMG>\n console.log('Method #3: '+$(this).find('img:eq(0)'));\n });\n}); .the_div{\n background-color: yellow;\n width: 100%;\n height: 200px;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n<div id=\"my_div\" class=\"the_div\">\n <img src=\"...\">\n</div>" }, { "answer_id": 45842093, "author": "Jason Williams", "author_id": 2733283, "author_profile": "https://Stackoverflow.com/users/2733283", "pm_score": 3, "selected": false, "text": "<img> <div> .find() .each() .find() .each() <img> <img> // Set the click handler on your div\n$(\"body\").off(\"click\", \"#mydiv\").on(\"click\", \"#mydiv\", function() {\n\n // Find the image using.find() and .each()\n $(this).find(\"img\").each(function() {\n \n var img = this; // \"this\" is, now, scoped to the image element\n \n // Do something with the image\n $(this).animate({\n width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + \"px\"\n }, 500);\n \n });\n \n}); #mydiv {\n text-align: center;\n vertical-align: middle;\n background-color: #000000;\n cursor: pointer;\n padding: 50px;\n \n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n\n<div id=\"mydiv\">\n <img src=\"\" width=\"100\" height=\"100\"/>\n</div>" }, { "answer_id": 58005680, "author": "Hassan Fayyaz", "author_id": 7800690, "author_profile": "https://Stackoverflow.com/users/7800690", "pm_score": -1, "selected": false, "text": " <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\">\n $(this).find('img');\n</script>\n" }, { "answer_id": 61653406, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 1, "selected": false, "text": "$(this.firstChild);\n $( \"#box\" ).click( function() {\n let img = $(this.firstChild);\n console.log({img});\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"box\"><img src=\"https://picsum.photos/seed/picsum/300/150\"></div>" }, { "answer_id": 66812429, "author": "Vishnu Prasanth G", "author_id": 6624082, "author_profile": "https://Stackoverflow.com/users/6624082", "pm_score": 0, "selected": false, "text": "this.querySelectorAll(\"img\") this.querySelector(\"img\")" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16974/" ]
306,591
<p>I'm trying to get the contents from another file with <code>file_get_contents</code> (don't ask why).<br /> I have two files: <em>test1.php</em> and <em>test2.php</em>. <em>test1.php</em> returns a string, bases on the user that is logged in.</p> <p><em>test2.php</em> tries to get the contents of <em>test1.php</em> and is being executed by the browser, thus getting the cookies.</p> <p>To send the cookies with <code>file_get_contents</code>, I create a streaming context:</p> <pre><code>$opts = array('http' =&gt; array('header'=&gt; 'Cookie: ' . $_SERVER['HTTP_COOKIE'].&quot;\r\n&quot;))`; </code></pre> <p>I'm retrieving the contents with:</p> <pre><code>$contents = file_get_contents(&quot;http://www.example.com/test1.php&quot;, false, $opts); </code></pre> <p>But now I get the error:</p> <blockquote> <p>Warning: file_get_contents(<a href="http://www.example.com/test1.php" rel="nofollow noreferrer">http://www.example.com/test1.php</a>) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found</p> </blockquote> <p>Does somebody knows what I'm doing wrong here?</p> <p>edit:<br /> forgot to mention: Without the <em>streaming_context</em>, the page just loads. But without the cookies I don't get the info I need.</p>
[ { "answer_id": 308060, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 6, "selected": true, "text": "$opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE'].\"\\r\\n\"));\n$context = stream_context_create($opts);\n$contents = file_get_contents('http://example.com/test1.txt', false, $context);\necho $contents;\n" }, { "answer_id": 3027043, "author": "Jason", "author_id": 365014, "author_profile": "https://Stackoverflow.com/users/365014", "pm_score": 1, "selected": false, "text": "file_get_contents str_replace" }, { "answer_id": 9509776, "author": "Yves Lange", "author_id": 1173553, "author_profile": "https://Stackoverflow.com/users/1173553", "pm_score": 4, "selected": false, "text": "session_start() fsockopen() file_get_contents() session_write_close() session_start() <?php\n $opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE'].\"\\r\\n\"));\n $context = stream_context_create($opts);\n session_write_close(); // unlock the file\n $contents = file_get_contents('http://120.0.0.1/controler.php?c=test_session', false, $context);\n session_start(); // Lock the file\n echo $contents;\n?>\n file_get_contents() fsockopen()" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20261/" ]
306,596
<p>I am trying to deserialize a stream but I always get this error "End of Stream encountered before parsing was completed"?</p> <p>Here is the code:</p> <pre><code> //Some code here BinaryFormatter b = new BinaryFormatter(); return (myObject)b.Deserialize(s);//s---&gt; is a Stream object that has been fill up with data some line over here </code></pre> <p>Any one have ideas?</p>
[ { "answer_id": 306598, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 7, "selected": true, "text": " BinaryFormatter b = new BinaryFormatter();\n s.Position = 0;\n return (YourObjectType)b.Deserialize(s);\n" }, { "answer_id": 29947537, "author": "Alia Ramli Ramli", "author_id": 1040959, "author_profile": "https://Stackoverflow.com/users/1040959", "pm_score": 0, "selected": false, "text": "stream.Seek(0, SeekOrigin.Begin);\n" }, { "answer_id": 58977787, "author": "Yaroslav", "author_id": 7094638, "author_profile": "https://Stackoverflow.com/users/7094638", "pm_score": 0, "selected": false, "text": "using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace ConsoleApp3\n{\n class Program\n {\n static void Main(string[] args)\n {\n string large = LargeJsonContent.GetBigObject();\n string base64;\n\n using (var readStream = new MemoryStream())\n using (var writeStream = new MemoryStream())\n {\n using (GZipStream compressor = new GZipStream(writeStream, CompressionMode.Compress, true)) //pay attention to leaveOpen = true\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(readStream, large);\n\n Console.WriteLine($\"After binary serialization of JsonString: {readStream.Length} bytes\");\n\n readStream.Position = 0;\n readStream.CopyTo(compressor);\n }\n\n Console.WriteLine($\"Compressed stream size: {writeStream.Length} bytes\");\n\n writeStream.Position = 0;\n byte[] writeBytes = writeStream.ToArray();\n base64 = Convert.ToBase64String(writeBytes);\n }\n\n\n ////\n\n using (var stream = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(stream, base64);\n Console.WriteLine($\"Size of base64: {stream.Length} bytes\");\n }\n\n Console.WriteLine(\"---------------------\");\n ////\n\n string large2;\n\n var bytes = Convert.FromBase64String(base64);\n using (var readStream = new MemoryStream())\n {\n readStream.Write(bytes, 0, bytes.Length);\n readStream.Position = 0;\n Console.WriteLine($\"Compressed stream size: {readStream.Length} bytes\");\n using (var writeStream = new MemoryStream())\n {\n using (GZipStream decompressor = new GZipStream(readStream, CompressionMode.Decompress, true)) //pay attention to leaveOpen = true\n {\n decompressor.CopyTo(writeStream);\n writeStream.Position = 0;\n }\n\n var formatter = new BinaryFormatter();\n large2 = (string)formatter.Deserialize(writeStream);\n }\n }\n\n Console.WriteLine(large == large2);\n Console.WriteLine($\"large:{large.Length} | large2:{large2.Length}\");\n }\n }\n}\n\n" }, { "answer_id": 64100356, "author": "Mukesh Pareek", "author_id": 4360948, "author_profile": "https://Stackoverflow.com/users/4360948", "pm_score": 0, "selected": false, "text": "NetworkStream strm = client.GetStream(); // the stream\nformatter.Serialize(strm, status); // the serialization process\nstrm.Close();// Remove this code, this was the culprit in my case\n" } ]
2008/11/20
[ "https://Stackoverflow.com/questions/306596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14441/" ]