qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
259,532
<p>I'm getting something pretty strange going on when trying to read some data using the MySql .net connector. Here's the code:</p> <pre><code>IDataReader reader = null; using (MySqlConnection connection = new MySqlConnection(this.ConnectionString)) { String getSearch = "select * from organization"; MySqlCommand cmd = new MySqlCommand(getSearch, connection); cmd.CommandType = CommandType.Text; connection.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { // response write some stuff to the screen (snipped for brevity) } } </code></pre> <p>If I put a breakpoint after the ExecuteReader and expand the results view in Visual Studio (hovering over reader and expanding), I can see the rows returned by the query. If I then let that close and expand the results view again, I get the message 'Enumeration yielded no results'.</p> <p>It seems as if the contents of the reader are getting reset as soon as they're viewed.</p> <p>As for what we've tried:<br> - the SQL runs fine directly on to DB<br> - Binding the results of the query directly to a datagrid just returns an empty datagrid<br> - got the latest version of the .net connector<br> - tried on two different machines to rule out any local errors</p> <p>So far nothing's worked.</p> <p>If anyone could offer any ideas or suggestions they would be very much appreciated.</p>
[ { "answer_id": 259595, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "cmd.ExecuteReader(); Typed DataSet DataSet optimizations Connection ExecuteReader using IDisposable Command IDisposable" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33721/" ]
259,534
<p>Thanks for going to answer my question. I have the folowing pages.</p> <ul> <li>login.aspx</li> <li>default.aspx</li> <li>xxx.aspx</li> </ul> <p>After logging into application default.aspx will be displayed. Now if the user is trying to open <a href="http://server/" rel="nofollow noreferrer">http://server/</a><strong>xxx.aspx</strong>?Id=1234 by specifying its URL directly in a browser, the login screen is displayed and after successfull login, system redirects to "default.aspx" and not to "<a href="http://server/" rel="nofollow noreferrer">http://server/</a><strong>xxx.aspx</strong>?Id=1234". Actually there is an external application that would call my system like that. So Please let me know why is this happening. The .Net login control is used to login into the application. Kindly help me to solve this issue.</p> <p>Thanks,<br> Ang Vin</p>
[ { "answer_id": 259541, "author": "Markus Nigbur", "author_id": 33231, "author_profile": "https://Stackoverflow.com/users/33231", "pm_score": 0, "selected": false, "text": "Response.Redirect(Request.UrlReferrer.ToString());\n" }, { "answer_id": 259579, "author": "wonderchook", "author_id": 32113, "author_profile": "https://Stackoverflow.com/users/32113", "pm_score": 2, "selected": false, "text": "<authentication mode=\"Forms\">\n <forms name=\"FwLoginCookie\" loginUrl=\"Login.aspx\"\n protection=\"All\" \n path=\"/\" >\n </forms>\n </authentication>\n <authorization>\n <deny users=\"?\"/>\n </authorization>\n" }, { "answer_id": 259608, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 1, "selected": false, "text": "<asp:Login \n ID=\"Login1\" \n runat=\"server\" \n DestinationPageUrl=\"~/Default.aspx\">\n</asp:Login>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33722/" ]
259,536
<p>Does anyone has a good solution for a C# version of the C++ __FUNCTION__ macro? The compiler does not seem to like it.</p>
[ { "answer_id": 259544, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 6, "selected": true, "text": "System.Reflection.MethodBase.GetCurrentMethod().Name\n __LINE__ __FUNCTION__" }, { "answer_id": 259545, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 3, "selected": false, "text": "System.Reflection.MethodBase.GetCurrentMethod().Name\n" }, { "answer_id": 334255, "author": "Mark Booth", "author_id": 42473, "author_profile": "https://Stackoverflow.com/users/42473", "pm_score": 3, "selected": false, "text": "using System.Diagnostics;\n\npublic string __Function() {\n StackTrace stackTrace = new StackTrace();\n return stackTrace.GetFrame(1).GetMethod().Name;\n}\n Debug.Assert(false, __Function() + \": Unhandled option\");\n [ Conditional(\"Debug\") ]\n" }, { "answer_id": 31132484, "author": "ShloEmi", "author_id": 2759057, "author_profile": "https://Stackoverflow.com/users/2759057", "pm_score": 2, "selected": false, "text": "public static string CallerName([CallerMemberName] string callerName = \"\")\n{\n return callerName;\n}\n s_log.DebugFormat(\"{0}\", CallerName());\n s_log.Debug(\"CallerName\");\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21704/" ]
259,540
<p>It seems that the following piece of HTML is ignored in IE7 but works ok in IE6/FF. It supposes to override all the html links to be opened in the desired frame</p> <pre><code>&lt;HEAD&gt; &lt;title&gt;LeftPane&lt;/title&gt; &lt;base target="rightFrame"&gt; &lt;/HEAD&gt; </code></pre> <p>The above code is the header of a left frame that holds an Infragistics UltraWebTree (tree menu) which doesn't support the TargetFrame property.</p> <p>Is there another way to add the target attribute to all the links elements on the desired page. </p> <p>Any server or client-side code workarounds?</p> <p>The site is built on ASP.Net 1.1 and Infragistics V 2.0</p> <p><strong>Update</strong> the web page is aspx an the doctype is </p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" &gt; </code></pre>
[ { "answer_id": 259549, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "href=\"\"" }, { "answer_id": 260172, "author": "Oscar Cabrero", "author_id": 14440, "author_profile": "https://Stackoverflow.com/users/14440", "pm_score": 1, "selected": true, "text": "<script language=\"javascript\">\n\n var tags=document.getElementsByTagName(\"a\");\n for (i=0;i<tags.length;i++)\n { \n if(!tags[i].getAttribute('target'))\n {\n tags[i].setAttribute('target',\"right\")\n }\n }\n\n\n </script> \n" }, { "answer_id": 13844085, "author": "Peter", "author_id": 1898468, "author_profile": "https://Stackoverflow.com/users/1898468", "pm_score": 1, "selected": false, "text": "BASE HEAD head </head>" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14440/" ]
259,547
<p>If I have a table like this:</p> <pre><code>CREATE TABLE sizes ( name ENUM('small', 'medium', 'large') ); </code></pre> <p>Is MySQL going to store those strings in every row, or internally will it use something smaller like integers to know which enum value to refer to?</p> <p>I want to use an enum in a table but I'm worried if it's as wasteful as storing a string in every row.</p>
[ { "answer_id": 259561, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 6, "selected": true, "text": "SELECT mycolumn + 0" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
259,562
<p>I'm an old hand at embedded programming but new to CE and having a lot of trouble doing reasonably simple things, because I am not familiar with the API and struggling to understand the obscure MSDN docs.</p> <p>All I want to do is minimize and maximise two separate applications that are running from one of the applications.</p> <p>E.g. Application A decides that now it is time for it to appear and then minimises application B (App B being a third party application e.g. Notepad, no access to source code etc) and then at a later stage maximising B and minimising itself.</p> <p>Application A would be written by myself.</p> <p>I'm sure this must be very simple, but where to find answers.. :)</p> <p>Thanks in advance. EOI</p>
[ { "answer_id": 259582, "author": "Craig Nicholson", "author_id": 28305, "author_profile": "https://Stackoverflow.com/users/28305", "pm_score": 1, "selected": false, "text": "HWND hWnd = ::FindWindow( _T(\"Notepad\"), NULL); \n::ShowWindow(hWnd, SW_HIDE); \n" }, { "answer_id": 268279, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 0, "selected": false, "text": "SetWindowPos(windowToHide, 0, 0, 0, 0, 0, SWP_HIDEWINDOW);\nSetWindowPos(windowToShowInFullScreen, HWND_TOP, 0, 0, 240, 320, SWP_SHOWWINDOW);\nSetForegroundWindow(windowToShow);\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33720/" ]
259,575
<p>I am writing a java program that needs a file open dialog. The file open dialog isn't difficult, I'm hoping to use a <code>JFileChooser</code>. My problem is that I would like to have a dual pane <code>JFrame</code> (consisting of 2 <code>JPanels</code>). The left panel would have a <code>JList</code>, and the right panel would have a file open dialog. </p> <p>When I use <code>JFileChooser.showOpenDialog()</code> this opens the dialog box above all other windows, which isn't what I want. Is there any way to have the <code>JFileChooser</code> (or maybe another file selection dialog) display inside a <code>JPanel</code> and not pop-up above it?</p> <p>Here is the code that I've tried, at this point it's very simplified. I'm only trying to get the <code>JFileChooser</code> to be embedded in the <code>JPanel</code> at this point.</p> <pre><code>public class JFC extends JFrame{ public JFC() { setSize(800,600); JPanel panel= new JPanel(); JFileChooser chooser = new JFileChooser(); panel.add(chooser); setVisible(true); chooser.showOpenDialog(null); } public static void main(String[] args) { JFC blah = new JFC(); } } </code></pre> <p>I have also tried calling <code>chooser.showOpenDialog</code> with <code>this</code> and <code>panel</code>, but to no avail. Also, I have tried adding the <code>JFileChooser</code> directly to the frame. Both of the attempts listed above still have the <code>JFileChooser</code> pop up in front of the frame or panel (depending on which I add the <code>JFileChooser</code> to).</p>
[ { "answer_id": 259583, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 5, "selected": true, "text": "JFileChooser fc = ...\nJPanel panel ...\npanel.add(fc);\n" }, { "answer_id": 264697, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "fileChooser.addActionListener(this);\n[...]\n\npublic void actionPerformed(ActionEvent action)\n{\n if (action.getActionCommand().equals(\"CancelSelection\"))\n {\n System.out.printf(\"CancelSelection\\n\");\n this.setVisible(false);\n this.dispose();\n }\n if (action.getActionCommand().equals(\"ApproveSelection\"))\n {\n System.out.printf(\"ApproveSelection\\n\");\n this.setVisible(false);\n this.dispose();\n }\n}\n" }, { "answer_id": 1406359, "author": "Carles Barrobés", "author_id": 166761, "author_profile": "https://Stackoverflow.com/users/166761", "pm_score": 2, "selected": false, "text": "JFileChooser.APPROVE_SELECTION JFileChooser.CANCEL_SELECTION" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33725/" ]
259,587
<p>We have 3 applications using 3 different spring configuration files. But we have one database and one datasource, so one session factory.Hhow can we import the session factory bean into the 3 different spring config files?</p>
[ { "answer_id": 259599, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 2, "selected": false, "text": "<import resource=\"database-config.xml\"/>\n" }, { "answer_id": 259779, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 2, "selected": false, "text": "<beans>\n <import resource=\"classpath:path/to/session-factory-beans.xml\"/>\n <... other bean definitions.../>\n</beans>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
259,600
<p>I've read quite a bit of the Red Bean Software SVN Book, and some of the questions here on SO, but I want to make sure I'm going about this in the right way the first time around step-by-step before I begin using it. Is this correct?</p> <ol> <li>Install SVN.</li> <li><p>Create SVN repository at /usr/local/svn. Directory structure looks like this:</p> <pre><code>-- conf -- db -- format -- hooks -- locks -- README.txt </code></pre></li> <li><p>Create folders through command line for repository organization (including projects and vendors).</p> <pre><code>-- conf -- db -- format -- hooks -- locks -- projects -- project_name -- vendor -- trunk -- branches -- tags -- project_name -- vendor -- trunk -- branches -- tags -- README.txt </code></pre></li> <li><p>Checkout vendor code into vendor folder under the correct project name.</p></li> <li>Export vendor code into trunk under the correct project name (no merge necessary, as I have no project trunk files yet).</li> <li>Create users/permissions in /svnroot/conf/passwd and /svnroot/conf/svnserve.conf.</li> <li>Make sure that svnserve is running, and on my local SVN client (TortoiseSVN), checkout the trunk for the project that I need.</li> </ol> <p>I don't need to serve this up by public URL, so I'm not configuring for Apache. The server is not in our network, but is a dedicated CentOS box we rent. Thanks for any thoughts and advice.</p> <p><strong>EDIT:</strong></p> <p>I guess I'm confused because I don't have code or a project to begin with, so I am starting fresh from the vendor's code. Do I need to create a directory structure somewhere on the server that includes my project_name w/ vendor, trunk, branches and tags subfolders, import that into my repo, and then import the code from the vendor into the vendor folder? The idea is that I can get updates from the vendor, and then merge those updates with any changes I made to my trunk.</p>
[ { "answer_id": 259628, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 4, "selected": true, "text": "svn mkdir /usr/local/svn svn mkdir file:///usr/local/svn/projects -m \"Parent dir for projects created\"\n" }, { "answer_id": 259715, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 3, "selected": false, "text": "svnadmin create /usr/local/svn projects/ project_name/ svn import svn commit svn update svn:// file://" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
259,613
<p>I'm considering migrating a project to managed code, but I've heard that the .NET runtime is huge--several times larger than my executable binary, in fact. That just seems like the tail wagging the dog to me. But I've also been told that some CLR implementations, such as Mono, are modular, and you can create a custom distribution for them that only contains the parts you actually need.</p> <p>Problem is, I'm having a surprisingly difficult time finding answers on Google to what ought to be very simple questions about this. How big are the full CLR packages on various implementations, which ones support this modular distribution ability, and how big would the runtime end up being for a standard windows-style (form-based) app that doesn't use tons of .NET bells and whistles? (Mostly what I'm interested in is the Assembly system's inherent ability to create plugins easily, and the ability to build scripting into my program through JIT compilation.)</p> <p>EDIT: I'm not interested in installer sizes or download times. I want to know the size of the actual framework, uncompressed and ready to run, as it will be on the end-users' systems.</p>
[ { "answer_id": 259652, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 1, "selected": false, "text": "ClickOnce" }, { "answer_id": 259880, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "Microsoft.NET\\Framework C:\\Windows\\assembly Microsoft Visual J# 2.0 Redistributable Package" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
259,622
<p>How do I send mail via PHP with attachment of HTML file? -> Content of HTML file (code) is in string in DB. Is there some easy way or free script to do this? I don't want to store the file localy, I need to read it out of DB and send it straightaway as attachment (not included in body).</p>
[ { "answer_id": 259690, "author": "Georg Zimmer", "author_id": 3569719, "author_profile": "https://Stackoverflow.com/users/3569719", "pm_score": 2, "selected": false, "text": "<?\ninclude('Mail.php');\ninclude('Mail/mime.php');\n$text = 'Text version of email';\n$html = '<html><body>HTML version of email</body></html>';\n$file = './files/example.zip';\n$crlf = \"rn\";\n$hdrs = array(\n 'From' => 'someone@domain.pl',\n 'To' => 'someone@domain.pl',\n 'Subject' => 'Test mime message'\n );\n$mime = new Mail_mime($crlf);\n$mime->setTXTBody($text);\n$mime->setHTMLBody($html);\n$mime->addAttachment($file,'application/octet-stream');\n$body = $mime->get();\n$hdrs = $mime->headers($hdrs);\n$mail =& Mail::factory('mail', $params);\n$mail->send('mail@domain.pl', $hdrs, $body); \n?>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21209/" ]
259,634
<p>ok so basically I am asking the question of their name I want this to be one input rather than Forename and Surname.</p> <p>Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g.</p> <pre><code>name = "Thomas Winter" print name.split() </code></pre> <p>and what would be output is just "Winter"</p>
[ { "answer_id": 259638, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "print name.split()[-1]\n" }, { "answer_id": 259639, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 0, "selected": false, "text": "rsplit([sep [,maxsplit]])\n sep maxsplit maxsplit sep None rsplit() split()" }, { "answer_id": 259809, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 3, "selected": false, "text": "name = \"Thomas Winter\"\nLastName = name.split()[1]\n" }, { "answer_id": 263331, "author": "UberJumper", "author_id": 34395, "author_profile": "https://Stackoverflow.com/users/34395", "pm_score": 2, "selected": false, "text": "import re\np = re.compile(r'^(\\s+)?(Mr(\\.)?|Mrs(\\.)?)?(?P<FIRST_NAME>.+)(\\s+)(?P<LAST_NAME>.+)$', re.IGNORECASE)\nm = p.match('Mr. Dingo Bat')\nif(m != None):\n first_name = m.group('FIRST_NAME')\n last_name = m.group('LAST_NAME')\n" }, { "answer_id": 9305240, "author": "Ryan Flores", "author_id": 1212961, "author_profile": "https://Stackoverflow.com/users/1212961", "pm_score": 2, "selected": false, "text": "def get_first_name(fullname):\n firstname = ''\n try:\n firstname = fullname.split()[0] \n except Exception as e:\n print str(e)\n return firstname\n\ndef get_last_name(fullname):\n lastname = ''\n try:\n index=0\n for part in fullname.split():\n if index > 0:\n if index > 1:\n lastname += ' ' \n lastname += part\n index += 1\n except Exception as e:\n print str(e)\n return lastname\n\ndef get_last_word(string):\n return string.split()[-1]\n\nprint get_first_name('Jim Van Loon')\nprint get_last_name('Jim Van Loon')\nprint get_last_word('Jim Van Loon')\n" }, { "answer_id": 56150253, "author": "Kurtis Pykes", "author_id": 10511518, "author_profile": "https://Stackoverflow.com/users/10511518", "pm_score": 0, "selected": false, "text": "name = \"Thomas Winter\"\nfirst, last = name.split()\nprint(\"First = {first}\".format(first=first))\n#First = Thomas\nprint(\"Last = {last}\".format(last=\" \".join(last)))\n#Last = Winter\n" }, { "answer_id": 59272196, "author": "Gaurav Meena", "author_id": 12421161, "author_profile": "https://Stackoverflow.com/users/12421161", "pm_score": 0, "selected": false, "text": "str.find() x=input(\"enter your name \")\nl=x.find(\" \")\nprint(\"your first name is\",x[:l])\nprint(\"your last name is\",x[l:])\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
259,656
<p>I'm running through an XML document, selecting all the elements, and creating links based on the ancestor which is usually two nodes up in the tree, but occasionally 3 or 4 nodes up. For the majority of the elements, using <code>&lt;xsl:value-of select="translate(../../@name,$uc,$lc)" /&gt;</code> works just fine, but for the cases where the ancestor is 3 or so nodes up, I'd like to use <code>&lt;xsl:value-of select="translate(ancestor::package/@name,$uc,$lc)" /&gt;</code>, but this doesn't work.</p> <p>I'm using xsltproc from Ruby to do my XSL transforms.</p> <p>Sample tree (yes, it has XSLT in it, no, I'm not trying to process it):</p> <pre><code>&lt;package name="blork!" xmlns="http://xml.snapin.com/XBL"&gt; &lt;xsl:template name="doSomething"&gt; &lt;tokens&gt; &lt;token name="text-from-resource" export="public" /&gt; &lt;/tokens&gt; &lt;/xsl:template&gt; &lt;/package&gt; </code></pre> <p>The XSL I'm using:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s4="http://xml.snapin.com/XBL"&gt; &lt;xsl:template match="/"&gt; &lt;xsl:if test="count(//s4:token) &gt;0"&gt; &lt;xsl:text&gt;Tokens!&lt;/xsl:text&gt; &lt;xsl:for-each select="//s4:token"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="@export='global'" /&gt; &lt;xsl:otherwise&gt; &lt;xsl:value-of select="translate(ancestor::s4:package/@name,$uc,$lc)" /&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:for-each&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><em>Edit:</em> Ah, right, forgot the namespace on the select. The parser's finding that ancestor properly for most cases, but it still can't find it when there's an xsl: node in there, and the target file has no namespace for xsl. I'd prefer not to modify the target file, because it's production code---I'm just writing an autodoc tool.</p>
[ { "answer_id": 259664, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": true, "text": "<xsl:value-of select=\"translate(ancestor::s4:package/@name,$uc,$lc)\" />\n <xsl:value-of select=\"translate(ancestor::*[local-name()='package']/@name,$uc,$lc)\" />\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26257/" ]
259,673
<p><strong>What is the best way to share Delphi source files among projects?</strong></p> <p><em>Clarification: We want to use a single source file in multiple Delphi projects. We've been using our SCM tool to put the same file into multiple folders, but this is not a super-elegant experience and we are also considering migrating to a tool that doesn't support this.</em></p> <p>As I’ve been investigating this question, I’ve considered a few different approaches, but I’d like to know what you’re doing and how you find your approach.</p> <p><strong>Important Scenarios:</strong></p> <ul> <li>Code-time <ul> <li>Adding a new sharing dependency should require explicit declaration, so that sharing is managed.</li> <li>Adding a new sharing dependency should still be relatively simple; it should not require a complicated process. <ul> <li>One file which lists all of the project’s “imported” files (from externally) would be nice.</li> </ul></li> </ul></li> <li>Compile-time <ul> <li>All projects should always build with the one current version (current as of the source sync state plus local edits). <ul> <li>(Maintaining different versions in different locations should use file branching, which is not the topic, here.)</li> </ul></li> <li>Whether each project should be able to affect the shared file’s compilation with different compiler settings (including flags) is arguable. <ul> <li>It’s arguably easier to maintain (i.e. long-term) source code that is always built consistently.</li> <li>It’s arguably easier to make maintenance fixes (i.e. short-term) if the scope of said changes can easily be restricted to one project.</li> </ul></li> </ul></li> <li>Debug-time <ul> <li>The correct version of the source should automatically open, when stepping into a routine or setting a breakpoint.</li> <li>Editing the displayed source should affect the next build. <ul> <li>We do not want to debug against a temporary copy of the source: we'd probably lose code, in the confusion.</li> </ul></li> </ul></li> </ul> <p><strong>Considerations:</strong></p> <ul> <li>Near-Term: <ul> <li>What approach will be simplest to put in place?</li> </ul></li> <li>Long-Term: <ul> <li>What approach will be simplest to use and maintain?</li> </ul></li> </ul> <p>Thanks, in advance, for your feedback!</p> <p>Mattias</p> <p><hr/> <strong>--- UPDATE ---</strong></p> <p>Thanks for your feedback, via answers, comments, and votes!</p> <p>I've started down the path of putting shared files into one "producer" project and importing a list of compiled files into each "consumer" project. The projects are being linked together with MSBuild. Once things are more nailed-down, I'll edit this question and the "Library Project" answer, to share what I've learned.</p> <p>Stay tuned! (But don't hold your breath; you'll asphyxiate within minutes! :P )</p>
[ { "answer_id": 295322, "author": "vrad", "author_id": 12891, "author_profile": "https://Stackoverflow.com/users/12891", "pm_score": 1, "selected": false, "text": "\\Main\n \\Project1\n \\Project2\n ...\n \\CommonUnits\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32841/" ]
259,676
<ol> <li><p>In a simple winform application, I call a function that endlessy create files on a button click event. I add Application.DoEvents() to the loop.</p></li> <li><p>I press the red X to close the form.</p></li> <li><p>the form closes, but files continue to be created ... </p></li> </ol> <p>I think its on the buttons thread, but shouldnt it be a background one ? trying changing Thread.CurrentThread.IsBackGround to True on the loop function does not help.</p> <p>Ideas ?</p>
[ { "answer_id": 259695, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "Application.DoEvents CancelAsync CancellationPending" }, { "answer_id": 259703, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "Thread.CurrentThread.Abort() s source code it might help (even though you say you are calling background worker" }, { "answer_id": 259710, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 1, "selected": false, "text": "{windows forms methods incl. message pump}\n **ClickHandler**\n Application.DoEvents\n {windows forms methods incl. message pump}\n **ClickHandler**\n Application.DoEvents\n {windows forms methods incl. message pump}\n etc.\n" }, { "answer_id": 259747, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "private bool _StillOpen = true;\n while (_StillOpen)\n{\n // do whatever your method does\n Application.DoEvents();\n}\n _StillOpen = false;\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195/" ]
259,709
<p>I the following styles:</p> <pre><code>a.button { background-color: orange; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } a.buttonMouseover { background-color: darkGoldenRod; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } </code></pre> <p>And the following javascript code (my first ever btw):</p> <pre><code>function backgroundChangeIn(element){ if (element.className = "a.button"){element.className = "buttonMouseover";} } function backgroundChangeOut(element){ if (element.className = "a.buttonMouseover"){element.className = "button";} } </code></pre> <p>And, the following element that should change the background on mouseover:</p> <pre><code>&lt;a class="button" href="" onmouseover="backgroundChangeIn(this)" onmouseout="backgroundChangeOut(this)"&gt;A Button&lt;/a&gt; </code></pre> <p>It is working for me so far. But I was wondering if there was a better way.</p> <p>(Sorry about all the code)</p>
[ { "answer_id": 259712, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": true, "text": "hover a.button {\n background-color: orange;\n margin: .2cm;\n padding: .2cm;\n color: black;\n font-family: sans-serif;\n text-decoration: none;\n font-weight: bold;\n border: solid #000000;\n}\n\na.button:hover {\n background-color: darkGoldenRod;\n}\n" }, { "answer_id": 259713, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 1, "selected": false, "text": "a.button, a.button:hover {\n margin: .2cm;\n padding: .2cm;\n color: black;\n font-family: sans-serif;\n text-decoration: none;\n font-weight: bold;\n border: solid #000000;\n}\n\na.button {\n background-color: orange;\n}\n\na.button:hover {\n background-color: darkGoldenRod;\n}\n <a class=\"button\" href=\"\">A Button</a>\n" }, { "answer_id": 259739, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 3, "selected": false, "text": "$(function(){\n $('.hoverable').hover(function(){\n $(this).addClass('hover');\n },\n function(){\n $(this).removeClass('hover');\n })\n})\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
259,719
<p>I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file:</p> <pre><code>$doc-&gt;addChild('myToken'); </code></pre> <p>This generates (what I know as) a self-closing or single tag:</p> <pre><code>&lt;myToken/&gt; </code></pre> <p>However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag:</p> <pre><code>&lt;myToken&gt;&lt;/myToken&gt; </code></pre> <p>The question is, how do I do this, outside of running the generated XML through a <strong>preg_replace</strong>?</p>
[ { "answer_id": 259754, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 3, "selected": true, "text": "<?php\n$sxe = new SimpleXMLElement($someData, LIBXML_NOEMPTYTAG);\n\n// some processing here\n\n$out = $sxe->asXML();\n?>\n" }, { "answer_id": 25036442, "author": "Milos Cuculovic", "author_id": 1018270, "author_profile": "https://Stackoverflow.com/users/1018270", "pm_score": 2, "selected": false, "text": "This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.\n" }, { "answer_id": 29581022, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 2, "selected": false, "text": "$tag = '<SomeTagName/>';\n\necho \"Tag: '$tag'\\n\\n\";\n\n$x = new SimpleXMLElement($tag);\necho \"Autoclosed: {$x->asXML()}\\n\";\n\n$x = new SimpleXMLElement($tag);\n$x[0] = null;\necho \"Null: {$x->asXML()}\\n\";\n\n$x = new SimpleXMLElement($tag);\n$x[0] = '';\necho \"Empty: {$x->asXML()}\\n\";\n" }, { "answer_id": 31028384, "author": "Rochdi", "author_id": 5044882, "author_profile": "https://Stackoverflow.com/users/5044882", "pm_score": 0, "selected": false, "text": "$xml_reader = new XMLReader;\n$xml_reader->open($xml_file);\n\n$data = preg_replace('/\\<(\\w+)\\s*\\/\\s*\\>/i', '<$1></$1>', $xml_reader->readOuterXML());\n" }, { "answer_id": 56356569, "author": "Petr Gürth", "author_id": 3241655, "author_profile": "https://Stackoverflow.com/users/3241655", "pm_score": 0, "selected": false, "text": "LIBXML_NOEMPTYTAG DOMDocument::save DOMDocument::saveXML $dom = dom_import_simplexml(SimpleXMLElement)->ownerDocument;\n$dom->formatOutput = true;\n$dom->save($save_path, LIBXML_NOEMPTYTAG);\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33739/" ]
259,726
<p>I am using XmlSerializer to write and read an object to xml in C#. I currently use the attributes <code>XmlElement</code> and <code>XmlIgnore</code> to manipulate the serialization of the object.</p> <p>If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine. How do I indicate (preferably via Attributes) that a certain field is "required"?</p> <p>Here is a sample method of what I am using currently:</p> <pre><code>[XmlElement(ElementName="numberOfWidgets")] public int NumberThatIsRequired { set ...; get ...; } </code></pre> <p>My ideal solution would be to add something like an <code>XmlRequired</code> attribute. </p> <p>Also, is there a good reference for what Attributes are available to manipulate the behavior of XmlSerializer?</p>
[ { "answer_id": 259969, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 4, "selected": false, "text": "static T Deserialize<T>(string xml, XmlSchemaSet schemas)\n{\n //List<XmlSchemaException> exceptions = new List<XmlSchemaException>();\n ValidationEventHandler validationHandler = (s, e) =>\n {\n //you could alternatively catch all the exceptions\n //exceptions.Add(e.Exception);\n throw e.Exception;\n };\n\n XmlReaderSettings settings = new XmlReaderSettings();\n settings.Schemas.Add(schemas);\n settings.ValidationType = ValidationType.Schema;\n settings.ValidationEventHandler += validationHandler;\n\n XmlSerializer serializer = new XmlSerializer(typeof(T));\n using (StringReader sr = new StringReader(xml))\n using (XmlReader books = XmlReader.Create(sr, settings))\n return (T)serializer.Deserialize(books);\n}\n" }, { "answer_id": 260955, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "XmlSerializer [DefaultValue] ShouldSerialize{Foo} {Foo}Specified {Foo}Specified IXmlSerializable" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ]
259,751
<p>Need a function like: </p> <pre><code>function isGoogleURL(url) { ... } </code></pre> <p>that returns true iff URL belongs to Google. No false positives; no false negatives.</p> <p>Luckily there's <a href="http://www.google.com/supported_domains" rel="nofollow noreferrer">this</a> as a reference:</p> <blockquote> <p>.google.com .google.ad .google.ae .google.com.af .google.com.ag .google.com.ai .google.am .google.it.ao .google.com.ar .google.as .google.at .google.com.au .google.az .google.ba .google.com.bd .google.be .google.bg .google.com.bh .google.bi .google.com.bn .google.com.bo .google.com.br .google.bs .google.co.bw .google.com.by .google.com.bz .google.ca .google.cd .google.cg .google.ch .google.ci .google.co.ck .google.cl .google.cn .google.com.co .google.co.cr .google.com.cu .google.cz .google.de .google.dj .google.dk .google.dm .google.com.do .google.dz .google.com.ec .google.ee .google.com.eg .google.es .google.com.et .google.fi .google.com.fj .google.fm .google.fr .google.ge .google.gg .google.com.gh .google.com.gi .google.gl .google.gm .google.gp .google.gr .google.com.gt .google.gy .google.com.hk .google.hn .google.hr .google.ht .google.hu .google.co.id .google.ie .google.co.il .google.im .google.co.in .google.is .google.it .google.je .google.com.jm .google.jo .google.co.jp .google.co.ke .google.com.kh .google.ki .google.kg .google.co.kr .google.kz .google.la .google.li .google.lk .google.co.ls .google.lt .google.lu .google.lv .google.com.ly .google.co.ma .google.md .google.mn .google.ms .google.com.mt .google.mu .google.mv .google.mw .google.com.mx .google.com.my .google.co.mz .google.com.na .google.com.nf .google.com.ng .google.com.ni .google.nl .google.no .google.com.np .google.nr .google.nu .google.co.nz .google.com.om .google.com.pa .google.com.pe .google.com.ph .google.com.pk .google.pl .google.pn .google.com.pr .google.pt .google.com.py .google.com.qa .google.ro .google.ru .google.rw .google.com.sa .google.com.sb .google.sc .google.se .google.com.sg .google.sh .google.si .google.sk .google.sn .google.sm .google.st .google.com.sv .google.co.th .google.com.tj .google.tk .google.tl .google.tm .google.to .google.com.tr .google.tt .google.com.tw .google.co.tz .google.com.ua .google.co.ug .google.co.uk .google.com.uy .google.co.uz .google.com.vc .google.co.ve .google.vg .google.co.vi .google.com.vn .google.vu .google.ws .google.rs .google.co.za .google.co.zm .google.co.zw .google.cat</p> </blockquote> <p>Any ideas how to do this elegantly?</p> <p><strong>Some Clarifications:</strong></p> <ul> <li>I need this for a greasemonkey script I wrote that currently only works for google.com (and should work for all other TLDs as well). <a href="http://userscripts.org/scripts/show/6415" rel="nofollow noreferrer">Here</a> is the script (it modifies Google Reader to work on wide screens better).</li> <li>It should work on URLs that belong to the above domains (not blogger.com, etc.).</li> </ul>
[ { "answer_id": 259788, "author": "luiscubal", "author_id": 32775, "author_profile": "https://Stackoverflow.com/users/32775", "pm_score": 0, "selected": false, "text": "<script>\nvar elem = document.getElementById(\"a\");\nvar regex = new RegExp(\"(http://)?(www\\\\.)?google\\\\.com\");\n\nelem.innerHTML = regex.test(elem.innerHTML);\n</script>\n" }, { "answer_id": 259830, "author": "Berzemus", "author_id": 2452, "author_profile": "https://Stackoverflow.com/users/2452", "pm_score": 1, "selected": false, "text": "\"(http://)?([\\w]+)?\\.google\\.([\\w]{2,3})\"\n" }, { "answer_id": 259893, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 0, "selected": false, "text": "^https?://[-A-Za-z0-9\\.]+(\\.google\\.com|\\.google\\.ad|\\.google\\.ae|\\.google\\.com\\.af|\\.google\\.com\\.ag|\\.google\\.com\\.ai|\\.google\\.am|\\.google\\.it\\.ao|\\.google\\.com\\.ar|\\.google\\.as|\\.google\\.at|\\.google\\.com\\.au|\\.google\\.az|\\.google\\.ba|\\.google\\.com\\.bd|\\.google\\.be|\\.google\\.bg|\\.google\\.com\\.bh|\\.google\\.bi|\\.google\\.com\\.bn|\\.google\\.com\\.bo|\\.google\\.com\\.br|\\.google\\.bs|\\.google\\.co\\.bw|\\.google\\.com\\.by|\\.google\\.com\\.bz|\\.google\\.ca|\\.google\\.cd|\\.google\\.cg|\\.google\\.ch|\\.google\\.ci|\\.google\\.co\\.ck|\\.google\\.cl|\\.google\\.cn|\\.google\\.com\\.co|\\.google\\.co\\.cr|\\.google\\.com\\.cu|\\.google\\.cz|\\.google\\.de|\\.google\\.dj|\\.google\\.dk|\\.google\\.dm|\\.google\\.com\\.do|\\.google\\.dz|\\.google\\.com\\.ec|\\.google\\.ee|\\.google\\.com\\.eg|\\.google\\.es|\\.google\\.com\\.et|\\.google\\.fi|\\.google\\.com\\.fj|\\.google\\.fm|\\.google\\.fr|\\.google\\.ge|\\.google\\.gg|\\.google\\.com\\.gh|\\.google\\.com\\.gi|\\.google\\.gl|\\.google\\.gm|\\.google\\.gp|\\.google\\.gr|\\.google\\.com\\.gt|\\.google\\.gy|\\.google\\.com\\.hk|\\.google\\.hn|\\.google\\.hr|\\.google\\.ht|\\.google\\.hu|\\.google\\.co\\.id|\\.google\\.ie|\\.google\\.co\\.il|\\.google\\.im|\\.google\\.co\\.in|\\.google\\.is|\\.google\\.it|\\.google\\.je|\\.google\\.com\\.jm|\\.google\\.jo|\\.google\\.co\\.jp|\\.google\\.co\\.ke|\\.google\\.com\\.kh|\\.google\\.ki|\\.google\\.kg|\\.google\\.co\\.kr|\\.google\\.kz|\\.google\\.la|\\.google\\.li|\\.google\\.lk|\\.google\\.co\\.ls|\\.google\\.lt|\\.google\\.lu|\\.google\\.lv|\\.google\\.com\\.ly|\\.google\\.co\\.ma|\\.google\\.md|\\.google\\.mn|\\.google\\.ms|\\.google\\.com\\.mt|\\.google\\.mu|\\.google\\.mv|\\.google\\.mw|\\.google\\.com\\.mx|\\.google\\.com\\.my|\\.google\\.co\\.mz|\\.google\\.com\\.na|\\.google\\.com\\.nf|\\.google\\.com\\.ng|\\.google\\.com\\.ni|\\.google\\.nl|\\.google\\.no|\\.google\\.com\\.np|\\.google\\.nr|\\.google\\.nu|\\.google\\.co\\.nz|\\.google\\.com\\.om|\\.google\\.com\\.pa|\\.google\\.com\\.pe|\\.google\\.com\\.ph|\\.google\\.com\\.pk|\\.google\\.pl|\\.google\\.pn|\\.google\\.com\\.pr|\\.google\\.pt|\\.google\\.com\\.py|\\.google\\.com\\.qa|\\.google\\.ro|\\.google\\.ru|\\.google\\.rw|\\.google\\.com\\.sa|\\.google\\.com\\.sb|\\.google\\.sc|\\.google\\.se|\\.google\\.com\\.sg|\\.google\\.sh|\\.google\\.si|\\.google\\.sk|\\.google\\.sn|\\.google\\.sm|\\.google\\.st|\\.google\\.com\\.sv|\\.google\\.co\\.th|\\.google\\.com\\.tj|\\.google\\.tk|\\.google\\.tl|\\.google\\.tm|\\.google\\.to|\\.google\\.com\\.tr|\\.google\\.tt|\\.google\\.com\\.tw|\\.google\\.co\\.tz|\\.google\\.com\\.ua|\\.google\\.co\\.ug|\\.google\\.co\\.uk|\\.google\\.com\\.uy|\\.google\\.co\\.uz|\\.google\\.com\\.vc|\\.google\\.co\\.ve|\\.google\\.vg|\\.google\\.co\\.vi|\\.google\\.com\\.vn|\\.google\\.vu|\\.google\\.ws|\\.google\\.rs|\\.google\\.co\\.za|\\.google\\.co\\.zm|\\.google\\.co\\.zw|\\.google\\.cat)\n" }, { "answer_id": 259918, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 1, "selected": false, "text": "var GOOGLE_DOMAINS = ([\n '.google.com',\n '.google.ad',\n '.google.ae',\n '.google.com.af',\n '.google.com.ag',\n '.google.com.ai',\n '.google.am',\n '.google.it.ao',\n '.google.com.ar',\n '.google.as',\n '.google.at',\n '.google.com.au',\n '.google.az',\n '.google.ba',\n '.google.com.bd'\n]).join('\\n');\n\nfunction isGoogleUrl(url) {\n var url = 'http://www.google.ba/the/page.html';\n\n // get the domain from the url\n var domain = /\\.google\\.[^\\/\\\\]+/i.exec(url) + '';\n if(!domain) return false;\n\n // create a regex to check to see if the domain is supported\n var re = new RegExp('^' + domain.replace(/\\./g, '\\\\.') + '$', 'mi');\n return re.test(GOOGLE_DOMAINS);\n}\n GOOGLE_DOMAINS" }, { "answer_id": 294197, "author": "wimh", "author_id": 33499, "author_profile": "https://Stackoverflow.com/users/33499", "pm_score": 4, "selected": true, "text": "var GOOGLE_DOMAINS = ([\n '.google.com',\n '.google.ad',\n '.google.ae',\n '.google.com.af',\n '.google.com.ag',\n '.google.com.ai',\n '.google.am',\n '.google.it.ao',\n '.google.com.ar',\n '.google.as',\n '.google.at',\n '.google.com.au',\n '.google.az',\n '.google.ba',\n '.google.com.bd'\n]).join('\\n');\n\nfunction isGoogleUrl(url) {\n // get the 2nd level domain from the url\n var domain = /^https?:\\/\\/[^\\///]*(google\\.[^\\/\\\\]+)\\//i.exec(url);\n if(!domain) return false;\n\n domain = '.'+domain[1];\n // create a regex to check to see if the domain is supported\n var re = new RegExp('^' + domain.replace(/\\./g, '\\\\.') + '$', 'mi');\n return re.test(GOOGLE_DOMAINS);\n}\n\nalert(isGoogleUrl('http://www.google.ba/the/page.html')); // true\nalert(isGoogleUrl('http://some_mal_site.com/http://www.google.ba/')); // false\nalert(isGoogleUrl('https://google.com.au/')); // true\nalert(isGoogleUrl('http://www.google.com.some_mal_site.com/')); // false\nalert(isGoogleUrl('http://yahoo.com/')); // false\n" }, { "answer_id": 294269, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 2, "selected": false, "text": "/^(\\w+\\.)*google\\.((com\\.|co\\.|it\\.)?([a-z]{2})|com)$/i\n function isGoogleUrl(url) {\n url = url.replace(/^https?:\\/\\//i, ''); // Strip \"http://\" from the beginning\n url = url.replace(/\\/.*/, ''); // Strip off the path\n return /^(\\w+\\.)*google\\.((com\\.|co\\.|it\\.)?([a-z]{2})|com)$/i.test(url);\n}\n window.location.hostname function isGoogleUrl() {\n return /^(\\w+\\.)*google\\.((com\\.|co\\.|it\\.)?([a-z]{2})|com)$/i.test(window.location.hostname);\n}\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11208/" ]
259,753
<p>I can't get the inner div (with Hello World) to fit inside the "box" div in this code example (also at <a href="http://www.toad-software.com/test.html" rel="nofollow noreferrer">http://www.toad-software.com/test.html</a>).</p> <p>Despite the body being set to 100%, the inner div will not be contained! This is a test case for a larger project in which a variable-width table exceeds the boundaries of its container. The table would be in the inner div and the container would the "box."</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; /*html { width: 100%; height: 100%; position: relative; background: #c0c0c0; } body { position: absolute; width: 100%; height: 100%; background: #f9f9f9; }*/ body, html { margin: 0; padding: 0; } body { width: 100%; } div.box { padding: 10px; background: #ff33ff; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="box"&gt; &lt;div style="width: 1500px; height: 900px; background: #f12;"&gt;Hello World&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 259761, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 4, "selected": false, "text": "overflow:hidden; <div>" }, { "answer_id": 260792, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 4, "selected": true, "text": "div.box { width: 100px; overflow: auto; }\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335036/" ]
259,784
<p>Compiling a program on Linux that calls POSIX timer functions (eg: timer_create, timer_settime) returns errors such as:</p> <pre> In function `foo': timer.c:(.text+0xbb): undefined reference to `timer_create' timer.c:(.text+0x187): undefined reference to `timer_settime' collect2: ld returned 1 exit status </pre> <p>Which library do I need to link?</p>
[ { "answer_id": 259789, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "-lrt" }, { "answer_id": 552654, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "-lrt" }, { "answer_id": 673047, "author": "dragonfly", "author_id": 81259, "author_profile": "https://Stackoverflow.com/users/81259", "pm_score": 2, "selected": false, "text": "gcc -lrt\n" }, { "answer_id": 13542061, "author": "steve-o", "author_id": 1459666, "author_profile": "https://Stackoverflow.com/users/1459666", "pm_score": 2, "selected": false, "text": "/lib/i386-linux-gnu/librt.so.1 Project->Build Options->Linker Settings->Link Libraries->Add" }, { "answer_id": 37349343, "author": "bedio", "author_id": 6361634, "author_profile": "https://Stackoverflow.com/users/6361634", "pm_score": 3, "selected": false, "text": "gcc -o mytemer mytimer.c -lrt gcc -lrt mytimer.c -o mytimer" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
259,798
<p>I've got a (SQL Server 2005) database where I'd like to create views on-the-fly. In my code, I'm building a CREATE VIEW statement, but the only way I can get it to work is by building the entire query string and running it bare. I'd like to use parameters, but this:</p> <pre><code>SqlCommand cmd = new SqlCommand("CREATE VIEW @name AS SELECT @body"); cmd.Parameters.AddWithValue("@name", "foo"); cmd.Parameters.AddWithValue("@body", "* from bar"); </code></pre> <p>tells me there's an error "near the keyword VIEW" (presumably the "@name") -- needless to say <code>"CREATE VIEW foo AS SELECT * FROM bar"</code> works like a champ.</p> <p>Is this just not possible? If not, is there a better way to clean up the input before running the CREATE statement? In some cases, the query body could have user input and I'd just feel safer if there was some way that I could say "treat this as the body of a single select statement". Maybe what I'm asking for is just too weird?</p> <p><hr/> FOLLOWUP 04 Nov: OK, yes, what I want is sort of like SQL injection when you get down to it, but I would like to at least minimize (if not totally remove) the option of running this command and dropping a table or something. Granted, the user this is running as doesn't have permissions to drop any tables in the first place, but I think you get the idea. I'd love to have a way of saying, in effect, <code>"This statement will not alter any existing data in any way{ ... }"</code>.</p> <p>The way it's coded right now is to do string concatenation like in <strong>friol</strong>'s answer, but that does no sanitization at all. I'd feel better if I could at least scrub it for suspect characters, like ; or -- or what have you. I was hoping there might be a library function to do the scrub for me, or something along those lines.</p>
[ { "answer_id": 259808, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 2, "selected": true, "text": "viewname=\"foo\";\nviewwhere=\"* from bar\";\n\nSqlCommand cmd = new SqlCommand(\"CREATE VIEW \"+viewname+\" AS SELECT \"+viewwhere);\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ]
259,800
<p>What exception should I throw if I encounter an illegal state - for instance, an initialization method that should only be called once being called a second time? I don't really see any built-in exception that makes sense. This seems like something that should be in the framework - am I not poking in the right spot?</p>
[ { "answer_id": 51556216, "author": "Maarten Bodewes", "author_id": 589259, "author_profile": "https://Stackoverflow.com/users/589259", "pm_score": 1, "selected": false, "text": "SystemException SystemException InvalidOperationException ToString" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
259,803
<p>Let's say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure):</p> <pre><code>CREATE PROCEDURE incrementCounter AS DECLARE @current int SET @current = (select CounterColumn from MyTable) + 1 UPDATE MyTable SET CounterColumn = current GO </code></pre> <p>We're assuming I have a table called 'myTable' that contains one row, with the 'CounterColumn' containing our current count.</p> <p>Can this stored procedure be executed multiple times, at the same time? </p> <p>i.e. is this possible:</p> <p>I call 'incrementCounter' twice. Call A gets to the point where it sets the 'current' variable (let's say it is 5). Call B gets to the point where it sets the 'current' variable (which would also be 5). Call A finishes executing, then Call B finishes. In the end, the table should contain the value of 6, but instead contains 5 due to the overlap of execution</p>
[ { "answer_id": 259931, "author": "Dave Cluderay", "author_id": 30933, "author_profile": "https://Stackoverflow.com/users/30933", "pm_score": 4, "selected": false, "text": "BEGIN TRANSACTION END TRANSACTION SERIALIZABLE READ COMMITTED SET TRANSACTION ISOLATION LEVEL SERIALIZABLE\n" }, { "answer_id": 2090940, "author": "SqlRyan", "author_id": 8114, "author_profile": "https://Stackoverflow.com/users/8114", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE incrementCounter AS\n\nUPDATE\n MyTable\nSET\n CounterColumn = CounterColumn + 1\n\nGO\n" }, { "answer_id": 18809072, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 1, "selected": false, "text": "CREATE PROCEDURE incrementCounter\nAS\n\nDECLARE @current int\n\nUPDATE MyTable\nSET\n @current = CounterColumn = CounterColumn + 1\n\nReturn @current\n" }, { "answer_id": 28392693, "author": "sqlfool", "author_id": 4542710, "author_profile": "https://Stackoverflow.com/users/4542710", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE ..\nBEGIN TRANSACTION\nUPDATE mylock SET ref = ref + 1\n...\n UPDATE\n MyTable\nSET\n CounterColumn = current \nWHERE CounterColumn = current - 1\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30006/" ]
259,819
<p>I want to create a view that consists solely of a <code>UITextView</code>. When the view is first shown, by default, I'd like the keyboard to be visible and ready for text entry. This way, the user does not have to touch the <code>UITextView</code> first in order to begin editing.</p> <p>Is this possible? I see the class has a notification called <code>UITextViewTextDidBeginEditingNotification</code> but I'm not sure how to send that, or if that is even the right approach. </p>
[ { "answer_id": 259842, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 7, "selected": true, "text": "- (void)viewWillAppear:(BOOL)animated {\n [super viewWillAppear:animated];\n [textField becomeFirstResponder];\n}\n" }, { "answer_id": 37086832, "author": "Suragch", "author_id": 3681880, "author_profile": "https://Stackoverflow.com/users/3681880", "pm_score": 4, "selected": false, "text": "override func viewDidLoad() {\n super.viewDidLoad()\n \n // show keyboard\n textView.becomeFirstResponder()\n}\n UITextView UITextField textView.resignFirstResponder()" }, { "answer_id": 39336732, "author": "Usman", "author_id": 184759, "author_profile": "https://Stackoverflow.com/users/184759", "pm_score": 3, "selected": false, "text": "override func viewDidAppear(animated: Bool) {\n super.viewDidAppear(animated)\n\n // Show keyboard by default\n billField.becomeFirstResponder()\n}\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543/" ]
259,836
<p>What is the best way to convert an array of bytes declared as TBytes to a unicode string in Delphi 2009? In my particular case, the TBytes array has UTF-16 encoded data already (2 bytes for each char).</p> <p>Since TBytes doesn't store a null terminator, the following will only work if the array happens to have #0 in the memory adjacent to it. </p> <pre><code>MyString := string( myBytes ); </code></pre> <p>If not, the string result will have random data at the end (it could also probably cause a read violation depending on how long it took to encounter a #0 in memory).</p> <p>If I use the ToBytes function, it returns 't'#0'e'#0's'#0't'#0, which is not what I want.</p>
[ { "answer_id": 259973, "author": "Jeremy Mullin", "author_id": 7893, "author_profile": "https://Stackoverflow.com/users/7893", "pm_score": 5, "selected": true, "text": "TEncoding.Unicode.GetString( MyByteArray );\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7893/" ]
259,841
<p>The company I work for writes a lot smallish Perl and Bash scripts to massage data into something usable for our software. These scripts, like any code, can change. I provided them CVS because of the file versioning rather than repository versioning. Anyway, I am thinking out a deploy tool to get the scripts from development to production. The production server will have it's own simple versioning system in that if one of the scripts' md5 sum does not match the one in a database it will not run the script and email the appropriate parties. </p> <p>I want to force the programmers to deploy the most current CVS version of the script. If it is not the most current it should die with a message telling them they have to check in their version first. I realize there might be cases where you need to deploy an old file. Those would be exceptions and could be handled as such.</p> <p>What's the best to do this? Is it just as simple as doing a 'cvs diff' ? </p>
[ { "answer_id": 259899, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 2, "selected": true, "text": "make dist\n cvs up -An \n grep -c ^[MCAR] \n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28714/" ]
259,850
<p>I am performing two validations on the client side on the samve event. I have defined my validations as shown below</p> <pre><code>btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();" </code></pre> <p>Pseudo code for </p> <pre><code>prepareSave(): { if (bPendingchanges) { return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first') } else {return true} } </code></pre> <p>Pseudo code for </p> <pre><code>prepareSearch(): { if (bNoSearchText) { alert('Please specify search criteria before proceeding') return false; } else {return true;} } </code></pre> <p>When <code>bPendingchanges=false</code>, I never get the second validation running. Anyone who can quickly spot what I have overlooked here? Please?</p>
[ { "answer_id": 259869, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": true, "text": "return javascript:return prepareSave() btnSearch.Attributes[\"OnClick\"] = javascript: return prepareSave() && prepareSearch();\n" }, { "answer_id": 259871, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "btnSearch.Attributes[\"OnClick\"] = \"javascript:return prepareSave() && prepareSearch();\"\n" }, { "answer_id": 259875, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "\"javascript:return prepareSave(); return prepareSearch();\" return prepareSearch(); \"return prepareSave(); \"return (prepareSave() && prepareSearch());\"" }, { "answer_id": 259878, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 2, "selected": false, "text": "return return prepareSave(); return prepareSearch();\n// ^^^^^^^^^^^^^^^^^^^^^^^ e.g. this part\n return (prepareSave() && prepareSearch());" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13370/" ]
259,853
<p>As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared:</p> <pre><code>class Base { virtual Base* clone() const = 0; }; class Derived : public Base { virtual Derived* clone() const }; </code></pre> <p>The compiler detects that clone() returns an pointer to the type of the object, and allows Derived to override it to return a pointer to derived.</p> <p>It would desirable to have clone() return a smart pointer that implies transfer of ownership semantics, like the following:</p> <pre><code>class Base { virtual std::auto_ptr&lt;Base&gt; clone() const = 0; }; class Derived : public Base { virtual std::auto_ptr&lt;Derived&gt; clone() const; }; </code></pre> <p>Unfortunately, the relaxation of the conventions does not apply to templated smart pointers, and the compiler will not allow the override.</p> <p>So, it seems I am left with two options:</p> <ol> <li>Have clone() return a "dumb" pointer, and document that clients are responsible for disposing of it.</li> <li>Have clone() return a smart base pointer, and have clients use dynamic_cast to save them to a Derived pointer if they need it.</li> </ol> <p>Is one of these approaches preferred? Or is there a way for me to eat my transfer of ownership semantics and have my strong type safety too?</p>
[ { "answer_id": 259946, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": true, "text": "clone clone" }, { "answer_id": 260054, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 4, "selected": false, "text": "template <typename T>\nstd::auto_ptr<T> clone(T const* t)\n{\n return t->clone();\n}\n" }, { "answer_id": 260063, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 1, "selected": false, "text": "boost::intrusive_ptr shared_ptr auto/unique_ptr" }, { "answer_id": 260231, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 2, "selected": false, "text": "Tr1::shared_ptr<> shared_ptr<Base> shared_ptr<Derived> tr1::static_pointer_cast<Derived> tr1::dynamic_pointer_cast<Derived> template <typename R, typename T>\ninline std::tr1::shared_ptr<R> polymorphic_pointer_downcast(T &p)\n{\n assert( std::tr1::dynamic_pointer_cast<R>(p) );\n return std::tr1::static_pointer_cast<R>(p);\n}\n" }, { "answer_id": 261278, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 5, "selected": false, "text": "class Base {\n public:\n std::auto_ptr<Base> clone () { return doClone(); }\n private:\n virtual Base* doClone() { return new (*this); }\n};\nclass Derived : public Base {\n public:\n std::auto_ptr<Derived> clone () { return doClone(); }\n private:\n virtual Derived* doClone() { return new (*this); }\n};\n" }, { "answer_id": 38709290, "author": "Daniel", "author_id": 2970186, "author_profile": "https://Stackoverflow.com/users/2970186", "pm_score": 1, "selected": false, "text": "#include <memory>\n\nclass Base\n{\npublic:\n std::unique_ptr<Base> clone() const\n {\n return do_clone();\n }\nprivate:\n virtual std::unique_ptr<Base> do_clone() const\n {\n return std::make_unique<Base>(*this);\n }\n};\n\nclass Derived : public Base\n{\nprivate:\n virtual std::unique_ptr<Base> do_clone() const override\n {\n return std::make_unique<Derived>(*this);\n }\n}\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1674/" ]
259,883
<p>I'd like to strip out occurrences of a specific tag, leaving the inner XML intact. I'd like to do this with one pass (rather than searching, replacing, and starting from scratch again). For instance, from the source:</p> <pre><code>&lt;element&gt; &lt;RemovalTarget Attribute="Something"&gt; Content Here &lt;/RemovalTarget&gt; &lt;/element&gt; &lt;element&gt; More Here &lt;/element&gt; </code></pre> <p>I'd like the result to be:</p> <pre><code>&lt;element&gt; Content Here &lt;/element&gt; &lt;element&gt; More Here &lt;/element&gt; </code></pre> <p>I've tried something like this (forgive me, I'm new to Linq):</p> <pre><code>var elements = from element in doc.Descendants() where element.Name.LocalName == "RemovalTarget" select element; foreach (var element in elements) { element.AddAfterSelf(element.Value); element.Remove(); } </code></pre> <p>but on the second time through the loop I get a null reference, presumably because the collection is invalidated by changing it. What is an efficient way to make remove these tags on a potentially large document?</p>
[ { "answer_id": 259987, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": true, "text": "var elements = doc.Descendants(\"RemovalTarget\").ToList().Reverse();\n/* reverse on the IList<T> may be faster than Reverse on the IEnumerable<T>,\n * needs benchmarking, but can't be any slower\n */\n\nforeach (var element in elements) {\n element.ReplaceWith(element.Nodes());\n}\n" }, { "answer_id": 260216, "author": "Philipp Schmid", "author_id": 33272, "author_profile": "https://Stackoverflow.com/users/33272", "pm_score": 0, "selected": false, "text": " static void Main(string[] args)\n {\n string content = File.ReadAllText(args[0]);\n\n Regex openTag = new Regex(\"<([/]?)RemovalTarget([^>]*)>\", RegexOptions.Multiline);\n\n string cleanContent = openTag.Replace(content, string.Empty);\n File.WriteAllText(args[1], cleanContent);\n }\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807/" ]
259,884
<p>I have a very standard <code>Gridview</code>, with Edit and Delete buttons auto-generated. It is bound to a <code>tableadapter</code> which is linked to my <code>RelationshipTypes</code> table.</p> <pre><code>dbo.RelationshipTypes: ID, Name, OriginConfigTypeID, DestinationConfigTypeID </code></pre> <p>I wish to use a label that will pull the name from the <code>ConfigTypes</code> table, using the <code>OriginConfigTypeID</code> and <code>DestinationTypeID</code> as the link.</p> <pre><code>dbo.ConfigTypes: ID, Name </code></pre> <p>My problem is, I can't automatically generate Edit and Delete buttons using an <code>Inner Join</code> in my dataset. Or can I?</p> <p>Here is my code:</p> <pre><code>&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" CssClass="TableList" DataKeyNames="ID" DataSourceID="dsRelationShipTypes1"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" Visible=False/&gt; &lt;asp:TemplateField HeaderText="Origin" SortExpression="OriginCIType_ID"&gt; &lt;EditItemTemplate&gt; &amp;nbsp;&lt;asp:DropDownList Enabled=true ID="DropDownList2" runat="server" DataSourceID="dsCIType1" DataTextField="Name" DataValueField="ID" SelectedValue='&lt;%# Bind("OriginCIType_ID") %&gt;'&gt; &lt;/asp:DropDownList&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &amp;nbsp; &lt;asp:Label ID="Label2" runat="server" Text='&lt;%# Bind("OriginCIType_ID") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Name" SortExpression="Name"&gt; &lt;EditItemTemplate&gt; &lt;asp:TextBox ID="TextBox3" runat="server" Text='&lt;%# Bind("Name") %&gt;'&gt;&lt;/asp:TextBox&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label3" runat="server" Text='&lt;%# Bind("Name") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Destination" SortExpression="DestinationCIType_ID"&gt; &lt;EditItemTemplate&gt; &lt;asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="dsCIType1" DataTextField="Name" DataValueField="ID" SelectedValue='&lt;%# Bind("DestinationCIType_ID") %&gt;'&gt; &lt;/asp:DropDownList&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label1" runat="server" Text='&lt;%# Bind("DestinationCIType_ID") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>So I did try to create my own edit and delete buttons, but kept receiving the error </p> <blockquote> <p>"cannot find update method"</p> </blockquote> <p>or something similar. Do I have to manually code the delete and update methods in my code-behind?</p>
[ { "answer_id": 259987, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": true, "text": "var elements = doc.Descendants(\"RemovalTarget\").ToList().Reverse();\n/* reverse on the IList<T> may be faster than Reverse on the IEnumerable<T>,\n * needs benchmarking, but can't be any slower\n */\n\nforeach (var element in elements) {\n element.ReplaceWith(element.Nodes());\n}\n" }, { "answer_id": 260216, "author": "Philipp Schmid", "author_id": 33272, "author_profile": "https://Stackoverflow.com/users/33272", "pm_score": 0, "selected": false, "text": " static void Main(string[] args)\n {\n string content = File.ReadAllText(args[0]);\n\n Regex openTag = new Regex(\"<([/]?)RemovalTarget([^>]*)>\", RegexOptions.Multiline);\n\n string cleanContent = openTag.Replace(content, string.Empty);\n File.WriteAllText(args[1], cleanContent);\n }\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13959/" ]
259,886
<p>I want to assign a resource I already have a second name, similar to using the BasedOn property of Styles. Specifically I have a brush that I use for a group of elements called ForegroundColor and I would like to use it in a control template (a ComboBox) calling it MouseOverBackgroundBrush. I would like to do something like this:</p> <pre><code>&lt;ResourceCopy x:key="MouseOverBackgroundBrush" Value="{StaticResource ForegroundColor}" /&gt; </code></pre> <p>Is there a way to do this or is there a better way to go about this in Xaml?</p>
[ { "answer_id": 259976, "author": "Amanda Mitchell", "author_id": 26628, "author_profile": "https://Stackoverflow.com/users/26628", "pm_score": 3, "selected": true, "text": "Resources[\"MouseOverBackgroundBrush\"] = Resources[\"ForegroundColor\"];\n" }, { "answer_id": 259992, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 1, "selected": false, "text": "<Color x:Key=\"firstColor\">#FFD97A7A</Color>\n<Color x:Key=\"secondColor\">#FFF4BFBF</Color>\n<LinearGradientBrush x:Key=\"firstGradientBrush\" EndPoint=\"0.5,1\" StartPoint=\"0.5,0\">\n <GradientStop Color=\"{DynamicResource firstColor}\" Offset=\"0\"/>\n <GradientStop Color=\"{DynamicResource secondColor}\" Offset=\"1\"/>\n</LinearGradientBrush>\n<LinearGradientBrush x:Key=\"secondGradientBrush\" EndPoint=\"0.5,1\" StartPoint=\"0.5,0\">\n <GradientStop Color=\"{DynamicResource firstColor}\" Offset=\"0\"/>\n <GradientStop Color=\"{DynamicResource secondColor}\" Offset=\"1\"/>\n</LinearGradientBrush>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21186/" ]
259,887
<p>In writing the code that throws the exception I asked about <a href="https://stackoverflow.com/questions/259800/is-there-a-built-in-net-exception-that-indicates-an-illegal-object-state">here</a>, I came to the end of my message, and paused at the punctuation. I realized that nearly every exception message I've ever thrown probably has a ! somewhere.</p> <pre><code>throw new InvalidOperationException("I'm not configured correctly!"); throw new ArgumentNullException("You passed a null!"); throw new StupidUserException("You can't divide by 0! What the hell were you THINKING??? DUMMY!!!!!"); </code></pre> <p>What tone do you take when writing exception messages? When going through logs, do you find any certain style of message actually helps more than another?</p>
[ { "answer_id": 259917, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 2, "selected": false, "text": "throw new MagicalException(getText(\"magical.exception.text\"));\n" }, { "answer_id": 259919, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "throw new IndexOutOfBoundsException(\"offset < 0: \" + off);\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
259,889
<p>If I have a button like the one in this image :</p> <p><strong><a href="http://www.freeimagehosting.net/image.php?4cd775814c.png" rel="nofollow noreferrer">http://www.freeimagehosting.net/image.php?4cd775814c.png</a></strong></p> <p>how could I make the text display itself vertically ? As in </p> <pre> j B u t t o n 1 </pre> <p>I would like to know how to do the same thing for JLabel . I'm sure there has to be a better way than to create as many labels as there are characters in the string . Right ?</p> <p><strong>EDIT:</strong> how can I insert an image into my post ? The button for the image shows the image in the preview section , but when I actually post the data , I only get some text back , like the tags are getting messed up .</p>
[ { "answer_id": 259928, "author": "asalamon74", "author_id": 21348, "author_profile": "https://Stackoverflow.com/users/21348", "pm_score": 4, "selected": true, "text": "button = new JButton(\"<html>J<br>b<br>u<br>t<br>t<br>o<br>n<br>1</html>\");\n" }, { "answer_id": 260099, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 3, "selected": false, "text": "label.setUI(new VerticalLabelUI(true));" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
259,890
<p>How do you draw the following dynamic <strong>3D</strong> array with OpenGL <strong>glDrawPixels()</strong>? You can find the documentation here: <a href="http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html" rel="nofollow noreferrer">http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html</a></p> <pre><code>float ***array3d; void InitScreenArray() { int i, j; int screenX = scene.camera.vres; int screenY = scene.camera.hres; array3d = (float ***)malloc(sizeof(float **) * screenX); for (i = 0 ; i &lt; screenX; i++) { array3d[i] = (float **)malloc(sizeof(float *) * screenY); for (j = 0; j &lt; screenY; j++) array3d[i][j] = (float *)malloc(sizeof(float) * /*Z_SIZE*/ 3); } } </code></pre> <p>I can use only the following header files:</p> <pre><code>#include &lt;math.h&gt; #include &lt;stdlib.h&gt; #include &lt;windows.h&gt; #include &lt;GL/gl.h&gt; #include &lt;GL/glu.h&gt; #include &lt;GL/glut.h&gt; </code></pre>
[ { "answer_id": 261776, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": true, "text": "malloc() glDrawPixels() malloc() float *array3d;\narray3d = malloc(scene.camera.hres * scene.camera.vres * 3 * sizeof *array3d);\n" }, { "answer_id": 262119, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 1, "selected": false, "text": "typedef struct\n{\n GLfloat R, G, B;\n} color_t;\n\ncolor_t *array1d;\n\nvoid InitScreenArray()\n{ \n long screenX = scene.camera.vres;\n long screenY = scene.camera.hres;\n array1d = (color_t *)malloc(screenX * screenY * sizeof(color_t));\n}\n\nvoid SetScreenColor(int x, int y, float red, float green, float blue)\n{\n int screenX = scene.camera.vres;\n int screenY = scene.camera.hres;\n\n array1d[x + y*screenY].R = red;\n array1d[x + y*screenY].G = green;\n array1d[x + y*screenY].B = blue;\n}\n\nvoid onDisplay( ) \n{\n glClearColor(0.1f, 0.2f, 0.3f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glRasterPos2i(0,0); \n glDrawPixels(scene.camera.hres, scene.camera.vres, GL_RGB, GL_FLOAT, array1d);\n\n glFinish();\n glutSwapBuffers();\n}\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13937/" ]
259,897
<p>This question is related to <a href="https://stackoverflow.com/questions/259663/vba-password-protection-how-it-works-is-it-secure-are-there-any-alternatives">my previous one</a>.</p> <p>Can you explain or provide a link to an explanation of how Excel VBA code password protection actually works in versions prior to 2007? What is the difference in Excel 2007 and previous versions in terms of password protection?</p> <p>Also does Excel's password protection actually encrypt the code? How does Excel execute the code if it is encrypted?</p> <p>Lastly, how does password removal software for excel work?</p>
[ { "answer_id": 260619, "author": "Phil.Wheeler", "author_id": 15609, "author_profile": "https://Stackoverflow.com/users/15609", "pm_score": 5, "selected": true, "text": "vbext_pp_locked vbext_pp_locked" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
259,900
<p>Check it out: this little .NET Console Program yields interesting results...notice how I'm converting a float to an integer in two different ways:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CastVsConvert { class Program { static void Main(string[] args) { int newWidth = 0; CalculateResizeSizes(600, 500, out newWidth); } static void CalculateResizeSizes(int originalWidth, int maxWidth, out int newWidth) { float percentage = 1.0F; percentage = maxWidth / (float)originalWidth; newWidth = (int)((float)originalWidth * percentage); int newWidthConvert = Convert.ToInt32((float)originalWidth * percentage); Console.Write("Percentage: {0}\n", percentage.ToString()); Console.Write("Cast: {0}\n", newWidth.ToString()); Console.Write("Convert: {0}\n", newWidthConvert.ToString()); } } } </code></pre> <p>I would expect the output for "Cast" and "Convert" to be the same, but they're not...here's the output:</p> <pre><code>C:\Documents and Settings\Scott\My Documents\Visual Studio 2008\Projects\CastVsC onvert\CastVsConvert\bin\Debug&gt;CastVsConvert.exe Percentage: 0.8333333 Cast: 499 Convert: 500 </code></pre> <p>Does anybody know why .NET is returning different values here? </p>
[ { "answer_id": 259906, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 4, "selected": false, "text": "cast convert" }, { "answer_id": 259937, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 1, "selected": false, "text": "int newWidthConvert = Convert.ToInt32(newWidth);\n Convert.ToInt32(float) public static int ToInt32(float value)\n{\n return ToInt32((double) value);\n}\n Double float newWidth1 = ((float)originalWidth * percentage);\ndouble newWidth2 = ((float)originalWidth * percentage); \n double float Convert.ToInt32() float Double double" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33754/" ]
259,902
<p>I have the following solution project structure:</p> <blockquote> <p>Application.Core.Entities</p> <p>Application.Xtend.CustomerName.Entities</p> </blockquote> <p>In the Core project I have an entity <strong>Customer</strong> defiend. In the XTend project, I have an entity defined that subclasses Customer named <strong>xCustomer</strong> (for lack of a better name at this time...).</p> <p>The idea here is that we have a Core domain model in our application. A customer can then create a new assembly that contains extensions to our core model. When the extension assembly is present a smart <a href="http://martinfowler.com/eaaCatalog/repository.html" rel="noreferrer">IRepository</a> class will return a subclass of the core class instead.</p> <p>I am attempting to map this relationship in <a href="http://nhforge.org/" rel="noreferrer">NHibernate</a>. Using <a href="http://code.google.com/p/fluent-nhibernate/" rel="noreferrer">Fluent NHibernate</a> I was able to generate this mapping:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;hibernate-mapping xmlns=&quot;urn:nhibernate-mapping-2.2&quot; default-lazy=&quot;false&quot; assembly=&quot;NHibernate.Core.Entites&quot; namespace=&quot;NHibernate.Entites&quot; default-access=&quot;field.camelcase-underscore&quot;&gt; &lt;!-- Customer is located in assembly Application.Core.Entities --&gt; &lt;class name=&quot;Customer&quot; table=&quot;Customers&quot; xmlns=&quot;urn:nhibernate-mapping-2.2&quot;&gt; &lt;id name=&quot;Id&quot; column=&quot;Id&quot; type=&quot;Int64&quot;&gt; &lt;generator class=&quot;native&quot; /&gt; &lt;/id&gt; &lt;component name=&quot;Name&quot; insert=&quot;true&quot; update=&quot;true&quot;&gt; &lt;property name=&quot;LastName&quot; column=&quot;LastName&quot; length=&quot;255&quot; type=&quot;String&quot; not-null=&quot;true&quot;&gt; &lt;column name=&quot;LastName&quot; /&gt; &lt;/property&gt; &lt;property name=&quot;FirstName&quot; column=&quot;FirstName&quot; length=&quot;255&quot; type=&quot;String&quot; not-null=&quot;true&quot;&gt; &lt;column name=&quot;FirstName&quot; /&gt; &lt;/property&gt; &lt;/component&gt; &lt;!-- xCustomer is located in assembly Application.XTend.CustomerName.Entities --&gt; &lt;joined-subclass name=&quot;xCustomer&quot; table=&quot;xCustomer&quot;&gt; &lt;key column=&quot;CustomerId&quot; /&gt; &lt;property name=&quot;CustomerType&quot; column=&quot;CustomerType&quot; length=&quot;255&quot; type=&quot;String&quot; not-null=&quot;true&quot;&gt; &lt;column name=&quot;CustomerType&quot; /&gt; &lt;/property&gt; &lt;/joined-subclass&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>But NHib throws the following error:</p> <blockquote> <p>NHibernate.MappingException: persistent class Application.Entites.xCustomer, Application.Core.Entites not found ---&gt; System.TypeLoadException: Could not load type 'Application.Entites.xCustomer' from assembly 'Application.Core.Entites, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'..</p> </blockquote> <p>Which makes sense xCustomer is not defined in the Core library.</p> <p>Is it possible to span different assemblies like this? Am I approaching the problem wrong?</p>
[ { "answer_id": 261820, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": false, "text": "extends <class> .hbm.xml" }, { "answer_id": 262419, "author": "NotMyself", "author_id": 303, "author_profile": "https://Stackoverflow.com/users/303", "pm_score": 4, "selected": true, "text": "<joined-subclass name=\"Application.XTend.CustomerName.Entities.xCustomer, \n Application.XTend.CustomerName.Entities, Version=1.0.0.0, \n Culture=neutral, PublicKeyToken=null\" \n table=\"xCustomer\">\n <key column=\"CustomerId\" />\n <property name=\"CustomerType\" column=\"CustomerType\" length=\"255\" \n type=\"String\" not-null=\"true\">\n <column name=\"CustomerType\" />\n </property>\n</joined-subclass>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ]
259,941
<p>Wondering if my approach is ok or could be improved:</p> <pre><code>Public Class Company private _id as Integer private _name as String private _location as String Public Function LoadMultipleByLocation(Byval searchStr as String) as List(Of Company) 'sql etc here to build the list End Function End Classs </code></pre> <p>Thoughts on having the object mapping like this?</p>
[ { "answer_id": 259964, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "public class Company : EntityBase\n{\n private int _id;\n private string _name;\n private string _location;\n}\n" }, { "answer_id": 260159, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "public class EntityBase\n{\n public virtual string SaveSproc { get; }\n\n public virtual void LoadFromReader(SqlReader reader)\n {\n }\n\n public virtual void Save()\n {\n List<SqlParameters> paramList = = this.CreateParamsList();\n DoSqlStuff(this.SaveSproc, paramList);\n }\n\n public virtual List<SqlParamenter> CreateParamsList()\n { \n return new List<SqlParameter>\n }\n}\n\npublic Company : EntityBase\n{\n\n private string _data;\n\npublic override string SaveSproc { get { return \"SprocThatSaves\"; } }\n\n public override List<SqlParameter> CreateParamList()\n{ \n List<SqlParameter> param = new List<SqlParameter>\n param.Add(new SqlParameter(\"Data\",_data);\n\n return param; \n}\n\npublic override void LoadFromReader(SqlReader reader)\n{\n // PsuedoCode\n _data = reader[\"data\"];\n}\n}\n Company = new Company();\nCompany.LoadFromReader(reader);\n Company.Save();\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
259,943
<p>I have to simultaneously load data into a table and run queries on it. Because of data nature, I can trade integrity for performance. How can I minimize the overhead of transactions?</p> <p>Unfortunately, alternatives like MySQL cannot be used (due to non-technical reasons). </p>
[ { "answer_id": 262111, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 2, "selected": true, "text": "No Archive Log /*+ APPEND */ RAID 0 RAID 10" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18174/" ]
259,956
<p>What is the best way to tokenize/split a NSString in Objective-C?</p>
[ { "answer_id": 259966, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 9, "selected": true, "text": "NSString *string = @\"oop:ack:bork:greeble:ponies\";\nNSArray *chunks = [string componentsSeparatedByString: @\":\"];\n" }, { "answer_id": 261105, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 4, "selected": false, "text": "-[NSString componentsSeparatedByString:]" }, { "answer_id": 432796, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 5, "selected": false, "text": "componentsSeparatedByString: CFStringTokenizer NSString CFString" }, { "answer_id": 12151143, "author": "Wienke", "author_id": 471678, "author_profile": "https://Stackoverflow.com/users/471678", "pm_score": 3, "selected": false, "text": "componentsSeparatedByCharactersInSet whitespaceCharacterSet illegalCharacterSet // Tokenize sSourceEntityName on both whitespace and punctuation.\nNSMutableCharacterSet *mcharsetWhitePunc = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];\n[mcharsetWhitePunc formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];\nNSArray *sarrTokenizedName = [self.sSourceEntityName componentsSeparatedByCharactersInSet:mcharsetWhitePunc];\n[mcharsetWhitePunc release];\n componentsSeparatedByCharactersInSet" }, { "answer_id": 16321262, "author": "Rosario Carcò", "author_id": 2332617, "author_profile": "https://Stackoverflow.com/users/2332617", "pm_score": 0, "selected": false, "text": "//as the ldap query has to be done when the user selects one of our Active Directory Domains\n//(an according comboBox should be populated with print-server names we discover from AD)\n//my code is placed in the onSelectDomain event code\n\n//the following variables are declared in the interface .h file as globals\n@protected NSArray* aDomains;//domain combo list array\n@protected NSMutableArray* aPrinters;//printer combo list array\n@protected NSMutableArray* aPrintServers;//print server combo list array\n\n@protected NSString* sLdapQueryCommand;//for LDAP Queries\n@protected NSArray* aLdapQueryArgs;\n@protected NSTask* tskLdapTask;\n@protected NSPipe* pipeLdapTask;\n@protected NSFileHandle* fhLdapTask;\n@protected NSMutableData* mdLdapTask;\n\nIBOutlet NSComboBox* comboDomain;\nIBOutlet NSComboBox* comboPrinter;\nIBOutlet NSComboBox* comboPrintServer;\n//end of interface globals\n\n//after collecting the print-server names they are displayed in an according drop-down comboBox\n//as soon as the user selects one of the print-servers, we should start a new query to find all the\n//print-queues on that server and display them in the comboPrinter drop-down list\n//to find the shares/print queues of a windows print-server you need samba and the net -S command like this:\n// net -S yourPrintServerName.yourBaseDomain.com -U yourLdapUser%yourLdapUserPassWord -W adm rpc share -l\n//which dispalays a long list of the shares\n\n- (IBAction)onSelectDomain:(id)sender\n{\n static int indexOfLastItem = 0; //unfortunately we need to compare this because we are called also if the selection did not change!\n\n if ([comboDomain indexOfSelectedItem] != indexOfLastItem && ([comboDomain indexOfSelectedItem] != 0))\n {\n\n indexOfLastItem = [comboDomain indexOfSelectedItem]; //retain this index for next call\n\n //the print-servers-list has to be loaded on a per univeristy or domain basis from a file dynamically or from AN LDAP-QUERY\n\n //initialize an LDAP-Query-Task or console-command like this one with console output\n /*\n\n ldapsearch -LLL -s sub -D \"cn=yourLdapUser,ou=yourOuWithLdapUserAccount,dc=yourDomain,dc=com\" -h \"yourLdapServer.com\" -p 3268 -w \"yourLdapUserPassWord\" -b \"dc=yourBaseDomainToSearchIn,dc=com\" \"(&(objectcategory=computer)(cn=ps*))\" \"dn\"\n\n//our print-server names start with ps* and we want the dn as result, wich comes like this:\n\n dn: CN=PSyourPrintServerName,CN=Computers,DC=yourBaseDomainToSearchIn,DC=com\n\n */\n\n sLdapQueryCommand = [[NSString alloc] initWithString: @\"/usr/bin/ldapsearch\"];\n\n\n if ([[comboDomain stringValue] compare: @\"firstDomain\"] == NSOrderedSame) {\n\n aLdapQueryArgs = [NSArray arrayWithObjects: @\"-LLL\",@\"-s\", @\"sub\",@\"-D\", @\"cn=yourLdapUser,ou=yourOuWithLdapUserAccount,dc=yourDomain,dc=com\",@\"-h\", @\"yourLdapServer.com\",@\"-p\",@\"3268\",@\"-w\",@\"yourLdapUserPassWord\",@\"-b\",@\"dc=yourFirstDomainToSearchIn,dc=com\",@\"(&(objectcategory=computer)(cn=ps*))\",@\"dn\",nil];\n }\n else {\n aLdapQueryArgs = [NSArray arrayWithObjects: @\"-LLL\",@\"-s\", @\"sub\",@\"-D\", @\"cn=yourLdapUser,ou=yourOuWithLdapUserAccount,dc=yourDomain,dc=com\",@\"-h\", @\"yourLdapServer.com\",@\"-p\",@\"3268\",@\"-w\",@\"yourLdapUserPassWord\",@\"-b\",@\"dc=yourSecondDomainToSearchIn,dc=com\",@\"(&(objectcategory=computer)(cn=ps*))\",@\"dn\",nil];\n\n }\n\n\n //prepare and execute ldap-query task\n\n tskLdapTask = [[NSTask alloc] init];\n pipeLdapTask = [[NSPipe alloc] init];//instead of [NSPipe pipe]\n [tskLdapTask setStandardOutput: pipeLdapTask];//hope to get the tasks output in this file/pipe\n\n //The magic line that keeps your log where it belongs, has to do with NSLog (see https://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app and here http://www.cocoadev.com/index.pl?NSTask )\n [tskLdapTask setStandardInput:[NSPipe pipe]];\n\n //fhLdapTask = [[NSFileHandle alloc] init];//would be redundand here, next line seems to do the trick also\n fhLdapTask = [pipeLdapTask fileHandleForReading];\n mdLdapTask = [NSMutableData dataWithCapacity:512];//prepare capturing the pipe buffer which is flushed on read and can overflow, start with 512 Bytes but it is mutable, so grows dynamically later\n [tskLdapTask setLaunchPath: sLdapQueryCommand];\n [tskLdapTask setArguments: aLdapQueryArgs];\n\n#ifdef bDoDebug\n NSLog (@\"sLdapQueryCommand: %@\\n\", sLdapQueryCommand);\n NSLog (@\"aLdapQueryArgs: %@\\n\", aLdapQueryArgs );\n NSLog (@\"tskLdapTask: %@\\n\", [tskLdapTask arguments]);\n#endif\n\n [tskLdapTask launch];\n\n while ([tskLdapTask isRunning]) {\n [mdLdapTask appendData: [fhLdapTask readDataToEndOfFile]];\n }\n [tskLdapTask waitUntilExit];//might be redundant here.\n\n [mdLdapTask appendData: [fhLdapTask readDataToEndOfFile]];//add another read for safety after process/command stops\n\n NSString* sLdapOutput = [[NSString alloc] initWithData: mdLdapTask encoding: NSUTF8StringEncoding];//convert output to something readable, as NSData and NSMutableData are mere byte buffers\n\n#ifdef bDoDebug\n NSLog(@\"LdapQueryOutput: %@\\n\", sLdapOutput);\n#endif\n\n //Ok now we have the printservers from Active Directory, lets parse the output and show the list to the user in its combo box\n //output is formatted as this, one printserver per line\n //dn: CN=PSyourPrintServer,OU=Computers,DC=yourBaseDomainToSearchIn,DC=com\n\n //so we have to search for \"dn: CN=\" to retrieve each printserver's name\n //unfortunately splitting this up will give us a first line containing only \"\" empty string, which we can replace with the word \"choose\"\n //appearing as first entry in the comboBox\n\n aPrintServers = (NSMutableArray*)[sLdapOutput componentsSeparatedByString:@\"dn: CN=\"];//split output into single lines and store it in the NSMutableArray aPrintServers\n\n#ifdef bDoDebug\n NSLog(@\"aPrintServers: %@\\n\", aPrintServers);\n#endif\n\n if ([[aPrintServers objectAtIndex: 0 ] compare: @\"\" options: NSLiteralSearch] == NSOrderedSame){\n [aPrintServers replaceObjectAtIndex: 0 withObject: slChoose];//replace with localized string \"choose\"\n\n#ifdef bDoDebug\n NSLog(@\"aPrintServers: %@\\n\", aPrintServers);\n#endif\n\n }\n\n//Now comes the tedious part to extract only the print-server-names from the single lines\n NSRange r;\n NSString* sTemp;\n\n for (int i = 1; i < [aPrintServers count]; i++) {//skip first line with \"choose\". To get rid of the rest of the line, we must isolate/preserve the print server's name to the delimiting comma and remove all the remaining characters\n sTemp = [aPrintServers objectAtIndex: i];\n sTemp = [sTemp stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];//remove newlines and line feeds\n\n#ifdef bDoDebug\n NSLog(@\"sTemp: %@\\n\", sTemp);\n#endif\n r = [sTemp rangeOfString: @\",\"];//now find first comma to remove the whole rest of the line\n //r.length = [sTemp lengthOfBytesUsingEncoding:NSUTF8StringEncoding];\n r.length = [sTemp length] - r.location;//calculate number of chars between first comma found and lenght of string\n#ifdef bDoDebug\n NSLog(@\"range: %i, %i\\n\", r.location, r.length);\n#endif\n\n sTemp = [sTemp stringByReplacingCharactersInRange:r withString: @\"\" ];//remove rest of line\n#ifdef bDoDebug\n NSLog(@\"sTemp after replace: %@\\n\", sTemp);\n#endif\n\n [aPrintServers replaceObjectAtIndex: i withObject: sTemp];//put back string into array for display in comboBox\n\n#ifdef bDoDebug\n NSLog(@\"aPrintServer: %@\\n\", [aPrintServers objectAtIndex: i]);\n#endif\n\n }\n\n [comboPrintServer removeAllItems];//reset combo box\n [comboPrintServer addItemsWithObjectValues:aPrintServers];\n [comboPrintServer setNumberOfVisibleItems:aPrintServers.count];\n [comboPrintServer selectItemAtIndex:0];\n\n#ifdef bDoDebug\n NSLog(@\"comboPrintServer reloaded with new values.\");\n#endif\n\n\n//release memory we used for LdapTask\n [sLdapQueryCommand release];\n [aLdapQueryArgs release];\n [sLdapOutput release];\n\n [fhLdapTask release];\n\n [pipeLdapTask release];\n// [tskLdapTask release];//strangely can not be explicitely released, might be autorelease anyway\n// [mdLdapTask release];//strangely can not be explicitely released, might be autorelease anyway\n\n [sTemp release];\n\n }\n}\n" }, { "answer_id": 22761154, "author": "Michael Waterfall", "author_id": 106244, "author_profile": "https://Stackoverflow.com/users/106244", "pm_score": 3, "selected": false, "text": "NSString \"\" '' ‘’ “” NSArray *terms = [@\"This is my \\\"search phrase\\\" I want to split\" searchTerms];\n// results in: [\"This\", \"is\", \"my\", \"search phrase\", \"I\", \"want\", \"to\", \"split\"]\n @interface NSString (Search)\n- (NSArray *)searchTerms;\n@end\n\n@implementation NSString (Search)\n\n- (NSArray *)searchTerms {\n\n // Strip whitespace and setup scanner\n NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];\n NSString *searchString = [self stringByTrimmingCharactersInSet:whitespace];\n NSScanner *scanner = [NSScanner scannerWithString:searchString];\n [scanner setCharactersToBeSkipped:nil]; // we'll handle whitespace ourselves\n\n // A few types of quote pairs to check\n NSDictionary *quotePairs = @{@\"\\\"\": @\"\\\"\",\n @\"'\": @\"'\",\n @\"\\u2018\": @\"\\u2019\",\n @\"\\u201C\": @\"\\u201D\"};\n\n // Scan\n NSMutableArray *results = [[NSMutableArray alloc] init];\n NSString *substring = nil;\n while (scanner.scanLocation < searchString.length) {\n // Check for quote at beginning of string\n unichar unicharacter = [self characterAtIndex:scanner.scanLocation];\n NSString *startQuote = [NSString stringWithFormat:@\"%C\", unicharacter];\n NSString *endQuote = [quotePairs objectForKey:startQuote];\n if (endQuote != nil) { // if it's a valid start quote we'll have an end quote\n // Scan quoted phrase into substring (skipping start & end quotes)\n [scanner scanString:startQuote intoString:nil];\n [scanner scanUpToString:endQuote intoString:&substring];\n [scanner scanString:endQuote intoString:nil];\n } else {\n // Single word that is non-quoted\n [scanner scanUpToCharactersFromSet:whitespace intoString:&substring];\n }\n // Process and add the substring to results\n if (substring) {\n substring = [substring stringByTrimmingCharactersInSet:whitespace];\n if (substring.length) [results addObject:substring];\n }\n // Skip to next word\n [scanner scanCharactersFromSet:whitespace intoString:nil];\n }\n\n // Return non-mutable array\n return results.copy;\n\n}\n\n@end\n" }, { "answer_id": 25105997, "author": "Robert", "author_id": 296446, "author_profile": "https://Stackoverflow.com/users/296446", "pm_score": 2, "selected": false, "text": "NSString * string = @\" \\n word1! word2,%$?'/word3.word4 \";\n\n[string enumerateSubstringsInRange:NSMakeRange(0, string.length)\n options:NSStringEnumerationByWords\n usingBlock:\n ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {\n NSLog(@\"Substring: '%@'\", substring);\n }];\n\n // Logs:\n // Substring: 'word1'\n // Substring: 'word2'\n // Substring: 'word3'\n // Substring: 'word4' \n NSStringEnumerationByComposedCharacterSequences" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
259,968
<p>Consider the following file</p> <pre><code>var1 var2 variable3 1 2 3 11 22 33 </code></pre> <p>I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to:</p> <pre><code>variable_names = char('var1', 'var2', 'variable3'); </code></pre> <p>I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option. </p> <p>Note that there can be an arbitrary number of variables (columns)</p>
[ { "answer_id": 260016, "author": "Robert Van Hoose", "author_id": 460599, "author_profile": "https://Stackoverflow.com/users/460599", "pm_score": 1, "selected": false, "text": "fid = fopen(filename,'r');\nheading = textscan(fid,'%s %s %s',1);\nfgetl(fid); %advance the file pointer one line\ndata = textscan(fid,'%n %n %n');%read the rest of the data\nfclose(fid);\n" }, { "answer_id": 260093, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 2, "selected": false, "text": "A = dlmread(filename,delimString,2,1);\n fid = fopen(filename)\nheaderString = fscanf(fid,'%s/n') % reads header data into a string\nfclose(fid)\n" }, { "answer_id": 263943, "author": "Adam Holmberg", "author_id": 20688, "author_profile": "https://Stackoverflow.com/users/20688", "pm_score": 4, "selected": true, "text": "d = importdata('filename.txt');\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17523/" ]
259,972
<p>I am trying to create an instance of a COM object. I have the class name that implements the interface and I get a CLSID by using CLSIDFromProgID(). So since I am getting a CLSID I thought everything should be fine from now on. However when I do a call to CreateInstance and pass in the CLSID, I get an error saying "Class not registered". Also I get this error only in some computers. It runs error free on several computers. I don't understand where the problem could be. Is my registry dirty? Does anyone know what is going on here? Thanks for your help!</p> <p>I just want to add that this is a .NET COM class. The appropriate entries are in the registry and the DLL is in the GAC.</p>
[ { "answer_id": 1742446, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 0, "selected": false, "text": "var shl = (Shell) Activator.CreateInstance(Type.GetTypeFromProgID(\"Shell.Application\"));\n var shl2 = (Shell) Marshal.GetActiveObject(\"Shell.Application\");\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8661/" ]
260,008
<p>Is there a way to <strong>increase the font-size</strong> in the Firefox extension Firebug?</p>
[ { "answer_id": 12217650, "author": "Nat Ritmeyer", "author_id": 2032500, "author_profile": "https://Stackoverflow.com/users/2032500", "pm_score": 0, "selected": false, "text": "extensions.firebug.textSize about:config 0" }, { "answer_id": 17988316, "author": "Ankur Saxena", "author_id": 1647941, "author_profile": "https://Stackoverflow.com/users/1647941", "pm_score": 0, "selected": false, "text": "1.open firebug\n2.on the right side there are three icons select open firebug in new window(option)\n3.click left side firebug option on new window\n4.mouse over to text size you find\n a.increase text size ctrl++\n b.decrease text size ctrl+-\n c.normal text size ctrl+0\n5.lastly right side there are three icons select open firebug in new window(option)\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
260,010
<p>If I have a query to return all matching entries in a DB that have "news" in the searchable column (i.e. <code>SELECT * FROM table WHERE column LIKE %news%</code>), and one particular row has an entry starting with "In recent World news, Somalia was invaded by ...", can I return a specific "chunk" of an SQL entry? Kind of like a teaser, if you will.</p>
[ { "answer_id": 260023, "author": "Rockcoder", "author_id": 5290, "author_profile": "https://Stackoverflow.com/users/5290", "pm_score": 2, "selected": false, "text": "SELECT SUBSTRING(column, 1,20) FROM table WHERE column LIKE %news%\n" }, { "answer_id": 260029, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 4, "selected": true, "text": "select substring(column,\n CHARINDEX ('news',lower(column))-10,\n 20)\nFROM table \nWHERE column LIKE %news%\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
260,040
<p>I want to make a transparent dialog. I capture the OnCtlColor message in a CDialog derived class...this is the code:</p> <pre><code>HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if(bSetBkTransparent_) { pDC-&gt;SetBkMode(TRANSPARENT); hbr = (HBRUSH)GetStockObject(NULL_BRUSH); } return hbr; } </code></pre> <p>It works fine for all the controls but the group-box (CStatic). All the labels (CStatic) are been painted with a transparent text background but the text of the group box it is not transparent.</p> <p>I already googled for this but I didn't find a solutions. Does anybody know how to make a real transparent group-box?</p> <p>By the way, I am working in Windows XP. And I don't want to fully draw the control to avoid having to change the code if the application is migrated to another OS.</p> <p>Thanks,</p> <p>Javier</p> <p>Note: I finally changed the dialog so that I don't need to make it transparent. Anyway, I add this information because maybe someone is still trying to do it. The groupbox isn't a CStatic but a CButton (I know this is not new). I changed the Windows XP theme to Windows classic and then the groupbox backgraund was transparent. The bad new is that in this case the frame line gets visible beneath the text...so if someone is following this approach I think maybe he/she would better follow the Adzm's advice. </p>
[ { "answer_id": 68690192, "author": "Mecanik", "author_id": 6583298, "author_profile": "https://Stackoverflow.com/users/6583298", "pm_score": 0, "selected": false, "text": "case WM_CTLCOLORSTATIC: \n{\n HDC hDC = (HDC)wParam;\n SetTextColor(hDC, RGB(255, 255, 255));\n SetBkMode(hDC, TRANSPARENT);\n return (INT_PTR)GetStockObject(HOLLOW_BRUSH);\n}\nbreak;\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14053/" ]
260,043
<p>I want to display from cache for a long time and I want a slightly different behavior on page render vs loading the page from cache. Is there an easy way I can determine this with JavaScript?</p>
[ { "answer_id": 260108, "author": "Will Dieterich", "author_id": 31233, "author_profile": "https://Stackoverflow.com/users/31233", "pm_score": 1, "selected": false, "text": "timestamp cacheLength timestamp timestamp+cacheLength" }, { "answer_id": 13390644, "author": "Reactgular", "author_id": 1031569, "author_profile": "https://Stackoverflow.com/users/1031569", "pm_score": 2, "selected": false, "text": "$(document).ready(function()\n{\n $('body').append('<div class=\"is_cached\"></div>');\n});\n\nHistory.Adapter.bind(window,'statechange',function(){\n if($('.is_cached').length >= 1)\n {\n alert('this page is cached');\n }\n});\n" }, { "answer_id": 51817474, "author": "Knaģis", "author_id": 1711598, "author_profile": "https://Stackoverflow.com/users/1711598", "pm_score": 4, "selected": false, "text": "var isCached = performance.getEntriesByType(\"navigation\")[0].transferSize === 0;\n" }, { "answer_id": 56249394, "author": "Afterparty", "author_id": 7140849, "author_profile": "https://Stackoverflow.com/users/7140849", "pm_score": 1, "selected": false, "text": " window.rand = {{ rand() }} \n reloadIfCached() {\n var cached = localStorage.getItem(window.location.href) == window.rand;\n if (cached) {\n window.location.reload();\n }\n localStorage.setItem(window.location.href, window.rand);\n }\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30099/" ]
260,056
<p>I'm trying to figure out if there's a reasonably efficient way to perform a lookup in a dictionary (or a hash, or a map, or whatever your favorite language calls it) where the keys are regular expressions and strings are looked up against the set of keys. For example (in Python syntax):</p> <pre><code>&gt;&gt;&gt; regex_dict = { re.compile(r'foo.') : 12, re.compile(r'^FileN.*$') : 35 } &gt;&gt;&gt; regex_dict['food'] 12 &gt;&gt;&gt; regex_dict['foot in my mouth'] 12 &gt;&gt;&gt; regex_dict['FileNotFoundException: file.x does not exist'] 35 </code></pre> <p>(Obviously the above example won't work as written in Python, but that's the sort of thing I'd like to be able to do.)</p> <p>I can think of a naive way to implement this, in which I iterate over all of the keys in the dictionary and try to match the passed in string against them, but then I lose the O(1) lookup time of a hash map and instead have O(n), where n is the number of keys in my dictionary. This is potentially a big deal, as I expect this dictionary to grow very large, and I will need to search it over and over again (actually I'll need to iterate over it for every line I read in a text file, and the files can be hundreds of megabytes in size).</p> <p>Is there a way to accomplish this, without resorting to O(n) efficiency?</p> <p>Alternatively, if you know of a way to accomplish this sort of a lookup in a database, that would be great, too.</p> <p>(Any programming language is fine -- I'm using Python, but I'm more interested in the data structures and algorithms here.)</p> <p>Someone pointed out that more than one match is possible, and that's absolutely correct. Ideally in this situation I'd like to return a list or tuple containing all of the matches. I'd settle for the first match, though.</p> <p>I can't see O(1) being possible in that scenario; I'd settle for anything less than O(n), though. Also, the underlying data structure could be anything, but the basic behavior I'd like is what I've written above: lookup a string, and return the value(s) that match the regular expression keys.</p>
[ { "answer_id": 260079, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 0, "selected": false, "text": ">>> regex_dict['FileNfoo']\n" }, { "answer_id": 260085, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "regex_dict = { re.compile(\"foo.*\"): 5, re.compile(\"f.*\"): 6 }\n regex_dict[\"food\"]" }, { "answer_id": 260591, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 0, "selected": false, "text": ".* \\d+ a*b*c ^\\d+a\\*b\\*c:\\s+\\w+" }, { "answer_id": 260886, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "use Tie::Hash::Regex;\nmy %h;\n\ntie %h, 'Tie::Hash::Regex';\n\n$h{key} = 'value';\n$h{key2} = 'another value';\n$h{stuff} = 'something else';\n\nprint $h{key}; # prints 'value'\nprint $h{2}; # prints 'another value'\nprint $h{'^s'}; # prints 'something else'\n\nprint tied(%h)->FETCH(k); # prints 'value' and 'another value'\n\ndelete $h{k}; # deletes $h{key} and $h{key2};\n" }, { "answer_id": 816047, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "class redict(dict):\ndef __init__(self, d):\n dict.__init__(self, d)\n\ndef __getitem__(self, regex):\n r = re.compile(regex)\n mkeys = filter(r.match, self.keys())\n for i in mkeys:\n yield dict.__getitem__(self, i)\n >>> keys = [\"a\", \"b\", \"c\", \"ab\", \"ce\", \"de\"]\n>>> vals = range(0,len(keys))\n>>> red = redict(zip(keys, vals))\n>>> for i in red[r\"^.e$\"]:\n... print i\n... \n5\n4\n>>>\n" }, { "answer_id": 5835497, "author": "TOTEM_MOTORIST", "author_id": 731518, "author_profile": "https://Stackoverflow.com/users/731518", "pm_score": 0, "selected": false, "text": "C++/CLI LanguageProcessor.dll DynamicMethod Emit Reflexion fasterlex_engine <Regex, action_delegate> map_rule[gcnew Regex(\"[a-zA-Z]\")];\n public ref class lex_rule: ILexRule\n{\nprivate:\n Exception ^m_exception;\n Regex ^m_pattern;\n\n //BACKSTORAGE delegates, esto me lo aprendi asiendo la huella.net de m*e*da JEJE\n yy_lexical_action ^m_yy_lexical_action; \n yy_user_action ^m_yy_user_action;\n\npublic: \n virtual property String ^short_id; \nprivate:\n void init(String ^_short_id, String ^well_formed_regex);\npublic:\n\n lex_rule();\n lex_rule(String ^_short_id,String ^well_formed_regex);\n virtual event yy_lexical_action ^YY_RULE_MATCHED\n {\n virtual void add(yy_lexical_action ^_delegateHandle)\n {\n if(nullptr==m_yy_lexical_action)\n m_yy_lexical_action=_delegateHandle;\n }\n virtual void remove(yy_lexical_action ^)\n {\n m_yy_lexical_action=nullptr;\n }\n\n virtual long raise(String ^id_rule, String ^input_string, String ^match_string, int index) \n {\n long lReturn=-1L;\n if(m_yy_lexical_action)\n lReturn=m_yy_lexical_action(id_rule,input_string, match_string, index);\n return lReturn;\n }\n }\n};\n public ref class fasterlex_engine \n{\nprivate: \n Dictionary<String^,ILexRule^> ^m_map_rules;\npublic:\n fasterlex_engine();\n fasterlex_engine(array<String ^,2>^defs);\n Dictionary<String ^,Exception ^> ^load_definitions(array<String ^,2> ^defs);\n void run();\n};\n inline Exception ^object::builder(ConstructorInfo ^target, array<Type^> ^args)\n{\ntry\n{\n DynamicMethod ^dm=gcnew DynamicMethod(\n \"dyna_method_by_totem_motorist\",\n Object::typeid,\n args,\n target->DeclaringType);\n ILGenerator ^il=dm->GetILGenerator();\n il->Emit(OpCodes::Ldarg_0);\n il->Emit(OpCodes::Call,Object::typeid->GetConstructor(Type::EmptyTypes)); //invoca a constructor base\n il->Emit(OpCodes::Ldarg_0);\n il->Emit(OpCodes::Ldarg_1);\n il->Emit(OpCodes::Newobj, target); //NewObj crea el objeto e invoca al constructor definido en target\n il->Emit(OpCodes::Ret);\n method_handler=(method_invoker ^) dm->CreateDelegate(method_invoker::typeid);\n}\ncatch (Exception ^e)\n{\n return e;\n}\nreturn nullptr;\n Delegate ^connection_point::hook(String ^receiver_namespace,String ^receiver_class_name, String ^handler_name)\n{\nDelegate ^d=nullptr;\nif(connection_point::waitfor_hook<=m_state) // si es 0,1,2 o mas => intenta hookear\n{ \n try \n {\n Type ^tmp=meta::_class(receiver_namespace+\".\"+receiver_class_name);\n m_handler=tmp->GetMethod(handler_name);\n m_receiver_object=Activator::CreateInstance(tmp,false); \n\n d=m_handler->IsStatic?\n Delegate::CreateDelegate(m_tdelegate,m_handler):\n Delegate::CreateDelegate(m_tdelegate,m_receiver_object,m_handler);\n\n m_add_handler=m_connection_point->GetAddMethod();\n array<Object^> ^add_handler_args={d};\n m_add_handler->Invoke(m_publisher_object, add_handler_args);\n ++m_state;\n m_exception_flag=false;\n }\n catch(Exception ^e)\n {\n m_exception_flag=true;\n throw gcnew Exception(e->ToString()) ;\n }\n}\nreturn d; \n}\n array<String ^,2> ^defs=gcnew array<String^,2> {/* shortID pattern namespc clase fun*/\n {\"LETRAS\", \"[A-Za-z]+\" ,\"prueba\", \"manejador\", \"procesa_directriz\"},\n {\"INTS\", \"[0-9]+\" ,\"prueba\", \"manejador\", \"procesa_comentario\"},\n {\"REM\", \"--[^\\\\n]*\" ,\"prueba\", \"manejador\", \"nullptr\"}\n }; //[3,5]\n\n//USO EL IDENTIFICADOR ESPECIAL \"nullptr\" para que el sistema asigne el proceso del evento a un default que realice nada\nfasterlex_engine ^lex=gcnew fasterlex_engine();\nDictionary<String ^,Exception ^> ^map_error_list=lex->load_definitions(defs);\nlex->run();\n" }, { "answer_id": 16875839, "author": "rptb1", "author_id": 425078, "author_profile": "https://Stackoverflow.com/users/425078", "pm_score": 2, "selected": false, "text": "lastindex # Regular expression map\n# Abuses match.lastindex to figure out which key was matched\n# (i.e. to emulate extracting the terminal state of the DFA of the regexp engine)\n# Mostly for amusement.\n# Richard Brooksby, Ravenbrook Limited, 2013-06-01\n\nimport re\n\nclass ReMap(object):\n\n def __init__(self, items):\n if not items:\n items = [(r'epsilon^', None)] # Match nothing\n key_patterns = []\n self.lookup = {}\n index = 1\n for key, value in items:\n # Ensure there are no capturing parens in the key, because\n # that would mess up match.lastindex\n key_patterns.append('(' + re.sub(r'\\((?!\\?:)', '(?:', key) + ')')\n self.lookup[index] = value\n index += 1\n self.keys_re = re.compile('|'.join(key_patterns))\n\n def __getitem__(self, key):\n m = self.keys_re.match(key)\n if m:\n return self.lookup[m.lastindex]\n raise KeyError(key)\n\nif __name__ == '__main__':\n remap = ReMap([(r'foo.', 12), (r'FileN.*', 35)])\n print remap['food']\n print remap['foot in my mouth']\n print remap['FileNotFoundException: file.x does not exist']\n" }, { "answer_id": 16878309, "author": "Nick Barnes", "author_id": 2444191, "author_profile": "https://Stackoverflow.com/users/2444191", "pm_score": 2, "selected": false, "text": "# Regular expression map\n# Abuses match.lastindex to figure out which key was matched\n# (i.e. to emulate extracting the terminal state of the DFA of the regexp engine)\n# Mostly for amusement.\n# Richard Brooksby, Ravenbrook Limited, 2013-06-01\n\nimport re\n\nclass ReMap(object):\n def __init__(self, items):\n if not items:\n items = [(r'epsilon^', None)] # Match nothing\n self.re = re.compile('|'.join('('+k+')' for (k,v) in items))\n self.lookup = {}\n index = 1\n for key, value in items:\n self.lookup[index] = value\n index += re.compile(key).groups + 1\n\n def __getitem__(self, key):\n m = self.re.match(key)\n if m:\n return self.lookup[m.lastindex]\n raise KeyError(key)\n\ndef test():\n remap = ReMap([(r'foo.', 12),\n (r'.*([0-9]+)', 99),\n (r'FileN.*', 35),\n ])\n print remap['food']\n print remap['foot in my mouth']\n print remap['FileNotFoundException: file.x does not exist']\n print remap['there were 99 trombones']\n print remap['food costs $18']\n print remap['bar']\n\nif __name__ == '__main__':\n test()\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33775/" ]
260,064
<p>Published Date returned from Twitter Search API Atom Feed as 2008-11-03T21:30:06Z which needs to be converted to "X seconds/minutes/hours/days ago" for showing how long ago twitter messages were posted.</p> <p>Think this can be done with php date() function using DATE_ATOM value?</p>
[ { "answer_id": 260199, "author": "Jack", "author_id": 24998, "author_profile": "https://Stackoverflow.com/users/24998", "pm_score": 3, "selected": true, "text": "function time_since($your_timestamp) {\n $unix_timestamp = strtotime($your_timestamp);\n $seconds = time() - $unix_timestamp;\n $minutes = 0;\n $hours = 0;\n $days = 0;\n $weeks = 0;\n $months = 0;\n $years = 0;\n if ( $seconds == 0 ) $seconds = 1;\n if ( $seconds> 60 ) {\n $minutes = $seconds/60;\n } else {\n return add_s($seconds,'second');\n }\n\n if ( $minutes >= 60 ) {\n $hours = $minutes/60;\n } else {\n return add_s($minutes,'minute');\n }\n\n if ( $hours >= 24) {\n $days = $hours/24;\n } else {\n return add_s($hours,'hour');\n }\n\n if ( $days >= 7 ) {\n $weeks = $days/7;\n } else {\n return add_s($days,'day');\n }\n\n if ( $weeks >= 4 ) {\n $months = $weeks/4;\n } else {\n return add_s($weeks,'week');\n }\n\n if ( $months>= 12 ) {\n $years = $months/12;\n return add_s($years,'year');\n } else {\n return add_s($months,'month');\n }\n\n}\n\nfunction add_s($num,$word) {\n $num = floor($num);\n if ( $num == 1 ) {\n return $num.' '.$word.' ago';\n } else {\n return $num.' '.$word.'s ago';\n }\n}\n\necho time_since('2008-11-03T21:30:06Z');\n" }, { "answer_id": 14595699, "author": "John Conde", "author_id": 250259, "author_profile": "https://Stackoverflow.com/users/250259", "pm_score": 0, "selected": false, "text": "$posted = new DateTime('2008-11-03T21:30:06Z');\n$now = new DateTime();\n$interval = $posted->diff($now);\necho $interval->format('%a days'); // You can change this to be whatever format you like\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
260,094
<p>I've been developing a few JSF applications lately and am disturbed with the inconsistency in the web component APIs. </p> <p>I've noticed that there is extremely unpredictable behavior when calling .getValue() or .getSubmittedValue() on a JSF component object in server side code. Sometimes when I call .getValue() on a drop down list box, I've noticed that I get the value as it was BEFORE I selected my value (so the value from the last page refresh), of which .getSubmittedValue() gets me the correct value, as such:</p> <pre><code>UIInput name = new UIInput(); // This is the control I have in a bean. public void submit(ActionEvent ae) { someMethod(name.getValue().toString()); // Retrieves the "old" value someMethod(name.getSubmittedValue().toString()); // Retrieves the correct value } </code></pre> <p>Also, I've noticed that calling .getSubmittedValue() on a form field sometimes results in a null pointer exception because that value has not been instantiated in the component object, in which case when I call .getValue() in that circumstance I get the correct value, for example:</p> <pre><code>HtmlInputText name = new HtmlInputText(); // This is the control I have in a bean. public void submit(ActionEvent ae) { someMethod(name.getValue().toString()); // Retrieves the correct value someMethod(name.getSubmittedValue().toString()); // Throws NullPointerException } </code></pre> <p>Is this just a "quirk" of the JSF framework, or am I just using the API <strong>COMPLETELY</strong> incorrectly?? Any insight into these two methods would be greatly appreciated. Cheers.</p>
[ { "answer_id": 1145620, "author": "Dr. Nichols", "author_id": 140412, "author_profile": "https://Stackoverflow.com/users/140412", "pm_score": 6, "selected": true, "text": "submit" }, { "answer_id": 46676231, "author": "Andrew", "author_id": 1599699, "author_profile": "https://Stackoverflow.com/users/1599699", "pm_score": 0, "selected": false, "text": "UIViewRoot viewRoot = context.getViewRoot();\nUIInput input = (UIInput)viewRoot.findComponent(\":form:inputID\");\n\nString inputValueString;\n\nif (input.isLocalValueSet()) {\n inputValueString = (String)input.getValue(); //validated and converted already\n} else {\n inputValueString = (String)input.getSubmittedValue(); //raw input\n}\n .getSubmittedValue() .getValue()" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ]
260,122
<p>I am trying to add a "title" element but am getting a NO_MODIFICATION_ALLOWED_ERR error...</p> <pre><code>private static void saveDoc(String f) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); // create DOMSource for source XML document DOMSource xmlSource = new DOMSource(doc); Node nextNode = xmlSource.getNode().getFirstChild(); while (nextNode != null) { System.out.print("\n node name: " + nextNode.getNodeName() + "\n"); if (nextNode.getNodeName().equals("map")) { nextNode.appendChild(doc.createElement("title")); </code></pre> <p><strong>the line above is throwing error:</strong></p> <blockquote> <p>Exception in thread "main" org.w3c.dom.DOMException: <code>NO_MODIFICATION_ALLOWED_ERR</code>: An attempt is made to modify an object where modifications are not allowed. at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(Unknown Source) at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(Unknown Source) at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source) at myProject.Main.saveDoc(Main.java:171) at myProject.Main.main(Main.java:48)</p> </blockquote> <pre><code> break; } nextNode = nextNode.getNextSibling(); } } </code></pre> <p>My xml file looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?dctm xml_app="LOPackage"?&gt; &lt;!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "file:C:/Documents%20and%20Settings/joe/Desktop//LOPackage/map.dtd"&gt; &lt;map xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- map/map " ditaarch:DITAArchVersion="1.1" domains="(map mapgroup-d) (topic indexing-d)"&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002504?DMS_OBJECT_SPEC=RELATION_ID" type="Le"/&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002505?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002506?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/&gt; &lt;/map&gt; </code></pre>
[ { "answer_id": 260178, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 0, "selected": false, "text": "Document newDoc = doc.cloneNode(true);\n newDoc.setReadOnly(false,true);\n// ^^^^ also sets children\n" }, { "answer_id": 261550, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 3, "selected": true, "text": "nextNode.appendChild(doc.createTextNode(\"title\"));\n map Element title = doc.createElement(\"title\");\ntitle.appendChild(doc.createTextNode(\"title content\"))\nnextNode.appendChild(title);\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
260,125
<p>You'll have to forgive my ignorance, but I'm not used to using wide character sets in c++, but is there a way that I can use wide string literals in c++ without putting an L in front of each literal?</p> <p>If so, how?</p>
[ { "answer_id": 260135, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "const char* const wchar_t* TEXT() \n#ifdef UNICODE\n#define TEXT(s) L ## s\n#else\n#define TEXT(s) s\n#endif\n _T() TEXT()" }, { "answer_id": 480185, "author": "ShoeLace", "author_id": 3825, "author_profile": "https://Stackoverflow.com/users/3825", "pm_score": 2, "selected": false, "text": "#define get_switch( m ) myclass::getSwitch(L##m)\n get_switch(isrunning)\n myclass::getswitch(L\"isrunning\")\n error: 'L' was not defined in this scope.\n #define get_switch( m ) myclass::getSwitch(L ## #m)\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23553/" ]
260,150
<p>I am trying to use an XML-RPC server on my Drupal (PHP) backend to make it easier for my Perl backend to talk to it. However, I've run into an issue and I'm not sure which parts, if any, are bugs. Essentially, some of the variables I need to pass to Drupal are strings that sometimes are strings full of numbers and the Drupal XML-RPC server is returning an error that when a string is full of numbers it is not properly formed.</p> <p>My Perl code looks something like this at the moment.</p> <pre><code>use strict; use warnings; use XML::RPC; use Data::Dumper; my $xmlrpc = XML::RPC-&gt;new(URL); my $result = $xmlrpc-&gt;call( FUNCTION, 'hello world', '9876352345'); print Dumper $result; </code></pre> <p>The output is:</p> <pre><code>$VAR1 = { 'faultString' =&gt; 'Server error. Invalid method parameters.', 'faultCode' =&gt; '-32602' }; </code></pre> <p>When I have the Drupal XML-RPC server print out the data it receives, I notice that the second argument is typed as i4:</p> <pre><code>&lt;param&gt; &lt;value&gt; &lt;i4&gt;9876352345&lt;/i4&gt; &lt;/value&gt; </code></pre> <p>I think when Drupal then finishes processing the item, it is typing that variable as an int instead of a string. This means when Drupal later tries to check that the variable value is properly formed for a string, the is_string PHP function returns false.</p> <pre><code>foreach ($signature as $key =&gt; $type) { $arg = $args[$key]; switch ($type) { case 'int': case 'i4': if (is_array($arg) || !is_int($arg)) { $ok = FALSE; } break; case 'base64': case 'string': if (!is_string($arg)) { $ok = FALSE; } break; case 'boolean': if ($arg !== FALSE &amp;&amp; $arg !== TRUE) { $ok = FALSE; } break; case 'float': case 'double': if (!is_float($arg)) { $ok = FALSE; } break; case 'date': case 'dateTime.iso8601': if (!$arg-&gt;is_date) { $ok = FALSE; } break; } if (!$ok) { return xmlrpc_error(-32602, t('Server error. Invalid method parameters.')); } } </code></pre> <p>What I'm not sure about is on which side of the divide the issue lies or if there is something else I should be using. Should the request from the Perl side be typing the content as a string instead of i4 or is the Drupal side of the request too stringent for the string type? My guess is that the issue is the latter, but I don't know enough about how an XML-RPC server is supposed to work to know for sure.</p>
[ { "answer_id": 260283, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 1, "selected": false, "text": "9876352345" }, { "answer_id": 260289, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "my $result =\n $xmlrpc->call( FUNCTION, 'hello world', $xmlrpc->string('9876352345') );\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31240/" ]
260,165
<p>A colleague is looking to generate UML class diagrams from heaps of Python source code. He's primarily interested in the inheritance relationships, and mildly interested in compositional relationships, and doesn't care much about class attributes that are just Python primitives.</p> <p>The source code is pretty straightforward and not tremendously evil--it doesn't do any fancy metaclass magic, for example. (It's mostly from the days of Python 1.5.2, with some sprinklings of "modern" 2.3ish stuff.) </p> <p>What's the best existing solution to recommend?</p>
[ { "answer_id": 7554457, "author": "Nicolas Chauvat", "author_id": 964956, "author_profile": "https://Stackoverflow.com/users/964956", "pm_score": 8, "selected": false, "text": "pyreverse -o png -p yourpackage .\n ." } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16056/" ]
260,195
<p>I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run. So far I have:</p> <pre><code>SELECT startTime, endTime, cast(datediff(hh,starttime,endtime) as varchar) +':' +cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME FROM applog WHERE runID = 33871 ORDER BY startTime DESC </code></pre> <p>When I execute this I get expected values and also some unexpected. For example, if starttime = 2008-11-02 15:59:59.790 and endtime = 2008-11-02 19:05:41.857 then the runtime is = 4:-54. How do I get a quere in MS SQL SMS to return the value 3:06 for this case?</p> <p>Thanks.</p> <p>Eoin Campbell's I selected as the answer is the most bulletproof for my needs. David B's is do-able as well.</p>
[ { "answer_id": 260209, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "-- Find Hours, Minutes and Seconds in between two datetime\nDECLARE @First datetime\nDECLARE @Second datetime\nSET @First = '04/02/2008 05:23:22'\nSET @Second = getdate()\n\nSELECT DATEDIFF(day,@First,@Second)*24 as TotalHours,\nDATEDIFF(day,@First,@Second)*24*60 as TotalMinutes,\nDATEDIFF(day,@First,@Second)*24*60*60 as TotalSeconds\n" }, { "answer_id": 260220, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "DECLARE @applog TABLE\n(\n runID int,\n starttime datetime,\n endtime datetime\n)\n\nINSERT INTO @applog (runID, starttime, endtime)\nSELECT 33871, '2008-11-02 15:59:59.790', '2008-11-02 19:05:41.857'\n-------------------\nSELECT\n SUBSTRING(convert(varchar(30), DateAdd(mi, duration, 0), 121),\n 12, 5) as prettyduration\nFROM\n(\nSELECT starttime, DateDiff(mi, starttime, endtime) as duration\nFROM @applog\nWHERE runID = 33871\n) as sub\n" }, { "answer_id": 260234, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": true, "text": "declare @start datetime\nset @start = '2008-11-02 15:59:59.790'\n\ndeclare @end datetime\nset @end = '2008-11-02 19:05:41.857'\n select \n (datediff(ss, @start, @end) / 3600), \n (datediff(ss, @start, @end) / 60) % 60,\n (datediff(ss, @start, @end) % 60) % 60\n\n--returns\n\n----------- ----------- -----------\n3 5 42\n select\nRIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 3600)), 2) + ':' +\nRIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 60) % 60), 2) + ':' +\nRIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) % 60) % 60), 2)\n\n--------\n03:05:42\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33727/" ]
260,210
<p>I'm using jQuery and wanting to target the nth &lt;li&gt; in a list after clicking the nth link.</p> <pre><code>&lt;ul id="targetedArea"&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="clickedItems"&gt; &lt;a&gt;&lt;/a&gt; &lt;a&gt;&lt;/a&gt; &lt;a&gt;&lt;/a&gt; &lt;a&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I can target them individually, but I know there must be a faster way by passing which &lt;a&gt; element I clicked on.</p> <pre><code>$("#clickedItem a:eq(2)").click(function() { $("#targetedArea:eq(2)").addClass('active'); return false; }); </code></pre> <p>Cheers,<br /> Steve </p>
[ { "answer_id": 260242, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "$('#clickedItems a').click(function() {\n// figure out what position this element is in\n var n = $('#clickedItems a').index($(this) );\n// update the targetedArea\n $('#targetedArea li:eq('+n+')').html('updated!');\n return false;\n});\n <a> <li> <li>" }, { "answer_id": 260278, "author": "ken", "author_id": 20300, "author_profile": "https://Stackoverflow.com/users/20300", "pm_score": 0, "selected": false, "text": "$$('a.clickedItems').addEvent('click', function(e){\n e.preventDefault();\n $('targetedArea').getChildren()[this.getAllPrevious().length].addClass('selected');\n});\n" }, { "answer_id": 260284, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "$('#clickedItems a').click(function() {\n // you probably want to turn off the currently active one\n $('#targetedArea li.active').removeClass(\"active\");\n\n // count the links previous to this one and make the corresponding li active\n $('#targetedArea li:eq(' + $(this).prevAll('a').length + ')').addClass(\"active\");\n\n // prevent the browser from going to the link\n return false;\n});\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16124/" ]
260,217
<p>How can i draw a dotted line in .NET/WinForms/GDI+?</p> <pre><code>Pen p = new Pen (Color.Black) </code></pre> <p>gives me only solid line pen. </p> <p>I am trying to have a dotted (or dashed) lines; can't seem to be able to google it up successfully.</p> <p>Will much appreciate any help on this one.</p>
[ { "answer_id": 260221, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 6, "selected": true, "text": "p.DashStyle = DashStyle.Dash;\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19584/" ]
260,229
<p>I want to select records that are 1 month old or newer.</p> <p>The query is: SELECT * FROM foobar WHERE created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)</p> <p>Using Propel in Symfony, I do:</p> <blockquote> <p>$c = new Criteria<br> $c->add(FoobarPeer::CREATED_AT, "DATE_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::GREATER_THAN); </p> </blockquote> <p>What Propel generates is: SELECT * FROM foobar WHERE created_at > 'DATE_SUB(curdate(), INTERVAL 1 MONTH)' - in other words, it puts the MySQL function in single quotes, which makes it a (meaningless) string and I get no records.</p> <p>What I've done for now is:</p> <blockquote> <p>$c->add(FoobarPeer::CREATED_AT, "created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::CUSTOM); </p> </blockquote> <p>But I don't want to use custom workarounds unless I have to. Any hints besides using Criteria::CUSTOM?</p>
[ { "answer_id": 260263, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": true, "text": "$con = Propel::getConnection(DATABASE_NAME);\n\n$sql = \"SELECT foobar.* FROM foobar WHERE created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)\"; \n$stmt = $con->prepare($sql);\n$stmt->execute();\n\n$books = FoobarPeer::populateObjects($stmt);\n" }, { "answer_id": 260354, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 1, "selected": false, "text": "$monthAgo = '2008-10-03';\n$c = new Criteria\n$c->add(FoobarPeer::CREATED_AT, $monthAgo, Criteria::GREATER_THAN); \n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2706/" ]
260,233
<p>I've created a Visual Basic WPF Application project that contains Toy.edmx, an ADO.NET Entity Data Model generated from a database called Toy.</p> <p>Its <em>Window1.xaml.vb</em> file looks like this:</p> <pre> 1 Class Window1 2 3 Private Sub Window1_Loaded( _ 4 ByVal sender As System.Object, _ 5 ByVal e As System.Windows.RoutedEventArgs) _ 6 Handles MyBase.Loaded 7 8 Dim dc As New ToyEntities1 9 Label1.Content = (From c As Client In dc.ClientSet _ 10 Select c).First.FirstName 11 12 End Sub 13 14 End Class </pre> <p>That runs just fine.</p> <p>But, if I add the file <em>Client.vb</em>...</p> <pre> 1 Partial Public Class Client 2 Function IsWashington() As Boolean 3 Return Me.LastName = "Washington" 4 End Function 5 End Class </pre> <p>...and add a WHERE clause to my <em>Window1.xaml.vb</em> query...</p> <pre> 9 Label1.Content = (From c As Client In dc.ClientSet _ 10 Where c.IsWashington _ 11 Select c).First.FirstName </pre> <p>...then I get this NotSupportedException:</p> <blockquote> <p>LINQ to Entities does not recognize the method 'Boolean IsWashington()' method, and this method cannot be translated into a store expression.</p> </blockquote> <p>How do I extend ADO.NET Entity Framework objects with partial classes?</p>
[ { "answer_id": 260784, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "Partial Public Class Client\n Public Shared Function IsWashington(query As IQueryable(Of Client)) As IQueryable(Of Client)\n Return query.Where(Function(someClient) someClient.LastName = \"Washington\")\n End Function\nEnd Class\n IQueryable(Of Client) someQuery = dc.ClientSet.AsQueryable\nsomeQuery = Client.IsWashington(someQuery)\n\nLabel1.Content = someQuery.First.FirstName\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
260,235
<p>Consider the following simple C program that read a file into a buffer and displays that buffer to the console:</p> <pre><code>#include&lt;stdio.h&gt; main() { FILE *file; char *buffer; unsigned long fileLen; //Open file file = fopen("HelloWorld.txt", "rb"); if (!file) { fprintf(stderr, "Unable to open file %s", "HelloWorld.txt"); return; } //Get file length fseek(file, 0, SEEK_END); fileLen=ftell(file); fseek(file, 0, SEEK_SET); //Allocate memory buffer=(char *)malloc(fileLen+1); if (!buffer) { fprintf(stderr, "Memory error!"); fclose(file); return; } //Read file contents into buffer fread(buffer, fileLen, 1, file); //Send buffer contents to stdout printf("%s\n",buffer); fclose(file); } </code></pre> <p>The file it will read simply contains: </p> <blockquote> <p>Hello World!</p> </blockquote> <p>The output is:</p> <blockquote> <p>Hello World!²²²²▌▌▌▌▌▌▌↔☺</p> </blockquote> <p>It has been a while since I did anything significant in C/C++, but normally I would assume the buffer was being allocated larger than necessary, but this does not appear to be the case. </p> <p>fileLen ends up being 12, which is accurate.</p> <p>I am thinking now that I must just be displaying the buffer wrong, but I am not sure what I am doing wrong. </p> <p>Can anyone clue me in to what I am doing wrong?</p>
[ { "answer_id": 260243, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 6, "selected": true, "text": "buffer[fileLen] = 0;\n" }, { "answer_id": 260300, "author": "George Eadon", "author_id": 30530, "author_profile": "https://Stackoverflow.com/users/30530", "pm_score": 5, "selected": false, "text": "printf printf(\"%.*s\\n\", fileLen, buffer);\n" }, { "answer_id": 2076025, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 0, "selected": false, "text": "calloc malloc calloc calloc char 1 buffer = calloc (fileLen + 1, 1);\n malloc calloc calloc malloc" }, { "answer_id": 2076043, "author": "Alok Singhal", "author_id": 226621, "author_profile": "https://Stackoverflow.com/users/226621", "pm_score": 2, "selected": false, "text": "ftell() \"b\" fopen() ftell() char ftell() fseek() \"b\" fopen() fseek(file, 0, SEEK_END) fread() realloc() mmap()" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5640/" ]
260,236
<p>I know that php has md5(), sha1(), and the hash() functions, but I want to create a hash using the MySQL PASSWORD() function. So far, the only way I can think of is to just query the server, but I want a function (preferably in php or Perl) that will do the same thing without querying MySQL at all.</p> <p>For example:</p> <p>MySQL hash -> 464bb2cb3cf18b66</p> <p>MySQL5 hash -> *01D01F5CA7CA8BA771E03F4AC55EC73C11EFA229</p> <p>Thanks!</p>
[ { "answer_id": 1543873, "author": "defines", "author_id": 120990, "author_profile": "https://Stackoverflow.com/users/120990", "pm_score": 5, "selected": false, "text": "// The following is free for any use provided credit is given where due.\n// This code comes with NO WARRANTY of any kind, including any implied warranty.\n\n/**\n * MySQL \"OLD_PASSWORD()\" AKA MySQL323 HASH FUNCTION\n * This is the password hashing function used in MySQL prior to version 4.1.1\n * By Defines Fineout 10/9/2009 9:12:16 AM\n**/\nfunction mysql_old_password_hash($input, $hex = true)\n{\n $nr = 1345345333; $add = 7; $nr2 = 0x12345671; $tmp = null;\n $inlen = strlen($input);\n for ($i = 0; $i < $inlen; $i++) {\n $byte = substr($input, $i, 1);\n if ($byte == ' ' || $byte == \"\\t\") continue;\n $tmp = ord($byte);\n $nr ^= ((($nr & 63) + $add) * $tmp) + (($nr << 8) & 0xFFFFFFFF);\n $nr2 += (($nr2 << 8) & 0xFFFFFFFF) ^ $nr;\n $add += $tmp;\n }\n $out_a = $nr & ((1 << 31) - 1);\n $out_b = $nr2 & ((1 << 31) - 1);\n $output = sprintf(\"%08x%08x\", $out_a, $out_b);\n if ($hex) return $output;\n return hex_hash_to_bin($output);\n} //END function mysql_old_password_hash\n\n/**\n * MySQL \"PASSWORD()\" AKA MySQLSHA1 HASH FUNCTION\n * This is the password hashing function used in MySQL since version 4.1.1\n * By Defines Fineout 10/9/2009 9:36:20 AM\n**/\nfunction mysql_password_hash($input, $hex = true)\n{\n $sha1_stage1 = sha1($input, true);\n $output = sha1($sha1_stage1, !$hex);\n return $output;\n} //END function mysql_password_hash\n\n/**\n * Computes each hexidecimal pair into the corresponding binary octet.\n * Similar to mysql hex2octet function.\n**/\nfunction hex_hash_to_bin($hex)\n{\n $bin = \"\";\n $len = strlen($hex);\n for ($i = 0; $i < $len; $i += 2) {\n $byte_hex = substr($hex, $i, 2);\n $byte_dec = hexdec($byte_hex);\n $byte_char = chr($byte_dec);\n $bin .= $byte_char;\n }\n return $bin;\n} //END function hex_hash_to_bin\n" }, { "answer_id": 5576372, "author": "TFBW", "author_id": 341930, "author_profile": "https://Stackoverflow.com/users/341930", "pm_score": 1, "selected": false, "text": "use Digest::SHA1 qw(sha1 sha1_hex);\nsub password { \"*\".uc(sha1_hex(sha1($_[0]))) }\n" }, { "answer_id": 8634675, "author": "Kerem", "author_id": 362780, "author_profile": "https://Stackoverflow.com/users/362780", "pm_score": 3, "selected": false, "text": "function mysql_41_password($in) {\n $p = sha1($in, true);\n $p = sha1($p);\n return '*'. strtoupper($p);\n} \n" }, { "answer_id": 9208686, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "PHRASE=\"password\"; P1=`echo -n \"${PHRASE}\"|sha1sum`; P2=\"*`echo -en $(echo -n ${P1%% *}|sed -E 's/([0-9a-f]{2})/\\\\\\x\\1/g')|sha1sum -b`\"; PASS=\"${P2%% *}\"; echo \"${PASS^^}\"\n" }, { "answer_id": 49433597, "author": "Matthew Lenz", "author_id": 2051257, "author_profile": "https://Stackoverflow.com/users/2051257", "pm_score": 0, "selected": false, "text": "sub old_hash_password {\n my ($password) = @_;\n\n my $nr = 1345345333;\n my $nr2 = 0x12345671;\n my $add = 7;\n\n for (my $i = 0; $i < length($password); $i++) {\n my $byte = substr($password, $i, 1);\n\n next if ($byte eq ' ' || $byte eq \"\\t\");\n\n my $ord_b = ord($byte);\n $nr ^= ((($nr & 63) + $add) * $ord_b) + (($nr << 8) & 0xFFFFFFFF);\n $nr2 += (($nr2 << 8) & 0xFFFFFFFF) ^ $nr;\n $add += $ord_b;\n }\n\n my $out_a = $nr & ((1 << 31) - 1);\n my $out_b = $nr2 & ((1 << 31) - 1);\n\n return sprintf(\"%08x%08x\", $out_a, $out_b);\n}\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
260,252
<p>I have a web-app that I would like to extend to support multiple languages with new URLs. For example, www.example.com/home.do stays English, but www.example.com/es/home.do is Spanish. My first thought was to create a Filter which rewrites incoming urls like /es/home.do to /home.do (and sets the Locale in the Request); this works fine. The Filter wraps the ServletRequest with an HttpServletRequestWrapper which overrides getContextPath() to return the language:</p> <pre><code>class FakeContextRequest extends HttpServletRequestWrapper { private String context = ""; FakeContextRequest(HttpServletRequest request, String context) { super(request); // snip some validation code this.context = request.getContextPath() + context; } @Override public String getContextPath() { return this.context; } } </code></pre> <p>My Filter forwards to the appropriate request as follows:</p> <pre><code>FakeContextRequest fr = new FakeContextRequest(request, lang); fr.getRequestDispatcher(newResourceName).forward(fr, response); </code></pre> <p>My problem is that the next servlet doesn't forward properly. The next servlet (typically a Struts ActionServlet) forwards to a JSP (often using Struts Tiles); when I get to the JSP the HttpServletRequest has been wrapped several times and the object in question reports the context to be empty (the root context, which is where the application is actually deployed).</p> <p>I want the context to be re-written so that all my context-aware code that already exists can automatically insert the language into the URLs that are written. Is this possible?</p> <p><strong>Edit:</strong> I solved my problem by using a wrapped HttpServletResponse instead of a wrapped HttpServletRequest; I rewrite the URL in the response.encodeURL() method.</p>
[ { "answer_id": 260371, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": true, "text": "getContextPath() ServletContext.getContextPath() getRequestURI()" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867/" ]
260,253
<p>A little example</p> <pre><code>TTest&lt;T&gt; = class private f : T; public function ToString : string; end; </code></pre> <p>If is an object then this should work</p> <pre><code>TTest&lt;T&gt;.ToString; begin Result := f.ToString; end; </code></pre> <p>But what happens when is say an integer? This would be ok in .net. of course.</p> <p>I know it won't work, but how do I code this to work with objects AND simple types?</p>
[ { "answer_id": 260266, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "TTest<T: TObject>.ToString;\nbegin\n Result := T.ToString;\nend;\n type\n TToString<T> = reference to function(const AValue: T): string;\n TGenContainer<T> = class\n private\n FValue: T;\n FToString : TToString<T>;\n public\n constructor Create(const AToString: TToString<T>);\n\n function ToString: string;\n\n property Value: T read FValue write FValue;\n end;\n\nconstructor TGenContainer<T>.Create(const AToString: TToString<T>);\nbegin\n FToString := AToString;\nend;\n\nfunction TGenContainer<T>.ToString: string;\nbegin\n Result := FToString(FValue);\nend;\n\n\n\nprocedure TForm2.Button1Click(Sender: TObject);\nvar\n gen : TGenContainer<Integer>;\nbegin\n gen := TGenContainer<Integer>.Create(\n function(const AValue: Integer): string\n begin\n Result := IntToStr(AValue);\n end);\n try\n gen.Value := 17;\n Memo1.Lines.Add(gen.ToString);\n finally\n gen.Free;\n end;\nend;\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
260,254
<p>I'm writing a simple C++ class in which I would like cache picture thumbnails versions of images downloaded from the web. As such, I would like to use a hash function which takes in URL strings and outputs a unique string suitable as a filename.</p> <p>Is there a simple way to do this without re-writing the function myself? I searched around for a simple library, but couldn't find anything. Surely this is a common problem.</p>
[ { "answer_id": 260262, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": true, "text": "#include <cctype>\n\nchar *safe_url(const char *str) {\n char *safe = strdup(str);\n for (int i = 0; i < strlen(str); i++) {\n if (isalpha(str[i]))\n safe[i] = str[i];\n else\n safe[i] = '_';\n }\n}\n" }, { "answer_id": 260268, "author": "John", "author_id": 13895, "author_profile": "https://Stackoverflow.com/users/13895", "pm_score": 0, "selected": false, "text": "boost::hash" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33791/" ]
260,260
<p>I'm in need of a macro that will enter data into a webpage search field and than copy the results to excel.</p>
[ { "answer_id": 260297, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 2, "selected": false, "text": "http://finance.yahoo.com/q?s=MSFT" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33792/" ]
260,270
<p>Folks,</p> <p>I am pulling all my Flash (pure AS3 project, not Flash CS3) content from a Drupal back-end for SEO purposes. This works great, except the HTML rendering built into the TextField object leaves a lot to be desired. Could anyone recommend any libraries that would allow me to display HTML elements? At this stage, commercial or open-source libraries are welcome.</p> <p>Thanks, Marcus</p>
[ { "answer_id": 329914, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 2, "selected": false, "text": "DisplayObject flash.html.HTMLLoader HTMLLoader" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
260,273
<p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p> <pre><code>s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND" </code></pre>
[ { "answer_id": 260312, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 3, "selected": false, "text": "file_handle = open(\"somefile\")\nfile_size = file_handle.tell()\nfile_handle.seek(max(file_size - 2*1024, 0))\n\n# this will get rid of trailing newlines, unlike readlines()\nlast_10 = file_handle.read().splitlines()[-10:]\n\nassert len(last_10) == 10, \"Only read %d lines\" % len(last_10)\n" }, { "answer_id": 260352, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 6, "selected": true, "text": "# Tail\nfrom __future__ import with_statement\n\nfind_str = \"FIREFOX\" # String to find\nfname = \"g:/autoIt/ActiveWin.log_2\" # File to check\n\nwith open(fname, \"r\") as f:\n f.seek (0, 2) # Seek @ EOF\n fsize = f.tell() # Get Size\n f.seek (max (fsize-1024, 0), 0) # Set pos @ last n chars\n lines = f.readlines() # Read to end\n\nlines = lines[-10:] # Get last 10 lines\n\n# This returns True if any line is exactly find_str + \"\\n\"\nprint find_str + \"\\n\" in lines\n\n# If you're searching for a substring\nfor line in lines:\n if find_str in line:\n print True\n break\n" }, { "answer_id": 260359, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "def lastNLines(file, N=10, chunksize=1024):\n lines = None\n file.seek(0,2) # go to eof\n size = file.tell()\n for pos in xrange(chunksize,size-1,chunksize):\n # read a chunk\n file.seek(pos,2)\n chunk = file.read(chunksize)\n if lines is None:\n # first time\n lines = chunk.splitlines()\n else:\n # other times, update the 'first' line with\n # the new data, and re-split\n lines[0:1] = (chunk + lines[0]).splitlines()\n if len(lines) > N:\n return lines[-N:]\n file.seek(0)\n chunk = file.read(size-pos)\n lines[0:1] = (chunk + lines[0]).splitlines()\n return lines[-N:]\n def iter_lines_reversed(file, chunksize=1024):\n file.seek(0,2)\n size = file.tell()\n last_line = \"\"\n for pos in xrange(chunksize,size-1,chunksize):\n # read a chunk\n file.seek(pos,2)\n chunk = file.read(chunksize) + last_line\n # split into lines\n lines = chunk.splitlines()\n last_line = lines[0]\n # iterate in reverse order\n for index,line in enumerate(reversed(lines)):\n if index > 0:\n yield line\n # handle the remaining data at the beginning of the file\n file.seek(0)\n chunk = file.read(size-pos) + last_line\n lines = chunk.splitlines()\n for line in reversed(lines):\n yield line\n s = \"foo\"\nfor index, line in enumerate(iter_lines_reversed(fileObj)):\n if line == s:\n print \"FOUND\"\n break\n elif index+1 >= 10:\n break\n" }, { "answer_id": 260407, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "os.popen(\"tail -10 \" + filepath).readlines() tail" }, { "answer_id": 260433, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 5, "selected": false, "text": "import os\n\ndef reversed_lines(file):\n \"Generate the lines of file in reverse order.\"\n part = ''\n for block in reversed_blocks(file):\n for c in reversed(block):\n if c == '\\n' and part:\n yield part[::-1]\n part = ''\n part += c\n if part: yield part[::-1]\n\ndef reversed_blocks(file, blocksize=4096):\n \"Generate blocks of file's contents in reverse order.\"\n file.seek(0, os.SEEK_END)\n here = file.tell()\n while 0 < here:\n delta = min(blocksize, here)\n here -= delta\n file.seek(here, os.SEEK_SET)\n yield file.read(delta)\n from itertools import islice\n\ndef check_last_10_lines(file, key):\n for line in islice(reversed_lines(file), 10):\n if line.rstrip('\\n') == key:\n print 'FOUND'\n break\n" }, { "answer_id": 260648, "author": "user32716", "author_id": 32716, "author_profile": "https://Stackoverflow.com/users/32716", "pm_score": 2, "selected": false, "text": "!/usr/bin/env python\n# -*-mode: python; coding: iso-8859-1 -*-\n#\n# Copyright (c) Peter Astrand <astrand@cendio.se>\n\nimport os\nimport string\n\nclass BackwardsReader:\n \"\"\"Read a file line by line, backwards\"\"\"\n BLKSIZE = 4096\n\n def readline(self):\n while 1:\n newline_pos = string.rfind(self.buf, \"\\n\")\n pos = self.file.tell()\n if newline_pos != -1:\n # Found a newline\n line = self.buf[newline_pos+1:]\n self.buf = self.buf[:newline_pos]\n if pos != 0 or newline_pos != 0 or self.trailing_newline:\n line += \"\\n\"\n return line\n else:\n if pos == 0:\n # Start-of-file\n return \"\"\n else:\n # Need to fill buffer\n toread = min(self.BLKSIZE, pos)\n self.file.seek(-toread, 1)\n self.buf = self.file.read(toread) + self.buf\n self.file.seek(-toread, 1)\n if pos - toread == 0:\n self.buf = \"\\n\" + self.buf\n\n def __init__(self, file):\n self.file = file\n self.buf = \"\"\n self.file.seek(-1, 2)\n self.trailing_newline = 0\n lastchar = self.file.read(1)\n if lastchar == \"\\n\":\n self.trailing_newline = 1\n self.file.seek(-1, 2)\n\n# Example usage\nbr = BackwardsReader(open('bar'))\n\nwhile 1:\n line = br.readline()\n if not line:\n break\n print repr(line)\n" }, { "answer_id": 260973, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 3, "selected": false, "text": "mmap mmap import os\nfrom mmap import mmap\n\ndef lastn(filename, n):\n # open the file and mmap it\n f = open(filename, 'r+')\n m = mmap(f.fileno(), os.path.getsize(f.name))\n\n nlcount = 0\n i = m.size() - 1 \n if m[i] == '\\n': n += 1\n while nlcount < n and i > 0:\n if m[i] == '\\n': nlcount += 1\n i -= 1\n if i > 0: i += 2\n\n return m[i:].splitlines()\n\ntarget = \"target string\"\nprint [l for l in lastn('somefile', 10) if l == target]\n" }, { "answer_id": 262921, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 0, "selected": false, "text": "def getLastLines (path, n):\n # return the las N lines from the file indicated in path\n\n fp = open(path)\n for i in range(n):\n line = fp.readline()\n if line == '':\n return []\n\n back = open(path)\n for each in fp:\n back.readline()\n\n result = []\n for line in back:\n result.append(line[:-1])\n\n return result\n\n\n\n\ns = \"foo\"\nlast_bit = getLastLines(r'C:\\Documents and Settings\\ricardo.m.reyes\\My Documents\\desarrollo\\tail.py', 10)\nfor line in last_bit:\n if line == s:\n print \"FOUND\"\n" }, { "answer_id": 262988, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 1, "selected": false, "text": "lines = 0\nchunk_size = 1024\n\nf = file('filename')\nf.seek(0, 2)\nf.seek(f.tell() - chunk_size)\n\nwhile True:\n s = f.read(chunk_size)\n lines += s.count('\\n')\n if lines > NUM_OF_LINES:\n break\n f.seek(f.tell() - chunk_size*2)\n readlines()" }, { "answer_id": 2436554, "author": "AM01", "author_id": 2574254, "author_profile": "https://Stackoverflow.com/users/2574254", "pm_score": 0, "selected": false, "text": "import os.path\n\npath = 'path_to_file'\nos.system('tail -n1 ' + path)\n" }, { "answer_id": 17841165, "author": "Edd", "author_id": 700673, "author_profile": "https://Stackoverflow.com/users/700673", "pm_score": 2, "selected": false, "text": "mmap rfind from mmap import mmap\nimport sys\n\ndef reverse_file(f):\n mm = mmap(f.fileno(), 0)\n nl = mm.size() - 1\n prev_nl = mm.size()\n while nl > -1:\n nl = mm.rfind('\\n', 0, nl)\n yield mm[nl + 1:prev_nl]\n prev_nl = nl + 1\n\ndef main():\n # Example usage\n with open('test.txt', 'r+') as infile:\n for line in reverse_file(infile):\n sys.stdout.write(line)\n" }, { "answer_id": 51750850, "author": "asterio gonzalez", "author_id": 6924622, "author_profile": "https://Stackoverflow.com/users/6924622", "pm_score": 2, "selected": false, "text": "class ReverseFile(io.IOBase):\n def __init__ (self, filename, headers=1):\n self.fp = open(filename)\n self.headers = headers\n self.reverse = self.reversed_lines()\n self.end_position = -1\n self.current_position = -1\n\n def readline(self, size=-1):\n if self.headers > 0:\n self.headers -= 1\n raw = self.fp.readline(size)\n self.end_position = self.fp.tell()\n return raw\n\n raw = next(self.reverse)\n if self.current_position > self.end_position:\n return raw\n\n raise StopIteration\n\n def reversed_lines(self):\n \"\"\"Generate the lines of file in reverse order.\n \"\"\"\n part = ''\n for block in self.reversed_blocks():\n block = block + part\n block = block.split('\\n')\n block.reverse()\n part = block.pop()\n if block[0] == '':\n block.pop(0)\n\n for line in block:\n yield line + '\\n'\n\n if part:\n yield part\n\n def reversed_blocks(self, blocksize=0xFFFF):\n \"Generate blocks of file's contents in reverse order.\"\n file = self.fp\n file.seek(0, os.SEEK_END)\n here = file.tell()\n while 0 < here:\n delta = min(blocksize, here)\n here -= delta\n file.seek(here, os.SEEK_SET)\n self.current_position = file.tell()\n yield file.read(delta)\n rev = ReverseFile(filename)\nfor i, line in enumerate(rev):\n print(\"{0}: {1}\".format(i, line.strip()))\n" }, { "answer_id": 69370560, "author": "Arpit", "author_id": 12423274, "author_profile": "https://Stackoverflow.com/users/12423274", "pm_score": -1, "selected": false, "text": "def read_last_n_lines_new(lines_need=10):\n\n with open('Log.txt', 'rb') as f:\n f.seek(0, 2)\n data = []\n lines_found = 0\n while True:\n try:\n f.seek(-1, 1)\n except:\n break\n finally:\n c = f.read(1)\n f.seek(-1, 1)\n if c == b'\\n':\n lines_found = lines_found+1\n if lines_found > lines_need or not c:\n break\n data.insert(0, c.decode('utf-8'))\n \n \n lines = []\n cur = \"\"\n for l in data:\n if(l == '\\n'):\n lines.append(cur)\n cur = ''\n else:\n cur = cur + l\n return lines\n\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057/" ]
260,285
<p>I've got a canvas that's 800x600 inside a window that's 300x300. When I press a certain key, I want it the canvas to move in that direction.<br> I've done this inside the window's code behind:</p> <pre> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); Key keyPressed = e.Key; if (keyPressed == Key.W) { gcY += 5; } if (keyPressed == Key.S) { gcY -= 5; } if (keyPressed == Key.A) { gcX += 5; } if (keyPressed == Key.D) { gcX -= 5; } gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY); } </pre> <p>Well, it works, but the movement is jerky. And if I hold on to a key, <kbd>W</kbd> for instance, then it pauses for a split second, before moving.<br> Is there anyway to make the movement smoother and to get rid of the pause when you hold down a key?<br> Thanks.</p>
[ { "answer_id": 260295, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 1, "selected": false, "text": "private static DateTime nextUpdate\n\nif (nextUpdate <= DateTime.Now)\n{\n//Move\nnextUpdate = DateTime.Now.AddMilliseconds(100);\n}\n" }, { "answer_id": 415016, "author": "Karan", "author_id": 11110, "author_profile": "https://Stackoverflow.com/users/11110", "pm_score": 3, "selected": true, "text": "keydown[256] false true gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY); true false" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33324/" ]
260,335
<p>How does an application perform a proximity search? For example, a user types in a postal code, then the application lists all the businesses within 20 miles ordered by proximity.</p> <p>I want to build something like that in PHP and MySQL. Is this approach correct?</p> <ol> <li>Get the addresses for locations I'm interested in and store in my database</li> <li>Geocode all the addresses with Google's geocoding service</li> <li>Write a database query that includes Haversine formula to do the proximity search and ordering </li> </ol> <p>Is this OK? In step 3, I'm going to calculate the proximity for every query. Is it better to have a PROXIMITY table that lists the distance between every business and a few reference locations?</p>
[ { "answer_id": 260430, "author": "wonderchook", "author_id": 32113, "author_profile": "https://Stackoverflow.com/users/32113", "pm_score": 4, "selected": false, "text": "SELECT\n [DistanceRadius]=\n 69.09 *\n DEGREES(\n ACOS(\n SIN( RADIANS(latitude) )*SIN( RADIANS(@ziplat) ) \n +\n COS( RADIANS(latitude) )*COS( RADIANS(@ziplat) ) \n *\n COS( RADIANS(longitude - (@ziplon)) )\n )\n )\n ,*\n FROM\n table\n\n ) sub\nWHERE\n sub.DistanceRadius < @radius\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27305/" ]
260,337
<p>Why does this test program result in a <code>java.lang.IllegalMonitorStateException</code>?</p> <pre><code>public class test { static Integer foo = new Integer(1); public static void main(String[] args) { synchronized(foo) { foo++; foo.notifyAll(); } System.err.println("Success"); } } </code></pre> <p>Result:</p> <pre><code>Exception in thread "main" java.lang.IllegalMonitorStateException at java.lang.Object.notifyAll(Native Method) at test.main(test.java:6) </code></pre>
[ { "answer_id": 260343, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 7, "selected": true, "text": "notifyAll notifyAll foo wait" }, { "answer_id": 260362, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "static Integer foo = new Integer(1);\n\npublic static void main(String[] args) {\n synchronized (foo) {\n foo.notifyAll();\n }\n System.out.println(\"Success\");\n}\n" }, { "answer_id": 5358011, "author": "Eric Leschinski", "author_id": 445131, "author_profile": "https://Stackoverflow.com/users/445131", "pm_score": 2, "selected": false, "text": "import java.util.concurrent.atomic.AtomicInteger;\n\npublic class SynchronizeOnAPrimitive {\n static AtomicInteger foo = new AtomicInteger(1);\n public static void main(String[] args) {\n synchronized (foo) {\n foo.incrementAndGet();\n foo.notifyAll();\n }\n System.out.println(\"foo is: \" + foo);\n }\n}\n foo is: 2\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29264/" ]
260,342
<p>I'm currently in the process of testing our solution that has the whole "gamut" of layers: UI, Middle, and the omnipresent Database.</p> <p>Before my arrival on my current team, query testing was done by the testers manually crafting queries that would theoretically return a result set that the stored procedure should return based on various relevancy rules, sorting, what have you.</p> <p>This had the side effect of bugs being filed against the tester's query more often than against the actual query in question.</p> <p>I proposed actually working with a known result set that you could just infer how it should return since you control the data present -- previously, data was pulled from production, sanitized, and then populated in our test databases.</p> <p>People were still insistent on creating their own queries to test what the developers have created. I suspect that many still are. I have it in my mind that this isn't ideal at all, and just increases our testing footprint needlessly.</p> <p>So, I'm curious, which practices do you use to test scenarios like this, and what would be considered ideal for the best end-to-end coverage you can get, without introducing chaotic data?</p> <p>The issue I have is where's the best place to do what testing. Do I just poke the service directly, and compare that dataset to that which I can pull from the stored procedure? I have a rough idea, and have been successful enough so far, but I feel like we're still missing something important here, so I'm looking to the community to see if they have any valuable insights that might help formulate my testing approach better.</p>
[ { "answer_id": 260608, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "TestCase TestCase" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14409/" ]
260,356
<p>I am experimenting for the first time with css layouts and my experience with CSS is very basic. What I want to achieve is a 2 column layout: left panel and content.<br> I have found this:</p> <pre><code>#leftcontent { position: absolute; left: 10px; top: 10px; width: 170px; border: 1px solid #C0C0C0; padding: 2px; } #centercontent { position: absolute; margin-left: 181px; border:1px solid #C0C0C0; top: 10px; //fix IE5 bug voice-family: "\"}\""; voice-family: inherit; margin-left: 181px; } </code></pre> <p>This displays great in firefox but the content in IE8 goes off the right of the screen, I assume by the length of the <code>#leftcontent</code>. How can I fix this?</p> <p>This is probably quite a simple fix but I have experimented and looked for fixes, but this supposedly should work. I appreciate any help.</p>
[ { "answer_id": 260364, "author": "Samir Talwar", "author_id": 20856, "author_profile": "https://Stackoverflow.com/users/20856", "pm_score": 3, "selected": true, "text": "#leftcontent {\n float: left;\n width:170px;\n border:1px solid #C0C0C0;\n padding: 2px;\n}\n\n#centercontent {\n margin-left: 181px;\n border:1px solid #C0C0C0;\n}\n" }, { "answer_id": 260384, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "float #leftcontent {\n float: left;\n margin-left: 10px;\n margin-top: 10px;\n width: 170px;\n border: 1px solid #C0C0C0;\n padding: 2px;\n}\n\n#centercontent {\n float: left;\n margin-left: 10px;\n border: 1px solid #C0C0C0;\n margin-top: 10px;\n}\n #contentbelow {\n clear: both;\n}\n" }, { "answer_id": 260471, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "float overflow" }, { "answer_id": 260624, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": false, "text": "colwrapper margin-...:auto footer clear:both ctrl and + or - #colwrapper{\n width:40em;\n margin-left:auto;\n margin-right:auto;\n}\n#colleft{\n float:left;\n width:10em;\n}\n#colright{\n float:right;\n width:30em\n}\n#footer{\n clear:both\n}\n <div id=\"colwrapper\">\n <div id=\"colleft\">\n left column!\n </div>\n <div id=\"colright\">\n right column!\n </div>\n <div id=\"footer\">\n footer!\n </div>\n</div>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
260,372
<p>I occasionally work on an old project that uses classic asp as a front end and an access database as a backend.</p> <p>I'd like to create a new column in one of the tables that contains logic to calculate its value from the other columns in the row.</p> <p>I know how to do this in a more modern DBMS, but I don't think that access supports it. Keep in mind I'm not using the access frontend, just the Jet DB engine via ODBC.</p> <p>Any pointers?</p>
[ { "answer_id": 260631, "author": "pro3carp3", "author_id": 7899, "author_profile": "https://Stackoverflow.com/users/7899", "pm_score": 2, "selected": false, "text": "SELECT Table1.Col_1, Table1.Col_2, [Col_1]*[Col_2] AS Col_3\nFROM Table1;\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
260,380
<p>I have a base class with an optional virtual function</p> <pre><code>class Base { virtual void OnlyImplementThisSometimes(int x) {} }; </code></pre> <p>When I compile this I get a warning about the unused param x. Is there some other way I should have implemented the virtual function? I have re-written it like this:</p> <pre><code>class Base { virtual void OnlyImplementThisSometimes(int x) { x = 0; } }; </code></pre> <p>I also have the problem that if I'm not careful, the subclass I make can implement the wrong function and then I don't notice because of overloading: e.g.</p> <pre><code>class Derived : public Base { void OnlyImplementThisSometimes(int x, int y) { // some code } }; Derived d; Base *b = dynamic_cast&lt;Base *&gt;(&amp;d); b-&gt;OnlyImplementThisSometimes(x); // calls the method in the base class </code></pre> <p>The base class method was called because I implemented the derived function with an "int y" param but there is no warning about this. Are these just common pitfalls in C++ or have I misunderstood virtual functions?</p>
[ { "answer_id": 260412, "author": "nlativy", "author_id": 33635, "author_profile": "https://Stackoverflow.com/users/33635", "pm_score": 6, "selected": true, "text": "virtual void OnlyImplementThisSometimes(int ) { }\n" }, { "answer_id": 260425, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 2, "selected": false, "text": "int func(int x)\n{\n (void) x;\n}\n" }, { "answer_id": 260431, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 2, "selected": false, "text": "class mouse_listener{\npublic:\n virtual ~mouse_listener() {}\n\n virtual void button_down(mouse_button a_Button) {}\n virtual void button_up(mouse_button a_Button) {}\n virtual void scroll_wheel(mouse_scroll a_Scroll) {}\n virtual void mouse_move_abs(math::point a_Position) {}\n virtual void mouse_move_rel(math::point a_Position) {}\n};\n" }, { "answer_id": 260480, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 2, "selected": false, "text": "Base *b = &d;\n dynamic_cast<> if((Derived *d = dynamic_cast<Derived *>(b)) != 0)\n{\n // use d\n}\n static_cast<>" }, { "answer_id": 260483, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 4, "selected": false, "text": "_unused #define _unused(x) ((void)x)\n virtual void OnlyImplementThisSometimes(int x) { _unused( x );}\n" }, { "answer_id": 261335, "author": "Tim Ring", "author_id": 3685, "author_profile": "https://Stackoverflow.com/users/3685", "pm_score": -1, "selected": false, "text": "class Base {\n virtual void OnlyImplementThisSometimes(int x) { x;}\n};\n" }, { "answer_id": 266618, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "class Base {\n virtual void OnlyImplementThisSometimes(int x) = 0;\n};\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20889/" ]
260,387
<p>I am using the code below to display all the files from a directory in a drop down menu. Does anyone know how to make this alphabetical? I presume it has something to do with the sort function, I just can't figure out how!</p> <pre><code>&lt;?php $dirname = "images/"; $images = scandir($dirname); $dh = opendir($dirname); while ($file = readdir($dh)) { if (substr($file, -4) == ".gif") { print "&lt;option value='$file'&gt;$file&lt;/option&gt;\n"; } } closedir($dh); ?&gt; </code></pre>
[ { "answer_id": 260400, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<?php\n\n$dirname = \"images/\";\n$images = scandir($dirname);\n\n// This is how you sort an array, see http://php.net/sort\nsort($images);\n\n// There's no need to use a directory handler, just loop through your $images array.\nforeach ($images as $file) {\n if (substr($file, -4) == \".gif\") {\n print \"<option value='$file'>$file</option>\\n\"; }\n }\n}\n\n?>\n 1,10,2,20 1,2,10,20" }, { "answer_id": 260451, "author": "William Macdonald", "author_id": 2725, "author_profile": "https://Stackoverflow.com/users/2725", "pm_score": 2, "selected": false, "text": "array scandir ( string $directory [, int $sorting_order [, resource $context ]] )\n" }, { "answer_id": 260556, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "$matches = glob(\"*.gif\");\nif ( is_array ( $matches ) ) {\n sort($matches);\n foreach ( $matches as $filename) {\n echo '<option value=\"'.$filename.'\">.$filename . \"</option>\";\n }\n}\n" }, { "answer_id": 261210, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 0, "selected": false, "text": "$sorting_order $images = scandir($dirname); $dh = opendir($dirname);\nwhile ($file = readdir($dh)) {\n if (substr($file, -4) == \".gif\") {\n print \"<option value='$file'>$file</option>\\n\"; \n }\n}\nclosedir($dh);\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32972/" ]
260,391
<p>I have an iphone app where I call these three functions in appDidFinishLaunching:</p> <pre><code>glMatrixMode(GL_PROJECTION); glOrthof(0, rect.size.width, 0, rect.size.height, -1, 1); glMatrixMode(GL_MODELVIEW); </code></pre> <p>When stepping through with the debugger I get EXC BAD ACCESS when I execute the first line. Any ideas why this is happening?</p> <p>Btw I have another application where I do the same thing and it works fine. So I've tried to duplicate everything in that app (#imports, adding OpenGLES framework, etc) but now I'm just stuck.</p>
[ { "answer_id": 266005, "author": "Brad Larson", "author_id": 19679, "author_profile": "https://Stackoverflow.com/users/19679", "pm_score": 3, "selected": true, "text": "context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];\n\nif (!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer]) \n{\n [self release];\n return nil;\n}\n - (BOOL)createFramebuffer \n{ \n glGenFramebuffersOES(1, &viewFramebuffer);\n glGenRenderbuffersOES(1, &viewRenderbuffer);\n\n glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);\n glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);\n [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];\n glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);\n\n glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);\n glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);\n\n if (USE_DEPTH_BUFFER) {\n glGenRenderbuffersOES(1, &depthRenderbuffer);\n glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);\n glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);\n glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);\n }\n\n if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) \n {\n return NO;\n }\n\n return YES;\n}\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
260,398
<p>I have a list of stores, departments within the stores, and sales for each department, like so (created using max(sales) in a subquery, but that's not terribly important here I don't think):</p> <pre><code>toronto baskets 500 vancouver baskets 350 halifax baskets 100 toronto noodles 275 vancouver noodles 390 halifax noodles 120 halifax fish 200 </code></pre> <p>I would like to ask for the highest-selling department at each store. The results should look like this:</p> <pre><code>toronto baskets 500 vancouver noodles 275 halifax fish 200 </code></pre> <p>Whenever I use GROUP BY, it includes all the listings from my subquery. Is there a nice clean way to do this without a temporary table?</p>
[ { "answer_id": 260419, "author": "Noah Yetter", "author_id": 30080, "author_profile": "https://Stackoverflow.com/users/30080", "pm_score": 2, "selected": false, "text": "select store\n , max(department) keep(dense_rank last order by sales)\n , max(sales)\n from (\n ...query that generates your results...\n )\n group by store\n" }, { "answer_id": 260467, "author": "Jeffrey Meyer", "author_id": 2323, "author_profile": "https://Stackoverflow.com/users/2323", "pm_score": 1, "selected": false, "text": "with data as\n(select store, department, sales\nfrom <your query>),\n maxsales as\n(select store, sales = max(sales)\nfrom data\ngroup by store)\nselect store, (select top 1 department from data where store = t.store and sales = t.sales order by [your criteria for ties]), sales\nfrom maxsales m\n" }, { "answer_id": 260469, "author": "Rockcoder", "author_id": 5290, "author_profile": "https://Stackoverflow.com/users/5290", "pm_score": 0, "selected": false, "text": "select yourTable.store, dept, sales\nfrom yourTable\njoin (\n select store, max(sales) as maxSales from yourTable group by store\n) tempTable on tempTable.store = yourTable.store \n and tempTable.maxSales = yourTable.sales\n" }, { "answer_id": 260473, "author": "Pete", "author_id": 76, "author_profile": "https://Stackoverflow.com/users/76", "pm_score": 2, "selected": false, "text": "SELECT a.Store, a.Department, a.Sales\nFROM temp a\nINNER JOIN \n(SELECT store, max(sales) as sales\nFROM temp\nGROUP BY Store) b\nON a.Store = b.Store AND a.Sales = b.Sales;\n" }, { "answer_id": 260513, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 0, "selected": false, "text": "SELECT Store, Department, Sales FROM\n(SELECT Store, Department, Sales,\nDENSE_RANK() OVER (PARTITION BY Store\nORDER BY Sales DESC) AS Dense_Rank\nFROM Sales) A WHERE Dense_Rank = 1\n" }, { "answer_id": 260524, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "Select Store, Department, Sales\nFrom yourTable A\nWhere Sales = (Select Max(Sales)\n From YourTable\n Where Store = A.Store)\n" }, { "answer_id": 261775, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 2, "selected": false, "text": "DECLARE @tbl as TABLE (store varchar(20), department varchar(20), sales int)\n\nINSERT INTO @tbl VALUES ('Toronto', 'Baskets', 500)\nINSERT INTO @tbl VALUES ('Toronto', 'Noodles', 500)\nINSERT INTO @tbl VALUES ('Toronto', 'Fish', 300)\nINSERT INTO @tbl VALUES ('Halifax', 'Fish', 300)\nINSERT INTO @tbl VALUES ('Halifax', 'Baskets', 200)\n\n-- Expect Toronto/Noodles/500 and Halifax/Fish/300\n\n;WITH ranked AS -- Rank the rows by sales from 1 to x\n(\n SELECT \n ROW_NUMBER() OVER (ORDER BY sales, store, department) as 'rank', \n store, department, sales\n FROM @tbl\n)\n\nSELECT store, department, sales\nFROM ranked\nWHERE rank in (\n SELECT max(rank) -- chose the highest ranked per store\n FROM ranked\n GROUP BY store\n)\n\n-- Another way\nSELECT store, department, sales\nFROM (\n SELECT \n DENSE_RANK() OVER (PARTITION BY store ORDER BY sales desc, \nstore desc, department desc) as 'rank',\n store, department, sales\n FROM @tbl\n) tbl\nWHERE rank = 1\n\n\n-- This will bring back 2 rows for Toronto\nselect tbl.store, department, sales\nfrom @tbl tbl\n join (\n select store, max(sales) as maxSales from @tbl group by store\n ) tempTable on tempTable.store = tbl.store \n and tempTable.maxSales = tbl.sales\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
260,399
<p>I know you cannot use a alias column in the where clause for T-SQL; however, has Microsoft provided some kind of workaround for this?</p> <blockquote> <p><strong>Related Questions:</strong> </p> <ul> <li><a href="https://stackoverflow.com/questions/200200/can-you-use-an-alias-in-the-where-clause-in-mysql">Unknown Column In Where Clause</a> </li> <li><a href="https://stackoverflow.com/questions/153598/unknown-column-in-where-clause">Can you use an alias in the WHERE clause in mysql?</a> </li> <li><a href="https://stackoverflow.com/questions/46354/invalid-column-name-error-on-sql-statement-from-openquery-results">“Invalid column name” error on SQL statement from OpenQuery results</a></li> </ul> </blockquote>
[ { "answer_id": 260437, "author": "Jim V.", "author_id": 33819, "author_profile": "https://Stackoverflow.com/users/33819", "pm_score": 6, "selected": true, "text": "select *\nfrom \n (\n select a + b as aliased_column\n from table\n ) dt\nwhere dt.aliased_column = something.\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
260,403
<p><strong>Short version</strong></p> <p>If I split my users into shards, how do I offer a "user search"? Obviously, I don't want every search to hit every shard.</p> <p><strong>Long version</strong></p> <p>By shard, I mean have multiple databases where each contains a fraction of the total data. For (a naive) example, the databases UserA, UserB, etc. might contain users whose names begin with "A", "B", etc. When a new user signs up, I simple examine his name and put him into the correct database. When a returning user signs in, I again look at his name to determine the correct database to pull his information from.</p> <p>The advantage of sharding vs read replication is that read replication does not scale your writes. All the writes that go to the master have to go to each slave. In a sense, they all carry the same write load, even though the read load is distributed.</p> <p>Meanwhile, shards do not care about each other's writes. If Brian signs up on the UserB shard, the UserA shard does not need to hear about it. If Brian sends a message to Alex, I can record that fact on both the UserA and UserB shards. In this way, when either Alex or Brian logs in, he can retrieve all his sent and received messages from his own shard without querying all shards.</p> <p>So far, so good. What about searches? In this example, if Brian searches for "Alex" I can check UserA. But what if he searches for Alex by his last name, "Smith"? There are Smiths in every shard. From here, I see two options:</p> <ol> <li>Have the application search for Smiths on each shard. This can be done slowly (querying each shard in succession) or quickly (querying each shard in parallel), but either way, every shard needs to be involved in every search. In the same way that read replication does not scale writes, having searches hit every shard does not scale your searches. You may reach a time when your search volume is high enough to overwhelm each shard, and adding shards does not help you, since they all get the same volume.</li> <li>Some kind of indexing that itself is tolerant of sharding. For example, let's say I have a constant number of fields by which I want to search: first name and last name. In addition to UserA, UserB, etc. I also have IndexA, IndexB, etc. When a new user registers, I attach him to each index I want him to be found on. So I put Alex Smith into both IndexA and IndexS, and he can be found on either "Alex" or "Smith", but no substrings. In this way, you don't need to query each shard, so search might be scalable.</li> </ol> <p>So can search be scaled? If so, is this indexing approach the right one? Is there any other?</p>
[ { "answer_id": 267470, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 4, "selected": false, "text": "\"lastname='Smith' OR lastname='Jones'\"" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
260,406
<p>I have a C program with an embedded Perl interpreter. I want to be able to precompile some Perl code from within the program. How do I do that?</p> <p>Rationale (if anyone is interested) is to be able to compile it once, store the parse tree, and execute many times (as long as the compiled code does not change).</p> <p>Thanks! Madhu</p> <p>PS: I am using Perl-5.8, though it would be good to know if Perl-6.0 makes this easier in any way.</p>
[ { "answer_id": 267979, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 2, "selected": false, "text": "-lperl -llibperl" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
260,432
<p>I have the following method in my unit test project:</p> <pre><code> [TestMethod] [HostType("ASP.NET")] [UrlToTest("http://localhost:3418/Web/SysCoord/ChooseEPA.aspx")] [AspNetDevelopmentServerHost("%PathToWebRoot%")] public void TestMethod1() { Page page = TestContext.RequestedPage; Assert.IsTrue(false, "Test ran, at least."); } </code></pre> <p>I'm getting this exception:</p> <p>The test adapter 'WebHostAdapter' threw an exception while running test 'TestMethod1'. The web site could not be configured correctly; getting ASP.NET process information failed. Requesting '<a href="http://localhost:3418/SysCoord/VSEnterpriseHelper.axd" rel="noreferrer">http://localhost:3418/SysCoord/VSEnterpriseHelper.axd</a>' returned an error: The remote server returned an error: (404) Not Found. The remote server returned an error: (404) Not Found.</p> <p>The page works as it should in a browser at the url: <a href="http://localhost:3418/Web/SysCoord/ChooseEPA.aspx" rel="noreferrer">http://localhost:3418/Web/SysCoord/ChooseEPA.aspx</a>. </p> <p>This physical path is: C:\ESI\HR_Connect2\BenefitChangeSystem\Application_DEV\Web\SysCoord.</p> <p>Any ideas would be appreciated.</p> <p><strong>Update 1</strong></p> <p>Added the following to my web.config file per this article. Also made the web.config writable and killed/restarted the development web server. No change in behavior.</p> <pre><code>&lt;location path="VSEnterpriseHelper.axd"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <p><strong>Update 2</strong></p> <p>Changing the AspNetDevelopmentServerHost attribute to the equivalent of [AspNetDevelopmentServerHost("%PathToWebRoot%\solutionfolder\webfolder", "/webfolder")] resolved the 404 problem.</p> <p>Unfortunately the test began to return a 500 error instead. Progress, but not much. Trial and error with a clean project led to the conclusion that references to custom classes in the of the web.config were causing the problem.</p> <p>For example:</p> <pre><code> &lt;profile enabled="true" defaultProvider="MyProfileProvider"&gt; &lt;providers&gt; &lt;add name="MyProfileProvider" connectionStringName="ProfileConnectionString" applicationName="/MyApp" type="System.Web.Profile.SqlProfileProvider"/&gt; &lt;/providers&gt; &lt;properties&gt; &lt;add name="Theme" type="String" defaultValue="Default"/&gt; &lt;add name="LastLogon" type="DateTime"/&gt; &lt;add name="LastLogonIp" type="String"/&gt; &lt;!-- &lt;add name="EmployeeSearchCriteria" type="MyApplicationFramework.Profile.EmployeeSearchCriteria"/&gt; &lt;add name="DocumentSearchCriteria" type="MyApplicationFramework.Profile.DocumentSearchCriteria"/&gt; --&gt; &lt;/properties&gt; &lt;/profile&gt; </code></pre> <p>With the criteria types above commented out the test ran fine. With them uncommented, the 500 error was returned.</p> <p>Anyone had a similar problem in the past?</p>
[ { "answer_id": 269052, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "MyApplicationFramework.Profile.EmployeeSearchCriteria" }, { "answer_id": 761403, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<!-- <location path=\"VSEnterpriseHelper.axd\">\n <system.web>\n <authorization>\n <allow users=\"?\" />\n </authorization>\n </system.web> </location> -->\n" }, { "answer_id": 3515780, "author": "hal9000", "author_id": 24862, "author_profile": "https://Stackoverflow.com/users/24862", "pm_score": 3, "selected": false, "text": "<runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\" appliesTo=\"v2.0.50727\">\n <dependentAssembly>\n <assemblyIdentity name=\"System.Web.Extensions\" publicKeyToken=\"31bf3856ad364e35\"/>\n <bindingRedirect oldVersion=\"1.0.0.0-1.1.0.0\" newVersion=\"3.5.0.0\"/>\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"System.Web.Extensions.Design\" publicKeyToken=\"31bf3856ad364e35\"/>\n <bindingRedirect oldVersion=\"1.0.0.0-1.1.0.0\" newVersion=\"3.5.0.0\"/>\n </dependentAssembly>\n </assemblyBinding>\n</runtime>\n" }, { "answer_id": 3984373, "author": "Igor Zevaka", "author_id": 129404, "author_profile": "https://Stackoverflow.com/users/129404", "pm_score": 4, "selected": false, "text": "[TestMethod]\npublic void TestMethod1()\n{\n Page page = TestContext.RequestedPage;\n Assert.IsTrue(false, \"Test ran, at least.\");\n}\n" }, { "answer_id": 4708986, "author": "Ibsta", "author_id": 577923, "author_profile": "https://Stackoverflow.com/users/577923", "pm_score": 1, "selected": false, "text": "[AspNetDevelopmentServerHost(\"%PathToWebRoot%\")]" }, { "answer_id": 7740609, "author": "simpsons88", "author_id": 991500, "author_profile": "https://Stackoverflow.com/users/991500", "pm_score": 1, "selected": false, "text": " [HostType(\"ASP.NET\")]\n [AspNetDevelopmentServerHost(\"C:\\\\Inetpub\\\\....]\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260/" ]
260,436
<p>Disclaimer: the following is a sin against XML. That's why I'm trying to change it with XSLT :)</p> <p>My XML currently looks like this:</p> <pre><code>&lt;root&gt; &lt;object name="blarg" property1="shablarg" property2="werg".../&gt; &lt;object name="yetanotherobject" .../&gt; &lt;/root&gt; </code></pre> <p>Yes, I'm putting all the textual data in attributes. I'm hoping XSLT can save me; I want to move toward something like this:</p> <pre><code>&lt;root&gt; &lt;object&gt; &lt;name&gt;blarg&lt;/name&gt; &lt;property1&gt;shablarg&lt;/name&gt; ... &lt;/object&gt; &lt;object&gt; ... &lt;/object&gt; &lt;/root&gt; </code></pre> <p>I've actually got all of this working so far, with the exception that my sins against XML have been more... exceptional. Some of the tags look like this:</p> <pre><code>&lt;object description = "This is the first line This is the third line. That second line full of whitespace is meaningful"/&gt; </code></pre> <p>I'm using xsltproc under linux, but it doesn't seem to have any options to preserve whitespace. I've attempted to use xsl:preserve-space and xml:space="preserve" to no avail. Every option I've found seems to apply to keeping whitespace within the elements themselves, but not the attributes. Every single time, the above gets changed to:</p> <pre> This is the first line This is the third line. That second line full of whitespace is meaningful </pre> <p>So the question is, can I preserve the attribute whitespace?</p>
[ { "answer_id": 29782321, "author": "n611x007", "author_id": 611007, "author_profile": "https://Stackoverflow.com/users/611007", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<!DOCTYPE elemke [\n<!ATTLIST brush wood CDATA #REQUIRED>\n]>\n\n<elemke>\n<brush wood=\"guy&#xA;threep\"/>\n</elemke>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n<xsl:template name=\"split\">\n <xsl:param name=\"list\" select=\"''\" />\n <xsl:param name=\"separator\" select=\"'&#xA;'\" />\n <xsl:if test=\"not($list = '' or $separator = '')\">\n <xsl:variable name=\"head\" select=\"substring-before(concat($list, $separator), $separator)\" />\n <xsl:variable name=\"tail\" select=\"substring-after($list, $separator)\" />\n\n <xsl:value-of select=\"$head\"/>\n <br/><xsl:text>&#xA;</xsl:text>\n <xsl:call-template name=\"split\">\n <xsl:with-param name=\"list\" select=\"$tail\" />\n <xsl:with-param name=\"separator\" select=\"$separator\" />\n </xsl:call-template>\n </xsl:if>\n</xsl:template>\n\n\n<xsl:template match=\"brush\">\n <html>\n <xsl:call-template name=\"split\">\n <xsl:with-param name=\"list\" select=\"@wood\"/>\n </xsl:call-template>\n </html>\n</xsl:template>\n\n</xsl:stylesheet>\n <html>guy<br>\n threep<br>\n\n</html> \n java -jar saxon9he.jar -s:in.xml -xsl:in.xsl -o:out.html\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2555346/" ]
260,439
<p>I currently have two text boxes which accept any number. I have a text block that takes the two numbers entered and calculates the average. </p> <p>I was wondering if there was a way I could bind this text block to both text boxes and utilize a custom converter to calculate the average? I currently am catching the text changed events on both text boxes and calculating the average that way, but I am under the assumption data binding would be more efficient and easier.</p>
[ { "answer_id": 260445, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 7, "selected": true, "text": "MultiBinding XAML <TextBlock>\n <TextBlock.Text>\n <MultiBinding Converter=\"{StaticResource myConverter}\">\n <Binding Path=\"myFirst.Value\" />\n <Binding Path=\"mySecond.Value\" />\n </MultiBinding>\n </TextBlock.Text>\n</TextBlock>\n myConverter myFirst.Value mySecond.Value" }, { "answer_id": 260487, "author": "Donnelle", "author_id": 28074, "author_profile": "https://Stackoverflow.com/users/28074", "pm_score": 5, "selected": false, "text": "class AverageConverter : IMultiValueConverter\n{\n #region IMultiValueConverter Members\n public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n int total = 0;\n int number = 0;\n foreach (object o in values)\n {\n int i;\n bool parsed = int.TryParse(o.ToString(), out i);\n if (parsed)\n {\n total += i;\n number++;\n }\n }\n if (number == 0) return 0;\n return (total/number).ToString();\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n}\n <TextBox Text=\"{Binding Value1}\" x:Name=\"TextBox1\" />\n<TextBox Text=\"{Binding Value2}\" x:Name=\"TextBox2\" />\n\n<TextBlock>\n <TextBlock.Text>\n <MultiBinding Converter=\"{StaticResource AverageConverter}\">\n <Binding ElementName=\"TextBox1\" Path=\"Text\" />\n <Binding ElementName=\"TextBox2\" Path=\"Text\" />\n <!-- OR -->\n <!-- <Binding Path=\"Value1\" /> -->\n <!-- <Binding Path=\"Value2\" /> -->\n\n </MultiBinding>\n </TextBlock.Text>\n</TextBlock>\n" }, { "answer_id": 260493, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "public double AvgValue\n{\n get { return (valueA + valueB) / 2.0; }\n}\n <TextBlock Text=\"{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=AvgValue}\" />\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23939/" ]
260,441
<p>In class, we are all 'studying' databases, and everyone is using Access. Bored with this, I am trying to do what the rest of the class is doing, but with raw SQL commands with MySQL instead of using Access.</p> <p>I have managed to create databases and tables, but now how do I make a relationship between two tables?</p> <p>If I have my two tables like this:</p> <pre><code>CREATE TABLE accounts( account_id INT NOT NULL AUTO_INCREMENT, customer_id INT( 4 ) NOT NULL , account_type ENUM( 'savings', 'credit' ) NOT NULL, balance FLOAT( 9 ) NOT NULL, PRIMARY KEY ( account_id ) ) </code></pre> <p>and</p> <pre><code>CREATE TABLE customers( customer_id INT NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL, address VARCHAR(20) NOT NULL, city VARCHAR(20) NOT NULL, state VARCHAR(20) NOT NULL, PRIMARY KEY ( customer_id ) ) </code></pre> <p>How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).</p>
[ { "answer_id": 260453, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 8, "selected": true, "text": "CREATE TABLE accounts(\n account_id INT NOT NULL AUTO_INCREMENT,\n customer_id INT( 4 ) NOT NULL ,\n account_type ENUM( 'savings', 'credit' ) NOT NULL,\n balance FLOAT( 9 ) NOT NULL,\n PRIMARY KEY ( account_id ), \n FOREIGN KEY (customer_id) REFERENCES customers(customer_id) \n) ENGINE=INNODB;\n" }, { "answer_id": 260458, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 4, "selected": false, "text": "customer_id INT( 4 ) NOT NULL ,\n customer_id INT( 10 ) NOT NULL ,\n" }, { "answer_id": 260460, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 7, "selected": false, "text": "FOREIGN KEY (customer_id) REFERENCES customers(customer_id) \n ALTER TABLE `accounts`\n ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;\n" }, { "answer_id": 260500, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 3, "selected": false, "text": "SELECT a, b from table1 LEFT JOIN table2 USING (common_field);\n" }, { "answer_id": 14536060, "author": "Musa", "author_id": 2000184, "author_profile": "https://Stackoverflow.com/users/2000184", "pm_score": 1, "selected": false, "text": "CREATE TABLE accounts(\n account_id INT NOT NULL AUTO_INCREMENT,\n customer_id INT( 4 ) NOT NULL ,\n account_type ENUM( 'savings', 'credit' ) NOT NULL,\n balance FLOAT( 9 ) NOT NULL,\n PRIMARY KEY (account_id)\n)ENGINE=InnoDB;\n\nCREATE TABLE customers(\n customer_id INT NOT NULL AUTO_INCREMENT,\n name VARCHAR(20) NOT NULL,\n address VARCHAR(20) NOT NULL,\n city VARCHAR(20) NOT NULL,\n state VARCHAR(20) NOT NULL,\n PRIMARY KEY ( account_id ), \nFOREIGN KEY (customer_id) REFERENCES customers(customer_id) \n)ENGINE=InnoDB; \n" }, { "answer_id": 28890883, "author": "user3842431", "author_id": 3842431, "author_profile": "https://Stackoverflow.com/users/3842431", "pm_score": 4, "selected": false, "text": "CREATE TABLE accounts(\n account_id INT NOT NULL AUTO_INCREMENT,\n customer_id INT( 4 ) NOT NULL ,\n account_type ENUM( 'savings', 'credit' ) NOT NULL,\n balance FLOAT( 9 ) NOT NULL,\n PRIMARY KEY ( account_id )\n)\n\nand\n\nCREATE TABLE customers(\n customer_id INT NOT NULL AUTO_INCREMENT,\n name VARCHAR(20) NOT NULL,\n address VARCHAR(20) NOT NULL,\n city VARCHAR(20) NOT NULL,\n state VARCHAR(20) NOT NULL,\n)\n\nHow do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).\n CREATE TABLE customers(\n customer_id INT NOT NULL AUTO_INCREMENT,\n name VARCHAR(20) NOT NULL,\n address VARCHAR(20) NOT NULL,\n city VARCHAR(20) NOT NULL,\n state VARCHAR(20) NOT NULL,\n account_type ENUM( 'savings', 'credit' ) NOT NULL,\n balance FLOAT( 9 ) NOT NULL,\n)\n CREATE TABLE customersaccounts(\n customer_id INT NOT NULL,\n account_id INT NOT NULL,\n PRIMARY KEY (customer_id, account_id),\n FOREIGN KEY customer_id references customers (customer_id) on delete cascade,\n FOREIGN KEY account_id references accounts (account_id) on delete cascade\n}\n SELECT a.*\n FROM customersaccounts ca\n INNER JOIN accounts a ca.account_id=a.account_id\n AND ca.customer_id=mycustomerid;\n CREATE VIEW customeraccounts AS \n SELECT a.*, c.* FROM customersaccounts ca\n INNER JOIN accounts a ON ca.account_id=a.account_id\n INNER JOIN customers c ON ca.customer_id=c.customer_id;\n" }, { "answer_id": 52351148, "author": "Anayat", "author_id": 10369848, "author_profile": "https://Stackoverflow.com/users/10369848", "pm_score": 0, "selected": false, "text": "create table departement(\n dep_id int primary key auto_increment,\n dep_name varchar(100) not null,\n dep_descriptin text,\n dep_photo varchar(100) not null,\n dep_video varchar(300) not null\n);\n\ncreate table newsfeeds(\n news_id int primary key auto_increment,\n news_title varchar(200) not null,\n news_description text,\n news_photo varchar(300) ,\n news_date varchar(30) not null,\n news_video varchar(300),\n news_comment varchar(200),\n news_departement int foreign key(dep_id) references departement(dep_id)\n);\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
260,464
<p>I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like:</p> <pre><code>warning: HEAP[test.exe]: warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1 </code></pre> <p>How can I track down where this is happening at? Viewing the memory doesn't give me any clues.</p> <p>Thanks!</p>
[ { "answer_id": 16990738, "author": "Rafał", "author_id": 1048556, "author_profile": "https://Stackoverflow.com/users/1048556", "pm_score": 0, "selected": false, "text": "itemsetList_t ** iteration_isets; iteration_isets = realloc(iteration_isets, sizeof(itemsetList_t *) * max_elem); iteration_isets = realloc(iteration_isets, sizeof(int) * max_elem);" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
260,484
<p>How do I query the iPhone's current IP address?</p>
[ { "answer_id": 2913328, "author": "Krumelur", "author_id": 292477, "author_profile": "https://Stackoverflow.com/users/292477", "pm_score": 4, "selected": false, "text": "\n/*\nReturns the local IP, or NULL on failure.\n*/\nconst char* GetLocalIP() {\n char buf[256];\n if(gethostname(buf,sizeof(buf)))\n return NULL;\n struct hostent* he = gethostbyname(buf);\n if(!he)\n return NULL;\n for(int i=0; he->h_addr_list[i]; i++) {\n char* ip = inet_ntoa(*(struct in_addr*)he->h_addr_list[i]);\n if(ip != (char*)-1) return ip;\n }\n return NULL;\n}\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
260,491
<p>I'm developing a library for use in other apps and this library has lots of debugging and logging statements thanks to NLog.</p> <p>Is it possible to exclude the reference to NLog.dll when I switch to release mode?</p> <p>Cheers,</p>
[ { "answer_id": 860601, "author": "Sander Rijken", "author_id": 5555, "author_profile": "https://Stackoverflow.com/users/5555", "pm_score": 6, "selected": true, "text": "<Reference Include=\"NLog\" Condition=\"'$(Configuration)' == 'Debug'\" />\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
260,504
<p>Question: Is there an easy way (library function) to perform a bitwise AND or OR on numbers larger than 32-bit in ActionScript? </p> <p>From the docs: "Bitwise operators internally manipulate floating-point numbers to change them into 32-bit integers. The exact operation performed depends on the operator, but all bitwise operations evaluate each binary digit (bit) of the 32-bit integer individually to compute a new value."</p> <p>Bummer...</p> <p>I can't use the &amp; or | ops - does AS expose a library function to do this for Numbers?</p> <p>Specifics: I'm porting a bunch of java to flex and the java maintains a bunch of 'long' masks. I know that I can split the Java masks into two ints on the flex side. Since all of my mask manip is localized this won't be too painful. However, I'd like to keep the port as 1-1 as possible.</p> <p>Any suggestions? Thanks!</p>
[ { "answer_id": 1879659, "author": "THF", "author_id": 228625, "author_profile": "https://Stackoverflow.com/users/228625", "pm_score": 1, "selected": false, "text": "public class NumberUtils\n{\n public static const MSB_CONV : Number = Math.pow(2, 32);\n\n public static function bitwiseAND(num1 : Number, num2 : Number) : Number {\n var msb1 : int = num1 / MSB_CONV;\n var msb2 : int = num2 / MSB_CONV;\n\n return (msb1 & msb2) * MSB_CONV + (num1 & num2);\n }\n..OR..shiftRight..\n}\n" }, { "answer_id": 44130603, "author": "Chris Chan", "author_id": 8052533, "author_profile": "https://Stackoverflow.com/users/8052533", "pm_score": 0, "selected": false, "text": "public function readInt64():Number\n{\n var highInt:uint = bytes.readUnsignedInt();\n var lowerInt:uint = bytes.readUnsignedInt();\n return highInt * Math.pow(2,32) + lowerInt;\n}\n\npublic function writeInt64(value:Number):void\n{\n this.writeUnsignedInt(int(value / 0xffffffff));\n this.writeUnsignedInt(int(value));\n}\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25303/" ]
260,511
<p>Here is my short implementation of <a href="http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication" rel="noreferrer">Russian Peasant Multiplication</a>. How can it be improved?</p> <p><em>Restrictions</em> : only works when a>0,b>0</p> <pre><code>for(p=0;p+=(a&amp;1)*b,a!=1;a&gt;&gt;=1,b&lt;&lt;=1); </code></pre>
[ { "answer_id": 260546, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "p a a" }, { "answer_id": 260552, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 4, "selected": false, "text": "int sum = 0;\nwhile(1)\n{\n sum += (a & 1) * b;\n if(a == 1)\n break;\n\n a = a / 2;\n b = b * 2;\n}\n" }, { "answer_id": 260568, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": false, "text": "for(p=0;p+=(-(a&1))&b,a!=1;a>>=1,b<<=1);\n" }, { "answer_id": 260662, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "int RussianPeasant(int a, int b)\n{\n // sum = a * b\n int sum = 0;\n while (a != 0)\n {\n if ((a & 1) != 0)\n sum += b;\n b <<= 1;\n a >>= 1;\n }\n return sum;\n}\n" }, { "answer_id": 260893, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 7, "selected": true, "text": "int peasant_mult (int a, int b) {\n for (p = 0;\n p += (a & 1) * b, a != 1;\n a /= 2, b *= 2);\n return p;}\n for" }, { "answer_id": 261414, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 3, "selected": false, "text": "// Russian Peasant Multiplication ( p <- a*b, only works when a>0, b>0 )\n// See http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication\nfor( p=0; p+=(a&1)*b, a!=1; a>>=1,b<<=1 );\n" }, { "answer_id": 286768, "author": "flolo", "author_id": 36472, "author_profile": "https://Stackoverflow.com/users/36472", "pm_score": 4, "selected": false, "text": "p = a * b;\n" }, { "answer_id": 1172612, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function RPM(int a, int b){\n int rtn;\n for(rtn=0;rtn+=(a&1)*b,a!=1;a>>=1,b<<=1);\n return rtn;\n}\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34051/" ]
260,518
<p>I have some cross platform DNS client code that I use for doing end to end SMTP and on windows I can find the current DNS server ip addresses by looking in the registry. On the Mac I can probably use the SystemConfiguration framework as mentioned in the first answer, however the exact method of doing so is not immediately obvious.</p> <p>For instance SCDynamicStoreCopyDHCPInfo returns some of the dynamic DHCP related data but not the DNS server addresses.</p>
[ { "answer_id": 26982170, "author": "kmdent", "author_id": 786282, "author_profile": "https://Stackoverflow.com/users/786282", "pm_score": 3, "selected": false, "text": "// Get native iOS System Resolvers\nres_ninit(&_res);\nres_state res = &_res;\n\nfor (int i = 0; i < res->nscount; i++) {\n sa_family_t family = res->nsaddr_list[i].sin_family;\n int port = ntohs(res->nsaddr_list[i].sin_port);\n if (family == AF_INET) { // IPV4 address\n char str[INET_ADDRSTRLEN]; // String representation of address\n inet_ntop(AF_INET, & (res->nsaddr_list[i].sin_addr.s_addr), str, INET_ADDRSTRLEN);\n } else if (family == AF_INET6) { // IPV6 address\n char str[INET6_ADDRSTRLEN]; // String representation of address\n inet_ntop(AF_INET6, &(res->nsaddr_list [i].sin_addr.s_addr), str, INET6_ADDRSTRLEN);\n }\n}\nres_ndestroy(res);\n" }, { "answer_id": 34940848, "author": "taha027", "author_id": 1888169, "author_profile": "https://Stackoverflow.com/users/1888169", "pm_score": 3, "selected": false, "text": "SCPreferencesRef prefsDNS = SCPreferencesCreate(NULL, CFSTR(\"DNSSETTING\"), NULL);\nCFArrayRef services = SCNetworkServiceCopyAll(prefsDNS);\nlong servicesCount = CFArrayGetCount(services);\nfor (long i = 0; i < servicesCount; i++) {\n const SCNetworkServiceRef service = (const SCNetworkServiceRef)CFArrayGetValueAtIndex(services, i);\n CFStringRef interfaceServiceID = SCNetworkServiceGetServiceID(service);\n CFStringRef primaryservicepath = CFStringCreateWithFormat(NULL,NULL,CFSTR(\"State:/Network/Service/%@/DNS\"),interfaceServiceID);\n SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR(\"DNSSETTING\"), NULL, NULL);\n CFPropertyListRef propList = SCDynamicStoreCopyValue(dynRef,primaryservicepath);\n if (propList) {\n CFDictionaryRef dict = (CFDictionaryRef)propList;\n CFArrayRef addresses = (CFArrayRef)CFDictionaryGetValue(dict, CFSTR(\"ServerAddresses\"));\n long addressesCount = CFArrayGetCount(addresses);\n for (long j = 0; j < addressesCount; j++) {\n CFStringRef address = (CFStringRef)CFArrayGetValueAtIndex(addresses, j);\n // Print address\n CFShow(address);\n }\n CFRelease(propList);\n }\n CFRelease(dynRef);\n CFRelease(primaryservicepath);\n}\nCFRelease(services);\nCFRelease(prefsDNS);\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33847/" ]
260,521
<p>I am having a problem getting a list of fields from a query defined at run time by the users of my program. I let my users enter a SQL query into a memo control and then I want to let them go through the fields that will return and do such things as format the output, sum column values and so forth. So, I have to get the column names so they have a place to enter the additional information.</p> <p>I would do fine if there were no parameters, but I also have to let them define filter parameters for the query. So, if I want to set the parameters to null, I have to know what the parameter's datatype is.</p> <p>I am using Delphi 2006. I connect to a Firebird 2.1 database using the DBExpress component TSQLConnection and TSQLQuery. Previously, I was successful using:</p> <p>for i := 0 to Qry.Params.Count - 1 do Qry.Params[i].value := varNull;</p> <p>I discovered I had a problem when I tried to use a date parameter. It was just a coincidence that all my parameters up until then had been integers (record IDs). It turns out that varNull is just an enumerated constant with a value of 1 so I was getting acceptable results (no records) was working okay.</p> <p>I only need a list of the fields. Maybe I should just parse the SELECT clause of the SQL statement. I thought setting Qry.Prepared to True would get me a list of the fields but no such luck. It wants values for the parameters. </p> <p>If you have an idea, I would sure like to hear it. Thanks for any help.</p>
[ { "answer_id": 260582, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 1, "selected": false, "text": "for i := 0 to Qry.Params.Count - 1 do \nbegin\n if VarType(Qry.Params[i].value) and varTypeMask = varDate then\n begin\n Qry.Params[i].value := Now; //or whatever you choose as your default\n end\n else\n begin\n Qry.Params[i].value := varNull;\n end;\nend;\n" }, { "answer_id": 261394, "author": "Despatcher", "author_id": 10240, "author_profile": "https://Stackoverflow.com/users/10240", "pm_score": 2, "selected": false, "text": "for i := 0 to FilterDataSet.Params.Count -1 do \nbegin \n Case FilterDataSet.Params.Items[i].Datatype of \n ftString: \n ftSmallint, ftInteger, ftWord: \n ftFloat, ftCurrency, ftBCD: \n ftDate: \n ftTime: \n ftDateTime: \n . \n . \n . \nend; \n" }, { "answer_id": 261862, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 2, "selected": false, "text": "for i := 0 to Qry.Params.Count - 1 do begin\n Qry.Params[i].Clear;\n Qry.Params[i].Bound := True;\nend;\n" }, { "answer_id": 320656, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "TmpQuery.ParamByName('MyDateTimeParam').DataType := ftDate;\nTmpQuery.ParamByName('MyDateTimeParam').Clear;\nTmpQuery.ParamByName('MyDateTimeParam').Bound := True;\n" }, { "answer_id": 322067, "author": "jrodenhi", "author_id": 25315, "author_profile": "https://Stackoverflow.com/users/25315", "pm_score": 1, "selected": false, "text": "sNull := 'NULL';\nQry.SQL.Add(sSQL);\nfor i := 0 to Qry.Params.Count - 1 do begin\n sParamName := Qry.Params[i].Name;\n sSQL := SearchAndReplace (sSQL, ':' + sParamName, sNull, DELIMITERS);\nend;\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25315/" ]
260,523
<p>I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the <em>UITableViewCell Class Reference</em> but there are only three constants defined for Selection style (Blue, Gray, None). I saw one application that used a different color than those defined in the reference.</p> <p>How can we use a color other than those defined in the reference?</p>
[ { "answer_id": 260697, "author": "Jeffrey Forbes", "author_id": 28019, "author_profile": "https://Stackoverflow.com/users/28019", "pm_score": 2, "selected": false, "text": "UIView* selectedView; //inside your header\n\n- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{\n\n UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];\n selectedView = [[UIView alloc] initWithFrame:[cell frame]];\n selectedView.backgroundColor = [UIColor greenColor]; //whatever\n\n [cell insertSubview:selectedView atIndex:0]; //tweak this as necessary\n [selectedView release]; //clean up\n\n}\n" }, { "answer_id": 758493, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 7, "selected": true, "text": "selectedBackgroundView - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {\n\n static NSString *CellIdentifier = @\"Cell\";\n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\n if (cell == nil) {\n cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];\n cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"SelectedCellBackground.png\"]] autorelease];\n }\n\n // configure the cell\n}\n UIImageView backgroundColor" }, { "answer_id": 1844211, "author": "Paul", "author_id": 224415, "author_profile": "https://Stackoverflow.com/users/224415", "pm_score": 5, "selected": false, "text": "selectedBackgroundView cell.selectionStyle UITableViewCellSelectionStyleNone UIView" }, { "answer_id": 11600123, "author": "Charles Marsh", "author_id": 1450892, "author_profile": "https://Stackoverflow.com/users/1450892", "pm_score": 3, "selected": false, "text": "- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event\n{\n //Set backgorund\n self.backgroundColor = [UIColor themeBlue];\n\n //Set text\n self.textLabel.textColor = [UIColor themeWhite];\n\n //Call super\n [super touchesBegan:touches withEvent:event];\n}\n self.selectionStyle = UITableViewCellSelectionStyleNone;\n" }, { "answer_id": 11633174, "author": "Willster", "author_id": 385619, "author_profile": "https://Stackoverflow.com/users/385619", "pm_score": 4, "selected": false, "text": "- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {\n if(highlighted) {\n self.backgroundColor = [UIColor redColor];\n } else {\n self.backgroundColor = [UIColor clearColor];\n }\n\n [super setHighlighted:highlighted animated:animated];\n}\n cell.selectionStyle = UITableViewCellSelectionStyleNone\n" }, { "answer_id": 13070898, "author": "bentford", "author_id": 946, "author_profile": "https://Stackoverflow.com/users/946", "pm_score": 1, "selected": false, "text": "setHighlighted:animated: - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {\n if(highlighted) {\n self.backgroundColor = [UIColor redColor];\n } else {\n self.backgroundColor = [UIColor clearColor];\n }\n\n [super setHighlighted:highlighted animated:animated];\n}\n - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {\n if( highlighted == YES )\n self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"seasonal_list_event_bar_default.png\"]];\n else\n self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"seasonal_list_event_bar_active.png\"]];\n\n\n [super setHighlighted:highlighted animated:animated];\n}\n" }, { "answer_id": 17469723, "author": "PK86", "author_id": 952193, "author_profile": "https://Stackoverflow.com/users/952193", "pm_score": 0, "selected": false, "text": "- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { \n// Set Highlighted Color \nif (highlighted) { \nself.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];\n } else { \n self.backgroundColor = [UIColor clearColor]; \n } \n}\n" }, { "answer_id": 38100301, "author": "Ishwar Hingu", "author_id": 5022598, "author_profile": "https://Stackoverflow.com/users/5022598", "pm_score": 0, "selected": false, "text": "- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {\n return YES;\n}\n\n- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {\n // Add your Colour.\n SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];\n [self setCellColor:Ripple_Colour ForCell:cell]; //highlight colour\n}\n\n- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {\n // Reset Colour.\n SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];\n [self setCellColor:Ripple_Colour ForCell:cell]; //normal color\n\n}\n\n- (void)setCellColor:(UIColor *)color ForCell:(UITableViewCell *)cell {\n cell.contentView.backgroundColor = color;\n cell.backgroundColor = color;\n}\n" }, { "answer_id": 48623625, "author": "Prateekro", "author_id": 2714340, "author_profile": "https://Stackoverflow.com/users/2714340", "pm_score": 0, "selected": false, "text": "alpha: 0.0 cell.selectedBackgroundView = UIView(frame: CGRect.zero)\ncell.selectedBackgroundView?.backgroundColor = UIColor(red:0.27, green:0.71, blue:0.73, alpha:1.0)\n cell.layer.cornerRadius = 8\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n\n tableView.deselectRow(at: indexPath, animated: true)\n}\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ]
260,525
<p>if i decide to use the 'publish' option for my ASP.NET website, instead of a Web Deployment Project, can i do custom msbuild things? Or do i need to stick with WDP's if i want to do custom msbuild stuff during compile/deployment.</p>
[ { "answer_id": 262007, "author": "MartinHN", "author_id": 2972, "author_profile": "https://Stackoverflow.com/users/2972", "pm_score": 2, "selected": false, "text": "Release.AspNetCompiler.VirtualPath = \"/PrecompiledWeb\"\nRelease.AspNetCompiler.PhysicalPath = \"..\\Web\\\"\nRelease.AspNetCompiler.TargetPath = \"..\\..\\PrecompiledWeb\\\"\nRelease.AspNetCompiler.Updateable = \"true\"\nRelease.AspNetCompiler.ForceOverwrite = \"true\"\nRelease.AspNetCompiler.FixedNames = \"true\"\nRelease.AspNetCompiler.Debug = \"False\"\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
260,531
<p>How have you explained nested arrays to a programmer. I'm thinking someone that has an entry level understanding of programming, but is trying to do more complicated coding.</p> <p>The array with array works, but they can't quite get their mind around the idea.</p> <p><strong>Edit:</strong> example of a nested array:</p> <pre><code>array( 'array1' =&gt; array( 'key1' =&gt; 'val1', 'key2' =&gt; 'val2', ), 'array2' =&gt; array( 'key1' =&gt; 'val1', 'key2' =&gt; 'val2', ), ); </code></pre> <p>Of course, they are usually more complicated than this and maybe that's the problem.</p>
[ { "answer_id": 260551, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "X int x[5][5] = {\n { 1,0,0,0,1 },\n { 0,1,0,1,0 },\n { 0,0,1,0,0 },\n { 0,1,0,1,0 },\n { 1,0,0,0,1 }\n};\n for" }, { "answer_id": 260565, "author": "thursdaysgeek", "author_id": 22523, "author_profile": "https://Stackoverflow.com/users/22523", "pm_score": 3, "selected": false, "text": "For each book in library\n\n For each chapter in book\n\n For each paragraph in chapter\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
260,540
<p>Please advise how to scrape AJAX pages.</p>
[ { "answer_id": 260614, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "<script type=\"text/javascript\">\nfunction ajaxFunction()\n{\nvar xmlHttp;\ntry\n {\n // Firefox, Opera 8.0+, Safari\n xmlHttp=new XMLHttpRequest();\n }\ncatch (e)\n {\n // Internet Explorer\n try\n {\n xmlHttp=new ActiveXObject(\"Msxml2.XMLHTTP\");\n }\n catch (e)\n {\n try\n {\n xmlHttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n catch (e)\n {\n alert(\"Your browser does not support AJAX!\");\n return false;\n }\n }\n }\n xmlHttp.onreadystatechange=function()\n {\n if(xmlHttp.readyState==4)\n {\n document.myForm.time.value=xmlHttp.responseText;\n }\n }\n xmlHttp.open(\"GET\",\"time.asp\",true);\n xmlHttp.send(null);\n }\n</script>\n" }, { "answer_id": 17638017, "author": "yxc", "author_id": 2254730, "author_profile": "https://Stackoverflow.com/users/2254730", "pm_score": 2, "selected": false, "text": "GET /hqzx/quote.aspx?type=3&market=1&sorttype=3&updown=up&page=1&count=8&time=164330 \n HTTP/1.1\nAccept: */*\nReferer: http://quote.hexun.com/stock/default.aspx\nAccept-Language: zh-cn\nAccept-Encoding: gzip, deflate\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\nHost: quote.tool.hexun.com\nConnection: Keep-Alive\n http://quote.tool.hexun.com/hqzx/quote.aspx?type=3&market=1&sorttype=3&updown=up&page=1&count=8&time=164330\n" }, { "answer_id": 21653575, "author": "mattspain", "author_id": 2794310, "author_profile": "https://Stackoverflow.com/users/2794310", "pm_score": 3, "selected": false, "text": "/*global casper:true*/\nvar casper = require('casper').create();\nvar suggestions = [];\nvar word = casper.cli.get(0);\n\nif (!word) {\n casper.echo('please provide a word').exit(1);\n}\n\ncasper.start('http://www.google.com/', function() {\n this.sendKeys('input[name=q]', word);\n});\n\ncasper.waitFor(function() {\n return this.fetchText('.gsq_a table span').indexOf(word) === 0\n}, function() {\n suggestions = this.evaluate(function() {\n var nodes = document.querySelectorAll('.gsq_a table span');\n return [].map.call(nodes, function(node){\n return node.textContent;\n });\n });\n});\n\ncasper.run(function() {\n this.echo(suggestions.join('\\n')).exit();\n});\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34051/" ]
260,561
<p>Whats the normal procedure of clearing a form after POST? Just loop through the textboxes and cleat all text? I have an ASP.NET application with several forms and I am trying to avoid them sending the data twice?</p> <p>Thanks</p>
[ { "answer_id": 260570, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 1, "selected": false, "text": "document.forms[0].reset();\ndocument.forms[1].reset();\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
260,593
<p>I'm tasked with replicating a production environment to create many test/sit environments.</p> <p>One of the things I need to do is build up Perl, with all the modules which have been installed (including internal and external modules) over the years. I could just use CPAN.pm autobundle, but this will result in the test environment having much newer versions of the external modules that production has.</p> <p>What is the easiest/best way to get and install (a lot of) version specific Perl modules.</p>
[ { "answer_id": 267783, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 7, "selected": false, "text": "cpan> install MSCHWERN/Test-Simple-0.62.tar.gz\n cpan> o conf urllist push http://backpan.perl.org/\n" }, { "answer_id": 17101846, "author": "G. Cito", "author_id": 2019415, "author_profile": "https://Stackoverflow.com/users/2019415", "pm_score": 3, "selected": false, "text": "Carton Carton App::cpanminus App::cpanoutdated perlbrew Pinto" }, { "answer_id": 30540984, "author": "Ether", "author_id": 40468, "author_profile": "https://Stackoverflow.com/users/40468", "pm_score": 5, "selected": false, "text": "cpan install App::cpanminus\ncpanm Your::Module@1.23\n cpanm" }, { "answer_id": 36158342, "author": "Randall", "author_id": 584940, "author_profile": "https://Stackoverflow.com/users/584940", "pm_score": 2, "selected": false, "text": "cpanfile == <version> Carton cpanm" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
260,594
<p>My question is how do I configure an EJB 3.0 style message driven bean to use a configured JMS datasource in jboss. </p> <p>For example, my MDB looks something like:</p> <pre><code>@MessageDriven(mappedName = "ExampleMDB", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "MyTopic"), @ActivationConfigProperty(propertyName = "channel", propertyValue = "MyChannel"), }) @ResourceAdapter(value = "wmq.jmsra.rar") @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) @TransactionManagement(TransactionManagementType.BEAN) public class MyMDB implements MessageListener { ..... } </code></pre> <p>But I would like the bean to attached to a given JMS datasource ( in the case of jboss 4.2.2 this is in deploy/jms/jms-ds.xml). Perhaps this is not even possible but is worth asking.</p>
[ { "answer_id": 267783, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 7, "selected": false, "text": "cpan> install MSCHWERN/Test-Simple-0.62.tar.gz\n cpan> o conf urllist push http://backpan.perl.org/\n" }, { "answer_id": 17101846, "author": "G. Cito", "author_id": 2019415, "author_profile": "https://Stackoverflow.com/users/2019415", "pm_score": 3, "selected": false, "text": "Carton Carton App::cpanminus App::cpanoutdated perlbrew Pinto" }, { "answer_id": 30540984, "author": "Ether", "author_id": 40468, "author_profile": "https://Stackoverflow.com/users/40468", "pm_score": 5, "selected": false, "text": "cpan install App::cpanminus\ncpanm Your::Module@1.23\n cpanm" }, { "answer_id": 36158342, "author": "Randall", "author_id": 584940, "author_profile": "https://Stackoverflow.com/users/584940", "pm_score": 2, "selected": false, "text": "cpanfile == <version> Carton cpanm" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33864/" ]
260,597
<p>I'd like to receive error logs via email. For example, if a <code>Warning-level</code> error message should occur, I'd like to get an email about it.</p> <p>How can I get that working in CodeIgniter?</p>
[ { "answer_id": 260655, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 5, "selected": true, "text": "class MY_Exceptions extends CI_Exceptions {\n\n function __construct()\n {\n parent::__construct();\n }\n\n function log_exception($severity, $message, $filepath, $line)\n\n { \n if (ENVIRONMENT === 'production') {\n $ci =& get_instance();\n\n $ci->load->library('email');\n $ci->email->from('your@example.com', 'Your Name');\n $ci->email->to('someone@example.com');\n $ci->email->cc('another@another-example.com');\n $ci->email->bcc('them@their-example.com');\n $ci->email->subject('error');\n $ci->email->message('Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line);\n $ci->email->send();\n }\n\n\n parent::log_exception($severity, $message, $filepath, $line);\n }\n\n}\n" }, { "answer_id": 3379089, "author": "Jon Terry", "author_id": 407576, "author_profile": "https://Stackoverflow.com/users/407576", "pm_score": 2, "selected": false, "text": "$CI =& get_instance();\n $CI $this" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
260,605
<p>Is there a PHP class/library that would allow me to query an XHTML document with CSS selectors? I need to scrape some pages for data that is very easily accessible if I could somehow use CSS selectors (jQuery has spoiled me!). Any ideas?</p>
[ { "answer_id": 301155, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " $doc = new DOMDocument();\n $doc->loadHTML($html);\n\n $elements = $doc->getElementsByTagName(\"div\");\n foreach ($elements as $e){\n if ($e->getAttribute(\"class\")!=\"someclass\") continue;\n\n //its a div.classname\n }\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]