qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
235,455
<pre><code>string [] files = new string[2]; files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml"; files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml"; //Resharper complains this is an "access to modified closure" for (int i = 0; i &lt; files.Length; i++ ) { // Resharper disable AccessToModifiedClosure if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(), delegate(string name) { return name.Equals(files[i]); })) return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]); // ReSharper restore AccessToModifiedClosure } </code></pre> <p>The above seems to work fine though ReSharper complains that this is "access to modified closure". Can any one shed light on this?</p> <p>(this topic continued <a href="https://stackoverflow.com/questions/304258">here</a>)</p>
[ { "answer_id": 235459, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "i" }, { "answer_id": 15708331, "author": "gerrard00", "author_id": 1011470, "author_profile": "https://Stackoverflow.com/users/1011470", "pm_score": 5, "selected": false, "text": "private sealed class Closure\n{\n public string[] files;\n public int i;\n\n public bool YourAnonymousMethod(string name)\n {\n return name.Equals(this.files[this.i]);\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28413/" ]
235,470
<p>I was wondering about implementing my own sessions (more for an exercise than anything else) for a GAE app I'm working ... at first I was thinking of using the datastore to store the session data. However, every time something needs to be added to the session 'bucket', it would require saving to the datastore. Obviously that's bad since we want to minimize our writes. Then I thought about using memcache ... seemed like a good idea but then we're faced with issues of possible session corruption due to memcache being "evicted through memory pressure" by Google. So does that mean we are left with only the following options:</p> <ol> <li>Storing all session data in cookies</li> <li>Writing all session data to datastore and memcache, and then only reading from memcache</li> </ol> <p>Anyone have any other ideas?</p>
[ { "answer_id": 259462, "author": "massimo", "author_id": 24489, "author_profile": "https://Stackoverflow.com/users/24489", "pm_score": 0, "selected": false, "text": "from gluon.contrib.gql import *\ndb=GQLDB()\nsession.connect(request,response,db=db)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
235,484
<p>Can anyone suggest some references or other resources that are useful in learning MCML?</p> <p>I have a small pet project I have been working on for a while using C# and .Net 3.5. I have reached a point where I want to be able to send output from it to Windows Media Center, but I have been having a hard time finding coherent explanations of how to create MCML elements to represent my C# data objects. Particularly I am having a hard time finding information on creating an MCML element for each element in a C# collection. Any suggestions?</p>
[ { "answer_id": 259462, "author": "massimo", "author_id": 24489, "author_profile": "https://Stackoverflow.com/users/24489", "pm_score": 0, "selected": false, "text": "from gluon.contrib.gql import *\ndb=GQLDB()\nsession.connect(request,response,db=db)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,498
<p>Is there a way to show IE/Firefox Back button style, dropdown menu button?</p>
[ { "answer_id": 235646, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 3, "selected": false, "text": "procedure TForm86.Button1Click(Sender: TObject);\nvar\n button: TControl;\n lowerLeft: TPoint;\nbegin\n if Sender is TControl then\n begin\n button := TControl(Sender);\n lowerLeft := Point(button.Left, button.Top + Button.Height);\n lowerLeft := ClientToScreen(lowerLeft);\n PopupMenu1.Popup(lowerLeft.X, lowerLeft.Y);\n end;\nend;\n" }, { "answer_id": 1197386, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "procedure TForm86.Button1Click(Sender: TObject);\nvar\n button: TControl;\n lowerLeft: TPoint;\nbegin\n if Sender is TControl then\n begin\n button := TControl(Sender);\n lowerLeft := Point(0, button.Height);\n lowerLeft := button.ClientToScreen(lowerLeft);\n PopupMenu1.Popup(lowerLeft.X, lowerLeft.Y);\n end;\nend;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,504
<p>What is the best way to validate a crontab entry with PHP? Should I be using a regex, or an external library? I've got a PHP script that adds/removes entries from a crontab file, but want to have some way to verify that the time interval portion is in a valid format.</p>
[ { "answer_id": 235520, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "/^((\\*)|(\\d+((-\\d+)|(,\\d+)+))\\s+){5}/\n" }, { "answer_id": 235569, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 4, "selected": true, "text": "crontab" }, { "answer_id": 2610562, "author": "Jordi Salvat i Alabart", "author_id": 313149, "author_profile": "https://Stackoverflow.com/users/313149", "pm_score": 5, "selected": false, "text": "<?php\n/**\n * @author Jordi Salvat i Alabart - with thanks to <a href=\"www.salir.com\">Salir.com</a>.\n */\n\nabstract class CrontabChecker extends PHPUnit_Framework_TestCase {\n protected function assertFileIsValidUserCrontab($file) {\n $f= @fopen($file, 'r', 1);\n $this->assertTrue($f !== false, 'Crontab file must exist');\n while (($line= fgets($f)) !== false) {\n $this->assertLineIsValid($line);\n }\n }\n\n protected function assertLineIsValid($line) {\n $regexp= $this->buildRegexp();\n $this->assertTrue(preg_match(\"/$regexp/\", $line) !== 0);\n }\n\n private function buildRegexp() {\n $numbers= array(\n 'min'=>'[0-5]?\\d',\n 'hour'=>'[01]?\\d|2[0-3]',\n 'day'=>'0?[1-9]|[12]\\d|3[01]',\n 'month'=>'[1-9]|1[012]',\n 'dow'=>'[0-7]'\n );\n\n foreach($numbers as $field=>$number) {\n $range= \"($number)(-($number)(\\/\\d+)?)?\";\n $field_re[$field]= \"\\*(\\/\\d+)?|$range(,$range)*\";\n }\n\n $field_re['month'].='|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec';\n $field_re['dow'].='|mon|tue|wed|thu|fri|sat|sun';\n\n $fields_re= '('.join(')\\s+(', $field_re).')';\n\n $replacements= '@reboot|@yearly|@annually|@monthly|@weekly|@daily|@midnight|@hourly';\n\n return '^\\s*('.\n '$'.\n '|#'.\n '|\\w+\\s*='.\n \"|$fields_re\\s+\\S\".\n \"|($replacements)\\s+\\S\".\n ')';\n }\n}\n" }, { "answer_id": 10471978, "author": "ph4r05", "author_id": 1378053, "author_profile": "https://Stackoverflow.com/users/1378053", "pm_score": 2, "selected": false, "text": "<?php\n/**\n * @author Jordi Salvat i Alabart - with thanks to <a href=\"www.salir.com\">Salir.com</a>.\n */\n\nfunction buildRegexp() {\n $numbers = array(\n 'min' => '[0-5]?\\d',\n 'hour' => '[01]?\\d|2[0-3]',\n 'day' => '0?[1-9]|[12]\\d|3[01]',\n 'month' => '[1-9]|1[012]',\n 'dow' => '[0-6]'\n );\n\n foreach ($numbers as $field => $number) {\n $range = \"(?:$number)(?:-(?:$number)(?:\\/\\d+)?)?\";\n $field_re[$field] = \"\\*(?:\\/\\d+)?|$range(?:,$range)*\";\n }\n\n $field_re['month'].='|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec';\n $field_re['dow'].='|mon|tue|wed|thu|fri|sat|sun';\n\n $fields_re = '(' . join(')\\s+(', $field_re) . ')';\n\n $replacements = '@reboot|@yearly|@annually|@monthly|@weekly|@daily|@midnight|@hourly';\n\n return '^\\s*(' .\n '$' .\n '|#' .\n '|\\w+\\s*=' .\n \"|$fields_re\\s+\" .\n \"|($replacements)\\s+\" .\n ')' .\n '([^\\\\s]+)\\\\s+' .\n '(.*)$';\n}\n" }, { "answer_id": 27429522, "author": "Andrey", "author_id": 3621944, "author_profile": "https://Stackoverflow.com/users/3621944", "pm_score": 0, "selected": false, "text": "sub _BuildRegex {\n my $number = {\n 'min' => '[0-5]?\\d',\n 'hour' => '[01]?\\d|2[0-3]',\n 'day' => '0?[1-9]|[12]\\d|3[01]',\n 'month' => '[1-9]|1[012]',\n 'dow' => '[0-6]'\n };\n\n my $field_re = {};\n foreach my $nmb ( qw/min hour day month dow/ ) {\n my $range = \"(?:$number->{$nmb})(?:-(?:$number->{$nmb})(?:\\\\/\\\\d+)?)?\";\n $field_re->{$nmb} = \"\\\\*(?:\\\\/\\\\d+)?|$range(?:,$range)*\";\n }\n\n $field_re->{'month'} .='|[jJ]an|[fF]eb|[mM]ar|[aA]pr|[mM]ay|[jJ]un|[jJ]ul|[aA]ug|[sS]ep|[oO]ct|[nN]ov|[dD]ec';\n $field_re->{'dow'} .= '|[mM]on|[tT]ue|[wW]ed|[tT]hu|[fF]ri|[sS]at|[sS]un';\n\n my $ff = [];\n push @$ff, $field_re->{$_} foreach ( qw/min hour day month dow/ );\n\n my $fields_req = '(' . join(')\\s+(', @$ff) . ')';\n\n my $replacements = '@reboot|@yearly|@annually|@monthly|@weekly|@daily|@midnight|@hourly';\n\n return '^\\s*(' .\n '$' .\n '|#' .\n '|\\w+\\s*=' .\n \"|$fields_req\\\\s+\" .\n \"|($replacements)\\\\s+\" .\n ')' .\n '([^\\\\s]+)\\\\s+' .\n '(.*)$';\n}\n" }, { "answer_id": 35477195, "author": "night1008", "author_id": 3551856, "author_profile": "https://Stackoverflow.com/users/3551856", "pm_score": 1, "selected": false, "text": "/^((?:[1-9]?\\d|\\*)\\s*(?:(?:[\\/-][1-9]?\\d)|(?:,[1-9]?\\d)+)?\\s*){5}$/\n" }, { "answer_id": 40468733, "author": "Sergii Ivashchenko", "author_id": 1518080, "author_profile": "https://Stackoverflow.com/users/1518080", "pm_score": 2, "selected": false, "text": "composer require mtdowling/cron-expression\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
235,515
<p>Way back when I was working in an Oracle shop I took the CONNECT_BY for granted. Now I'm stuck working with SQL Server 2005 and have some nasty object hierarchies. Specifically, we have a self referencing table where all child records have a column with their parent's id. Currently we have a view that maps children to levels in the hierarchy and a nasty query that does the heavy lifting to connect parents with their children. While this method works, it is far from elegant and reeks of taint. I'm just curious how other people retrieve hierarchical data from SQL Server 2005.</p>
[ { "answer_id": 235534, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 5, "selected": false, "text": "CREATE TABLE tblHierarchy (ID int, ParentID int NULL, Name varchar(128));\n\nINSERT INTO tblHierarchy VALUES (1, NULL, '1');\nINSERT INTO tblHierarchy VALUES (2, NULL, '2');\nINSERT INTO tblHierarchy VALUES (3, NULL, '3');\nINSERT INTO tblHierarchy VALUES (4, 1, '1.1');\nINSERT INTO tblHierarchy VALUES (5, 1, '1.2');\nINSERT INTO tblHierarchy VALUES (6, 4, '1.1.1');\n\nWITH Parent AS\n(\n SELECT\n ID,\n ParentID,\n Name AS Path\n FROM\n tblHierarchy\n WHERE\n ParentID IS NULL\n\n UNION ALL\n\n SELECT\n TH.ID,\n TH.ParentID,\n CONVERT(varchar(128), Parent.Path + '/' + TH.Name) AS Path\n FROM\n tblHierarchy TH\n INNER JOIN\n Parent\n ON\n Parent.ID = TH.ParentID\n)\nSELECT * FROM Parent\n" }, { "answer_id": 9529223, "author": "Noora Akhtar", "author_id": 1244481, "author_profile": "https://Stackoverflow.com/users/1244481", "pm_score": 0, "selected": false, "text": "declare @tempTable TABLE\n(\n ORGUID int,\n ORGNAME nvarchar(100), \n PARENTORGUID int,\n ORGPATH nvarchar(max)\n)\n\n;WITH RECORG(ORGuid, ORGNAME, PARENTORGUID, ORGPATH)\nas\n(\n select \n org.UID,\n org.Name,\n org.ParentOrganizationUID,\n dbo.fGetOrganizationBreadcrumbs(org.UID)\n from Organization org\n where org.UID =1\n\n union all\n\n select \n orgRec.UID,\n orgRec.Name,\n orgRec.ParentOrganizationUID,\n dbo.fGetOrganizationBreadcrumbs(orgRec.UID) \n from Organization orgRec\n inner join RECORG recOrg on orgRec.ParentOrganizationUID = recOrg.ORGuid\n\n)\ninsert into @tempTable(ORGUID, ORGNAME, PARENTORGUID,ORGPATH)\n\nselect ORGUID, ORGNAME, PARENTORGUID,ORGPATH \nfrom RECORG rec \n\nselect * \nfrom @tempTable where ORGUID in(select MIN(tt.ORGUID) \n from @tempTable tt \n group by tt.PARENTORGUID)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31336/" ]
235,556
<p>Using jQuery, how would you <code>show()</code> every <code>div.foo</code> on a page in a random order, with a new one appearing every X milliseconds?</p> <p><strong>Clarification</strong>: I want to start with all these elements hidden and end with all of them showing, so it wouldn't make sense to <code>show()</code> the same element twice.</p> <p>I originally thought I'd make an array listing all the elements, randomly pick one, show that one, remove it from the array using <code>splice()</code>, and then randomly pick the next one from the remaining list - etc. But since my array is part of a jQuery object, <code>splice()</code> is not available.</p>
[ { "answer_id": 235705, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 1, "selected": false, "text": "var intervalMilliseconds = X; // set to your value for X\nvar divFoos = $(\"div.foo\").get();\nvar intervalId = setInterval(function() {\n $(divFoos.splice(Math.floor(Math.random() * divFoos.length), 1)).show();\n if(divFoos.length == 0) clearInterval(intervalId);\n}, intervalMilliseconds);\n" }, { "answer_id": 235775, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "(function () {\n var int, els;\n int = 100; // interval, in milliseconds\n els = $('div.foo');\n setInterval(function () {\n var idx;\n idx = Math.floor(els.length * Math.random());\n $(els[idx]).show();\n setTimeout(function () {\n $(els[idx]).hide();\n }, int);\n }, int);\n})();\n" }, { "answer_id": 235937, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 3, "selected": true, "text": "Object.extend(Array.prototype, {\n shuffle : function() {\n this.sort( function() { return 0.5 - Math.random(); } );\n return this;\n }\n});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ]
235,558
<p>When a user clicks a link to download a file on my website, they go to <a href="http://viewsourcecode.org/viewsource/homebrew.php" rel="noreferrer">this PHP file</a> which increments a download counter for that file and then header()-redirects them to the actual file. I suspect that bots are following the download link, however, so the number of downloads is inaccurate.</p> <ul> <li>How do I let bots know that they shouldn't follow the link?</li> <li>Is there a way to detect most bots?</li> <li>Is there a better way to count the number of downloads a file gets?</li> </ul>
[ { "answer_id": 235609, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 2, "selected": false, "text": "grep -c" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
235,560
<p>I've been getting some OutOfMemory errors lately in my application. Is it possible to detect ahead of time when the virtual machine is running low on memory? In other words to preemptively deal with OutOfMemory errors before they actually occur?</p>
[ { "answer_id": 235662, "author": "TheMarko", "author_id": 31099, "author_profile": "https://Stackoverflow.com/users/31099", "pm_score": 2, "selected": false, "text": "Runtime.getRuntime().freeMemory()\n" }, { "answer_id": 235701, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 3, "selected": false, "text": "java.lang.management.MemoryMXBean" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
235,564
<p>I am using a mock object in RhinoMocks to represent a class that makes calls to MessageQueue.GetPublicQueues. I want to simulate the exception thrown when message queueing is operating in workgroup mode, which is a MessageQueueException, to ensure that I am catching the exception correctly</p> <p>The MessageQueueException has no public constructor, only the standard protected constructor for an exception. Is there an appropriate way to throw this exception from the mock object / Expect.Call statement?</p>
[ { "answer_id": 235703, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 4, "selected": true, "text": "using System.Reflection;\nusing System.Messaging;\n...\n Type t = typeof(MessageQueueException);\n ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, \n null, new Type[] { typeof(int) }, null);\n MessageQueueException ex = (MessageQueueException)ci.Invoke(new object[] { 911 });\n throw ex;\n" }, { "answer_id": 294573, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 2, "selected": false, "text": "MessageQueue mq = MessageQueue.Create(\"\\\\invalid\");\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21862/" ]
235,604
<p>What is the best way to overwrite a specific line in a file? I basically want to search a file for the string '@parsethis' and overwrite the rest of that line with something else.</p>
[ { "answer_id": 235655, "author": "Gaurav", "author_id": 13492, "author_profile": "https://Stackoverflow.com/users/13492", "pm_score": -1, "selected": false, "text": "$cmd = \"grep '@parsethis' \" . $filename;\n$output = system($cmd, $result);\n$lines = explode(\"\\n\", $result);\n// Read the entire file as a string\n// Do a str_repalce for each item in $lines with \"\"\n" }, { "answer_id": 235672, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": false, "text": "flock()" }, { "answer_id": 236082, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 4, "selected": false, "text": "$source='in.txt';\n$target='out.txt';\n\n// copy operation\n$sh=fopen($source, 'r');\n$th=fopen($target, 'w');\nwhile (!feof($sh)) {\n $line=fgets($sh);\n if (strpos($line, '@parsethis')!==false) {\n $line='new line to be inserted' . PHP_EOL;\n }\n fwrite($th, $line);\n}\n\nfclose($sh);\nfclose($th);\n\n// delete old source file\nunlink($source);\n// rename target file to source file\nrename($target, $source);\n" }, { "answer_id": 236117, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "$sample = file_get_contents('sample');\n$parsed =preg_replace('#@parsethis.*#', 'REPLACE TO END OF LINE', $sample);\n" }, { "answer_id": 53302259, "author": "deusoz", "author_id": 4381739, "author_profile": "https://Stackoverflow.com/users/4381739", "pm_score": 1, "selected": false, "text": "$command = \"pathToShellScript folder1Name folder2Name myStyleVarName myStyleVarProp\";\nshell_exec($command);\n\n/* shellScript */\n#!/bin/bash\nfile=/var/www/vhosts/mydomain.com/$1/$2/scss/_variables.scss\nstr=$3\"$4\"\nsed -i \"s/^$3.*/$str;/\" $file\n" }, { "answer_id": 55702438, "author": "Adrian J G", "author_id": 10563082, "author_profile": "https://Stackoverflow.com/users/10563082", "pm_score": 0, "selected": false, "text": "rename(\"./some_path/data.txt\", \"./some_path/data_backup.txt\");\nrename(\"./some_path/new_data.txt\", \"./some_path/data.txt\");\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
235,608
<p>I have the following situation:</p> <p>A user will define a certain filter on a page, and on postback I will query the database using that filter and return a bunch of matching records to the user, each with a checkbox next to it, so he can choose whether to act on each of those records.</p> <p>In Classic ASP / PHP I can generate a lot of controls named "chk__*" and then on postback go through all the $<em>POST entries looking for the ones prefixed "chk</em>".</p> <p>What is the best way to do this in ASP.Net 2.0?</p> <p>I can do it easily by implementing a Repeater with a Template containing the checkbox, bind the Repeater to a Dataset, and then on the second Postback, I just do:</p> <pre><code>For Each it As RepeaterItem In repContacts.Items Dim chkTemp As CheckBox = DirectCast(it.FindControl("cbSelect"), CheckBox) If chkTemp.Checked Then End If Next </code></pre> <p>However this has the <em>slight</em> disadvantage of giving me a HUGE Viewstate, which is really bad because the client will need to re-upload the whole viewstate to the server, and these people will probably be using my site over a crappy connection.</p> <p>Any other ideas? (I can also create the controls dynamically and iterate through Request.Form as in the old days, however, I was looking for a cleaner </p>
[ { "answer_id": 235849, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<script type='text/javascript'>\n function record(checkbox,item)\n {\n var context = { ctl : checkbox };\n PageMethods.Record(item,checkbox.checked,onSuccess,onFailure,context);\n }\n\n function onSuccess(result,context)\n {\n // do something, maybe highlight the row, maybe nothing\n }\n\n function onFailure(error,context)\n {\n context.ctl.checked = false;\n alert(error.get_Message());\n }\n</script>\n\n\n...\n<tr><td><input type='checkbox' onclick='record(this,\"item_1\");'></td><td>Item 1</td></tr>\n...\n\nCodebehind\n\n[WebMethod(EnableSessionState=true)]\npublic static void Record( string itemName, bool value )\n{\n List<string> itemList = (List<string>)Session[\"Items\"];\n if (itemList == null)\n {\n itemList = new List<string>();\n Session[\"Items\"] = itemList;\n }\n if (itemList.Contains(itemName) && !value)\n {\n itemList.Remove(itemName);\n }\n else if (!itemList.Contains(itemName) && value)\n {\n itemList.Add(itemName);\n } \n}\n\nprotected void button_OnClick( object sender, EventArgs e )\n{\n List<string> itemList = (List<string>)Session[\"Items\"];\n if (itemList != null)\n {\n foreach (string item in itemList)\n {\n // do something with the selected item\n }\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
235,616
<p>Suppose a header file defines a function template. Now suppose two implementation files <code>#include</code> this header, and each of them has a call to the function template. In both implementation files the function template is instantiated with the same type.</p> <pre><code>// header.hh template &lt;typename T&gt; void f(const T&amp; o) { // ... } // impl1.cc #include "header.hh" void fimpl1() { f(42); } // impl2.cc #include "header.hh" void fimpl2() { f(24); } </code></pre> <p>One may expect the linker would complain about multiple definitions of <code>f()</code>. Specifically, if <code>f()</code> wouldn't be a template then that would indeed be the case.</p> <ul> <li>How come the linker doesn't complain about multiple definitions of <code>f()</code>?</li> <li>Is it specified in the standard that the linker must handle this situation gracefully? In other words, can I always count on programs similar to the above to compile and link?</li> <li>If the linker can be clever enough to disambiguate a set of function template instantiations, why can't it do the same for regular functions, given they are identical as is the case for instantiated function templates?</li> </ul>
[ { "answer_id": 235640, "author": "CAdaker", "author_id": 30579, "author_profile": "https://Stackoverflow.com/users/30579", "pm_score": 1, "selected": false, "text": "extern" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456/" ]
235,618
<p>I received an error when an referenced .NET Framework 2.0 assembly tried to execute the following line of code in an IIS hosted WCF service:</p> <p>Error Message:</p> <blockquote> <p>exePath must be specified when not running inside a stand alone exe.</p> </blockquote> <p>Source Code:</p> <pre><code>ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); </code></pre> <p>Has anyone experienced this issue and do they know how to resolve it?</p> <p><b>EDIT:</b> My question is, what is the best way to open a configuration file (app.config and web.config) from a WCF service that is backwards compatible with a .NET 2.0 assembly?</p>
[ { "answer_id": 252356, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 2, "selected": false, "text": "//Open app.config or web.config file\nif (HttpContext.Current != null)\n this.m_ConfigFile = WebConfigurationManager.OpenWebConfiguration(\"~\");\nelse\n this.m_ConfigFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n" }, { "answer_id": 273933, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 3, "selected": true, "text": "string MySetting = ConfigurationManager.AppSettings.Get(\"MyAppSetting\");\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
235,650
<p>There are many different styles of variable names that I've come across over the years.</p> <p>The current wikipedia entry on naming conventions is fairly light... </p> <p>I'd love to see a concise catalog of variable naming-conventions, identifying it by a name/description, and some examples. </p> <p>If a convention is particularly favored by a certain platform community, that would be worth noting, too.</p> <p>I'm turning this into a community wiki, so please create an answer for each convention, and edit as needed.</p>
[ { "answer_id": 235666, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "int i;\nchar c;\nfloat myWidth;\n" }, { "answer_id": 235710, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 2, "selected": false, "text": "foo\nparse_foo\na_long_descriptive_name\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22329/" ]
235,651
<p>I have the following string expression in a PowerShell script:</p> <pre><code>"select count(*) cnt from ${schema}.${table} where ${col.column_name} is null" </code></pre> <p>The schema and table resolve to the values of $schema and $table, respectively. However, an empty string is supplied for ${col.column_name}. How can I dot into the member of a variable as part of a string substitution?</p>
[ { "answer_id": 235669, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": true, "text": "\"select count(*) cnt from $schema.$table where $($col.column_name) is null\"\n" }, { "answer_id": 235679, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "\"select count(*) cnt from $schema.$table where $($col.column_name) is null\"\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20625/" ]
235,664
<p>After looking at another question on SO (<a href="https://stackoverflow.com/questions/235386/using-nan-in-c">Using NaN in C++</a>) I became curious about <code>std::numeric_limits&lt;double&gt;::signaling_NaN()</code>.</p> <p>I could not get signaling_NaN to throw an exception. I thought perhaps by signaling it really meant a signal so I tried catching SIGFPE but nope...</p> <p>Here is my code:</p> <pre><code>double my_nan = numeric_limits&lt;double&gt;::signaling_NaN(); my_nan++; my_nan += 5; my_nan = my_nan / 10; my_nan = 15 / my_nan; cout &lt;&lt; my_nan &lt;&lt; endl; </code></pre> <p><code>numeric_limits&lt;double&gt;::has_signaling_NaN</code> evaluates to true, so it is implemented on my system.</p> <p>Any ideas?</p> <p>I am using ms visual studio .net 2003's C++ compiler. I want to test it on another when I get home.</p> <p>Thanks!</p>
[ { "answer_id": 235677, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 1, "selected": false, "text": "cout << \"The signaling NaN for type float is: \"\n << numeric_limits<float>::signaling_NaN( )\n << endl;\n" }, { "answer_id": 236025, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 4, "selected": true, "text": "_control87()" }, { "answer_id": 236717, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "numeric_limits<T>::has_signaling_NaN" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29703/" ]
235,671
<p>I wanted to add a UTF-8 font in Gvim but I could not find out how to do this. I tried to follow the step on this manual but it still did not work. <a href="http://www.inter-locale.com/whitepaper/learn/learn_to_type.html" rel="noreferrer">http://www.inter-locale.com/whitepaper/learn/learn_to_type.html</a> (vim section halfway the page)</p> <p>Can anyone tell me how to add a font in Vim so I can have Japanese characters displayed ?</p>
[ { "answer_id": 237002, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 3, "selected": false, "text": " :set guifont=courier_new:h12\n" }, { "answer_id": 243943, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 4, "selected": false, "text": ":set guifont=*\n" }, { "answer_id": 4828071, "author": "atomicules", "author_id": 208793, "author_profile": "https://Stackoverflow.com/users/208793", "pm_score": 4, "selected": false, "text": "set guifont=Consolas:h10 \nset guifontwide=MingLiU:h10 \"For windows to display mixed character sets\nset encoding=utf-8 \n" }, { "answer_id": 14613767, "author": "ThomasJ", "author_id": 2026997, "author_profile": "https://Stackoverflow.com/users/2026997", "pm_score": 2, "selected": false, "text": "set gfn=MingLiU:h16:cDEFAULT\nset fenc=utf-8\nset encoding=utf-8\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18383/" ]
235,685
<p>How, in Java, to quickly (or generically) convert one class that implements an interface into another class that implements the same interface?</p> <p>I mean, if they're a POJO one class setters should take the other class getters as arguments.</p> <p>Is there a Pattern for this situation?</p>
[ { "answer_id": 235691, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 2, "selected": false, "text": "org.apache.commons.beanutils.BeanUtils\n .BeanUtils.copyProperties\n\npublic static void copyProperties(Object dest, Object orig)\n throws IllegalAccessException,\n InvocationTargetException\n\nCopy property values from the origin bean to the destination bean for all cases where the property names are the same.\n\nFor more details see BeanUtilsBean.\n\nParameters:\n dest - Destination bean whose properties are modified\n orig - Origin bean whose properties are retrieved \n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,694
<p>In the filesystem I have</p> <pre> /file.aspx /directory/default.aspx </pre> <p>I want to configure IIS so that it returns the appropriate file (add the aspx extension) or directory (default content page) as follows:</p> <pre> /file -> /file.aspx /directory -> /directory/default.aspx /directory/ -> /directory/default.aspx </pre> <p>I have configured the Wildcard application mapping set to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll. When the "Verify that file exists" is unchecked, the the file request works but not the directory request (returns 404). When the "Verify that file exists" is checked, the directory request works but not the file request.</p> <p>How can I configure it so that both the file and directory requests will work?</p>
[ { "answer_id": 248777, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<rewrite url=\"^/file$\" to=\"/file.aspx\" />\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6944/" ]
235,695
<p>I have a script that slides a div down from behind the menu, when people click on the tab. However its in jquery and I want to use mootools (lots of reasons I wont go into here). However im stuck with mootools 1.1 at present. But for some reason my attempt is not working :(</p> <p>The html</p> <pre><code>print("code sample"); &lt;div id="panel"&gt; &lt;form action=""&gt; &lt; form here &gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="slide"&gt; &lt;p class="sl"&gt;&lt;a href="#" class="btn-slide" id="toggle"&gt;&lt;span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt; </code></pre> <p>Div id panel holds the form which slides down, div class slide and the P tag is replaced by a tab/button which hangs down via css, clicking on this slides the tab down.</p> <p>The jquery (which works fine)</p> <pre><code>print("code sample"); &lt;script type="text/javascript"&gt; $j(document).ready(function(){ $j(".btn-slide").click(function(){ $j("#panel").slideToggle("slow"); $j(this).toggleClass("active"); return false; }); }); &lt;/script&gt; </code></pre> <p>My moo attempt</p> <pre><code>print("code sample"); &lt;script type="text/javascript"&gt; window.addEvent('domready', function(){ var mySlide = new Fx.Slide('panel'); $('toggle').addEvent('click', function(e){ e = new Event(e); mySlide.toggle(); e.stop(); }); }); &lt;/script&gt; </code></pre> <p>Like I said above I am restricted to moo 1.1 at present, but if there is a answer that will work with both 1.1 and 1.2 or if its a similar change I would be grateful to hear, as it will be updated at some point.</p>
[ { "answer_id": 248777, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<rewrite url=\"^/file$\" to=\"/file.aspx\" />\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
235,759
<p>I <em>think</em> I know how to create custom encrypted RSA keys, but how can I read one encrypted like ssh-keygen does?</p> <p>I know I can do this:</p> <pre><code>OpenSSL::PKey::RSA.new(File.read('private_key')) </code></pre> <p>But then OpenSSL asks me for the passphrase... How can I pass it to OpenSSL as a parameter?</p> <p>And, how can I create one compatible to the ones generated by ssh-keygen?</p> <p>I do something like this to create private encrypted keys:</p> <pre><code>pass = '123456' key = OpenSSL::PKey::RSA.new(1024) key = "0000000000000000#{key.to_der}" c = OpenSSL::Cipher::Cipher.new('aes-256-cbc') c.encrypt c.key = Digest::SHA1.hexdigest(pass).unpack('a2' * 32).map {|x| x.hex}.pack('c' * 32) c.iv = iv encrypted_key = c.update(key) encrypted_key &lt;&lt; c.final </code></pre> <p>Also, keys generated by OpenSSL::PKey::RSA.new(1024) (without encryption), don't work when I try password-less logins (i.e., I copy the public key to the server and use the private one to login).</p> <p>Also, when I open an ssh-keygen file via OpenSSL and then check its contents, it appears to have additional characters at the beginning and end of the key. Is this normal?</p> <p>I don't really understand some of this security stuff, but I'm trying to learn. What is it that I'm doing wrong?</p>
[ { "answer_id": 235847, "author": "Ivan", "author_id": 16957, "author_profile": "https://Stackoverflow.com/users/16957", "pm_score": -1, "selected": true, "text": "Net::SSH::KeyFactory.load_private_key 'keyfile', 'passphrase'\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957/" ]
235,787
<p>Do you primarily think of reasons TO implement it, or reasons NOT TO implement it? What are the advantages of each?</p>
[ { "answer_id": 235836, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "feature" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18658/" ]
235,822
<p>How can my vbscript detect whether or not it is running in a UAC elevated context?</p> <p>I have no problem detecting the user, and seeing if the user is within the Administrators group. But this still doesn't answer the question of whether the process has elevated privs or not, when running under Vista or Windows 2008. Please note, I need only to <em>detect</em> this status; not attempt to elevate or (err ..) de-elevate.</p>
[ { "answer_id": 258070, "author": "quux", "author_id": 2383, "author_profile": "https://Stackoverflow.com/users/2383", "pm_score": 4, "selected": true, "text": "sub GetOSVersion\nDim strComputer, oWMIService, colOSInfo, oOSProperty, strCaption, strOSFamily\nstrComputer = \".\"\nSet oWMIService = GetObject(\"winmgmts:\\\\\" & strComputer & \"\\root\\cimv2\")\nSet colOSInfo = oWMIService.ExecQuery(\"Select * from Win32_OperatingSystem\")\n'I hate looping through just to get one property. But dunno another way!\nFor Each oOSProperty in colOSInfo \n strCaption = oOSProperty.Caption \nNext\nIf InStr(1,strCaption, \"Vista\", vbTextCompare) Then strOSFamily = \"Vista\"\nIf InStr(1,strCaption, \"2008\", vbTextCompare) Then strOSFamily = \"2008\"\nIf InStr(1,strCaption, \"XP\", vbTextCompare) Then strOSFamily = \"XP\"\nIf InStr(1,strCaption, \"2003\", vbTextCompare) Then strOSFamily = \"2003\"\nIf InStr(1,strCaption, \"2000\", vbTextCompare) Then strOSFamily = \"2000\"\nIf strOSFamily = \"\" Then \n Wscript.Echo \"No known OS found. (Script can detect Windows 2000, 2003, XP, Vista, 2008.)\" \nElse \n Wscript.Echo \"OS Family = \" & strOSFamily\nEnd If\nSelect Case strOSFamily 'if Vista/2008 then call CheckforElevation\nCase \"Vista\"\n CheckforElevation\nCase \"2008\"\n CheckforElevation\nCase Else\n Exit Sub\nEnd Select\nend sub\n\nsub CheckforElevation 'test whether user has elevated token \nDim oShell, oExecWhoami, oWhoamiOutput, strWhoamiOutput, boolHasElevatedToken\nSet oShell = CreateObject(\"WScript.Shell\")\nSet oExecWhoami = oShell.Exec(\"whoami /groups\")\nSet oWhoamiOutput = oExecWhoami.StdOut\nstrWhoamiOutput = oWhoamiOutput.ReadAll\nIf InStr(1, strWhoamiOutput, \"S-1-16-12288\", vbTextCompare) Then boolHasElevatedToken = True\nIf boolHasElevatedToken Then\n Wscript.Echo \"Current script is running with elevated privs.\"\nElse\n Wscript.Echo \"Current script is NOT running with elevated privs.\"\nEnd If\nend sub\n" }, { "answer_id": 19894732, "author": "Keith S Garner", "author_id": 2863832, "author_profile": "https://Stackoverflow.com/users/2863832", "pm_score": 3, "selected": false, "text": "Function IsElevated\n IsElevated = CreateObject(\"WScript.Shell\").Run(\"cmd.exe /c \"\"whoami /groups|findstr S-1-16-12288\"\"\", 0, true) = 0\nEnd function \n" }, { "answer_id": 30484751, "author": "Alexey", "author_id": 4945039, "author_profile": "https://Stackoverflow.com/users/4945039", "pm_score": 0, "selected": false, "text": "function isElevated(){\n var strCaption = \"\";\n for (var enumItems=new Enumerator(GetObject(\"winmgmts:\\\\\\\\.\\\\root\\\\CIMV2\").ExecQuery(\"Select * from Win32_OperatingSystem\")); !enumItems.atEnd(); enumItems.moveNext()) {\n strCaption += enumItems.item().Caption;\n }\n if(/Vista|2008|Windows\\s7|Windows\\s8/.test(strCaption)){\n return (new ActiveXObject(\"WScript.Shell\").run('cmd.exe /c \"whoami /groups|findstr S-1-16-12288\"', 0, true)) == 0;\n }else{return true}\n} \n\nWScript.Echo(isElevated());\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2383/" ]
235,839
<p>It should be trivial, and it might even be in the help, but I can't figure out how to navigate it. How do I indent multiple lines quickly in vi?</p>
[ { "answer_id": 235841, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 12, "selected": true, "text": "shiftwidth" }, { "answer_id": 235876, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 6, "selected": false, "text": "ma" }, { "answer_id": 235891, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 5, "selected": false, "text": ">}" }, { "answer_id": 235897, "author": "svec", "author_id": 103, "author_profile": "https://Stackoverflow.com/users/103", "pm_score": 7, "selected": false, "text": ":help =" }, { "answer_id": 463129, "author": "Johan", "author_id": 51425, "author_profile": "https://Stackoverflow.com/users/51425", "pm_score": 7, "selected": false, "text": "gg=G\n" }, { "answer_id": 550381, "author": "Michael Ekoka", "author_id": 56974, "author_profile": "https://Stackoverflow.com/users/56974", "pm_score": 5, "selected": false, "text": "vnoremap < <gv\n\nvnoremap > >gv\n" }, { "answer_id": 1716803, "author": "pankaj ukumar", "author_id": 208889, "author_profile": "https://Stackoverflow.com/users/208889", "pm_score": 4, "selected": false, "text": "$vi .vimrc\n" }, { "answer_id": 5212123, "author": "ire_and_curses", "author_id": 143804, "author_profile": "https://Stackoverflow.com/users/143804", "pm_score": 10, "selected": false, "text": "shiftwidth" }, { "answer_id": 8720699, "author": "Eric Kigathi", "author_id": 181453, "author_profile": "https://Stackoverflow.com/users/181453", "pm_score": 4, "selected": false, "text": "VISUAL MODE" }, { "answer_id": 9330763, "author": "jash", "author_id": 1216556, "author_profile": "https://Stackoverflow.com/users/1216556", "pm_score": 4, "selected": false, "text": ">}" }, { "answer_id": 10876560, "author": "mda", "author_id": 1124854, "author_profile": "https://Stackoverflow.com/users/1124854", "pm_score": 3, "selected": false, "text": "set expandtab\nset tabstop=2\nset shiftwidth=2\n" }, { "answer_id": 12478748, "author": "Juan Lanus", "author_id": 243303, "author_profile": "https://Stackoverflow.com/users/243303", "pm_score": 4, "selected": false, "text": "'" }, { "answer_id": 16413270, "author": "rohitkadam19", "author_id": 1118854, "author_profile": "https://Stackoverflow.com/users/1118854", "pm_score": 3, "selected": false, "text": "5==" }, { "answer_id": 17419780, "author": "John La Rooy", "author_id": 174728, "author_profile": "https://Stackoverflow.com/users/174728", "pm_score": 3, "selected": false, "text": ">" }, { "answer_id": 19793684, "author": "NickSoft", "author_id": 676439, "author_profile": "https://Stackoverflow.com/users/676439", "pm_score": 3, "selected": false, "text": "vimrc" }, { "answer_id": 20736610, "author": "Eric Leschinski", "author_id": 445131, "author_profile": "https://Stackoverflow.com/users/445131", "pm_score": 3, "selected": false, "text": ":" }, { "answer_id": 21593765, "author": "Kamlesh", "author_id": 413148, "author_profile": "https://Stackoverflow.com/users/413148", "pm_score": 3, "selected": false, "text": ".vimrc" }, { "answer_id": 23160198, "author": "Sagar Jain", "author_id": 3345302, "author_profile": "https://Stackoverflow.com/users/3345302", "pm_score": 6, "selected": false, "text": "gg=G" }, { "answer_id": 24754427, "author": "attaboyabhipro", "author_id": 619328, "author_profile": "https://Stackoverflow.com/users/619328", "pm_score": 4, "selected": false, "text": ":line_num_start,line_num_end>\n" }, { "answer_id": 27573309, "author": "Michael", "author_id": 3590337, "author_profile": "https://Stackoverflow.com/users/3590337", "pm_score": 2, "selected": false, "text": "esc 4G=G\n" }, { "answer_id": 28255525, "author": "John Sonderson", "author_id": 2610873, "author_profile": "https://Stackoverflow.com/users/2610873", "pm_score": 4, "selected": false, "text": ":set shiftwidth=2\n" }, { "answer_id": 32141674, "author": "Nykakin", "author_id": 1542900, "author_profile": "https://Stackoverflow.com/users/1542900", "pm_score": 4, "selected": false, "text": "norm i" }, { "answer_id": 32509423, "author": "zundarz", "author_id": 780477, "author_profile": "https://Stackoverflow.com/users/780477", "pm_score": 3, "selected": false, "text": ":help left" }, { "answer_id": 46479908, "author": "sqqqrly", "author_id": 5474110, "author_profile": "https://Stackoverflow.com/users/5474110", "pm_score": 3, "selected": false, "text": "I" }, { "answer_id": 50016181, "author": "builder-7000", "author_id": 5411198, "author_profile": "https://Stackoverflow.com/users/5411198", "pm_score": 0, "selected": false, "text": "|" }, { "answer_id": 63043192, "author": "Mamrezo", "author_id": 3550735, "author_profile": "https://Stackoverflow.com/users/3550735", "pm_score": 3, "selected": false, "text": "<TAB>" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
235,851
<p>Does anyone know if it is possible to convert a HTML page (url) to a PDF using iText?</p> <p>If the answer is 'no' than that is OK as well since I will stop wasting my time trying to work it out and just spend some money on one of a number of components which I know can :)</p>
[ { "answer_id": 11960922, "author": "Jes", "author_id": 208344, "author_profile": "https://Stackoverflow.com/users/208344", "pm_score": 1, "selected": false, "text": "Paragraph" }, { "answer_id": 46033835, "author": "Joris Schellekens", "author_id": 6074376, "author_profile": "https://Stackoverflow.com/users/6074376", "pm_score": 2, "selected": false, "text": " HtmlConverter.convertToPdf(\n \"<b>This text should be written in bold.</b>\", // html to be converted\n new PdfWriter(\n new File(\"C://users/mark/documents/output.pdf\") // destination file\n )\n );\n" }, { "answer_id": 58029729, "author": "Asad Rao", "author_id": 852406, "author_profile": "https://Stackoverflow.com/users/852406", "pm_score": 1, "selected": false, "text": "String htmlFilePath = filePath + \".html\";\nString pdfFilePath = filePath + \".pdf\";\n\n// create an html file on given file path\nWriter unicodeFileWriter = new OutputStreamWriter(new FileOutputStream(htmlFilePath), \"UTF-8\");\nunicodeFileWriter.write(document.toString());\nunicodeFileWriter.close();\n\nConverterProperties properties = new ConverterProperties();\nproperties.setCharset(\"UTF-8\");\nif (url.contains(\".kr\") || url.contains(\".tw\") || url.contains(\".cn\") || url.contains(\".jp\")) {\n properties.setFontProvider(new DefaultFontProvider(false, false, true));\n}\n\n// convert the html file to pdf file.\nHtmlConverter.convertToPdf(new File(htmlFilePath), new File(pdfFilePath), properties);\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31374/" ]
235,855
<p>I'm trying to get a background image of a HTML element (body, div, etc.) to stretch its entire width and height.</p> <p>Not having much luck. Is it even possible or do I have to do it some other way besides it being a background image?</p> <p>My current css is:</p> <pre><code>body { background-position: left top; background-image: url(_images/home.jpg); background-repeat: no-repeat; } </code></pre> <p>Thanks in advance.</p> <p>Edit: I'm not keen on maintaining the CSS in Gabriel's suggestion so I'm changing the layout of the page instead. But that seems like the best answer so I'm marking it as such.</p>
[ { "answer_id": 241082, "author": "Traingamer", "author_id": 27609, "author_profile": "https://Stackoverflow.com/users/27609", "pm_score": 3, "selected": false, "text": "{ \nbackground-image: url(_images/home.jpg);\nbackground-repeat:no-repeat;\nbackground-position:center; \n}\n" }, { "answer_id": 1103672, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": false, "text": "background-size" }, { "answer_id": 5331272, "author": "Nathan", "author_id": 663232, "author_profile": "https://Stackoverflow.com/users/663232", "pm_score": 9, "selected": true, "text": "<style>\n { margin: 0; padding: 0; }\n\n html { \n background: url('images/yourimage.jpg') no-repeat center center fixed; \n -webkit-background-size: cover;\n -moz-background-size: cover;\n -o-background-size: cover;\n background-size: cover;\n }\n</style>\n" }, { "answer_id": 16417072, "author": "Tamal Samui", "author_id": 1331593, "author_profile": "https://Stackoverflow.com/users/1331593", "pm_score": 3, "selected": false, "text": "<div data-role=\"page\" style=\"background:url('backgrnd.png'); background-repeat: no-repeat; background-size: 100% 100%;\" >\n" }, { "answer_id": 22166903, "author": "Behnam", "author_id": 3243488, "author_profile": "https://Stackoverflow.com/users/3243488", "pm_score": 2, "selected": false, "text": "background: url(images/bg.jpg) no-repeat center center fixed; \n-webkit-background-size: cover;\n-moz-background-size: cover;\n-o-background-size: cover;\nbackground-size: cover;\n" }, { "answer_id": 30811127, "author": "live-love", "author_id": 436341, "author_profile": "https://Stackoverflow.com/users/436341", "pm_score": 2, "selected": false, "text": "html, body {\n margin: 0;\n padding: 0;\n min-height: 100%;\n}\n\nbody {\n background-image: url('myimage.jpg');\n background-position-x: center;\n background-position-y: bottom;\n background-repeat: no-repeat;\n background-attachment: scroll;\n -webkit-background-size: cover;\n -moz-background-size: cover;\n -o-background-size: cover;\n background-size: cover;\n}\n\n@media screen and (orientation:portrait) {\n body {\n background-position-y: top;\n -webkit-background-size: contain;\n -moz-background-size: contain;\n -o-background-size: contain;\n background-size: contain;\n }\n}\n" }, { "answer_id": 31320603, "author": "Badar", "author_id": 576750, "author_profile": "https://Stackoverflow.com/users/576750", "pm_score": 2, "selected": false, "text": "body {\n background-image: url('../images/bg.jpg');\n background-repeat: no-repeat;\n background-size: 100%;\n}\n" }, { "answer_id": 41288038, "author": "leocborges", "author_id": 1358674, "author_profile": "https://Stackoverflow.com/users/1358674", "pm_score": 3, "selected": false, "text": "body {\n background-image: url('../images/image.jpg');\n background-repeat: no-repeat;\n background-size: cover;\n}\n" }, { "answer_id": 60347436, "author": "Ebele Nwaelene", "author_id": 12941444, "author_profile": "https://Stackoverflow.com/users/12941444", "pm_score": 0, "selected": false, "text": "background-size: cover;\n background-repeat: no-repeat;\n background-position: center;\n padding: 0 3em 0 3em; \nmargin: -1.5em -0.5em -0.5em -1em; \n width: absolute;\n max-width: 100%; \n" }, { "answer_id": 61490906, "author": "Salah Ayman", "author_id": 8916785, "author_profile": "https://Stackoverflow.com/users/8916785", "pm_score": 0, "selected": false, "text": ".bg {\n background-image: url('_images/home.jpg');//Put your appropriate image URL here\n background-size: 100% 100%; //You need to put 100% twice here to stretch width and height\n}\n" }, { "answer_id": 62069614, "author": "msk_sureshkumar", "author_id": 970425, "author_profile": "https://Stackoverflow.com/users/970425", "pm_score": 1, "selected": false, "text": ".page-bg {\n background: url(\"res://background\");\n background-position: center center;\n background-repeat: no-repeat;\n background-size: 100% 100%;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ]
235,868
<p>Given this algorithm, I would like to know if there exists an iterative version. Also, I want to know if the iterative version can be faster.</p> <p>This some kind of pseudo-python...</p> <p>the algorithm returns a reference to root of the tree</p> <pre><code>make_tree(array a) if len(a) == 0 return None; node = pick a random point from the array calculate distances of the point against the others calculate median of such distances node.left = make_tree(subset of the array, such that the distance of points is lower to the median of distances) node.right = make_tree(subset, such the distance is greater or equal to the median) return node </code></pre>
[ { "answer_id": 235939, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": true, "text": "# naïve recursion\ndef fac(n):\n if n <= 1:\n return 1\n else:\n return n * fac(n - 1)\n\n# tail-recursive with accumulator\ndef fac(n):\n def fac_helper(m, k):\n if m <= 1:\n return k\n else:\n return fac_helper(m - 1, m * k)\n return fac_helper(n, 1)\n\n# iterative with accumulator\ndef fac(n):\n k = 1\n while n > 1:\n n, k = n - 1, n * k\n return k\n" }, { "answer_id": 236187, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "#light \nopen System\n\nlet printResults = false\nlet MAX = 20000\nlet shuffleIt = true\n\n// handy helper function\nlet rng = new Random(0)\nlet shuffle (arr : array<'a>) = // '\n let n = arr.Length\n for x in 1..n do\n let i = n-x\n let j = rng.Next(i+1)\n let tmp = arr.[i]\n arr.[i] <- arr.[j]\n arr.[j] <- tmp\n\n// Same random array\nlet sampleArray = Array.init MAX (fun x -> x) \nif shuffleIt then\n shuffle sampleArray\n\nif printResults then\n printfn \"Sample array is %A\" sampleArray\n\n// Tree type\ntype Tree =\n | Node of int * Tree * Tree\n | Leaf\n\n// MakeTree1 is recursive\nlet rec MakeTree1 (arr : array<int>) lo hi = // [lo,hi)\n if lo = hi then\n Leaf\n else\n let pivot = arr.[lo]\n // partition\n let mutable storeIndex = lo + 1\n for i in lo + 1 .. hi - 1 do\n if arr.[i] < pivot then\n let tmp = arr.[i]\n arr.[i] <- arr.[storeIndex]\n arr.[storeIndex] <- tmp \n storeIndex <- storeIndex + 1\n Node(pivot, MakeTree1 arr (lo+1) storeIndex, MakeTree1 arr storeIndex hi)\n\n// MakeTree2 has all tail calls (uses continuations rather than a stack, see\n// http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!171.entry \n// for more explanation)\nlet MakeTree2 (arr : array<int>) lo hi = // [lo,hi)\n let rec MakeTree2Helper (arr : array<int>) lo hi k =\n if lo = hi then\n k Leaf\n else\n let pivot = arr.[lo]\n // partition\n let storeIndex = ref(lo + 1)\n for i in lo + 1 .. hi - 1 do\n if arr.[i] < pivot then\n let tmp = arr.[i]\n arr.[i] <- arr.[!storeIndex]\n arr.[!storeIndex] <- tmp \n storeIndex := !storeIndex + 1\n MakeTree2Helper arr (lo+1) !storeIndex (fun lacc ->\n MakeTree2Helper arr !storeIndex hi (fun racc ->\n k (Node(pivot,lacc,racc))))\n MakeTree2Helper arr lo hi (fun x -> x)\n\n// MakeTree2 never stack overflows\nprintfn \"calling MakeTree2...\"\nlet tree2 = MakeTree2 sampleArray 0 MAX\nif printResults then\n printfn \"MakeTree2 yields\"\n printfn \"%A\" tree2\n\n// MakeTree1 might stack overflow\nprintfn \"calling MakeTree1...\"\nlet tree1 = MakeTree1 sampleArray 0 MAX\nif printResults then\n printfn \"MakeTree1 yields\"\n printfn \"%A\" tree1\n\nprintfn \"Trees are equal: %A\" (tree1 = tree2)\n" }, { "answer_id": 34528629, "author": "Walid Da.", "author_id": 1251220, "author_profile": "https://Stackoverflow.com/users/1251220", "pm_score": 0, "selected": false, "text": "public static Tree builtBSTFromSortedArray(int[] inputArray){\n\n Stack toBeDone=new Stack(\"sub trees to be created under these nodes\");\n\n //initialize start and end \n int start=0;\n int end=inputArray.length-1;\n\n //keep memoy of the position (in the array) of the previously created node\n int previous_end=end;\n int previous_start=start;\n\n //Create the result tree \n Node root=new Node(inputArray[(start+end)/2]);\n Tree result=new Tree(root);\n while(root!=null){\n System.out.println(\"Current root=\"+root.data);\n\n //calculate last middle (last node position using the last start and last end)\n int last_mid=(previous_start+previous_end)/2;\n\n //*********** add left node to the previously created node ***********\n //calculate new start and new end positions\n //end is the previous index position minus 1\n end=last_mid-1; \n //start will not change for left nodes generation\n start=previous_start; \n //check if the index exists in the array and add the left node\n if (end>=start){\n root.left=new Node(inputArray[((start+end)/2)]);\n System.out.println(\"\\tCurrent root.left=\"+root.left.data);\n }\n else\n root.left=null;\n //save previous_end value (to be used in right node creation)\n int previous_end_bck=previous_end;\n //update previous end\n previous_end=end;\n\n //*********** add right node to the previously created node ***********\n //get the initial value (inside the current iteration) of previous end\n end=previous_end_bck;\n //start is the previous index position plus one\n start=last_mid+1;\n //check if the index exists in the array and add the right node\n if (start<=end){\n root.right=new Node(inputArray[((start+end)/2)]);\n System.out.println(\"\\tCurrent root.right=\"+root.right.data);\n //save the created node and its index position (start & end) in the array to toBeDone stack\n toBeDone.push(root.right);\n toBeDone.push(new Node(start));\n toBeDone.push(new Node(end)); \n }\n\n //*********** update the value of root ***********\n if (root.left!=null){\n root=root.left; \n }\n else{\n if (toBeDone.top!=null) previous_end=toBeDone.pop().data;\n if (toBeDone.top!=null) previous_start=toBeDone.pop().data;\n root=toBeDone.pop(); \n }\n }\n return result; \n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
235,875
<p>I get the following message in a VC6 project compile:</p> <blockquote> <p>OTE: WINVER has been defined as 0x0500 or greater which enables Windows NT 5.0 and Windows 98 features. When these headers were released, Windows NT 5.0 beta 1 and Windows 98 beta 2.1 were the current versions. For this release when WINVER is defined as 0x0500 or greater, you can only build beta or test applications. To build a retail application, set WINVER to 0x0400 or visit <a href="http://www.microsoft.com/msdn/sdk" rel="nofollow noreferrer">http://www.microsoft.com/msdn/sdk</a> to see if retail Windows NT 5.0 or Windows 98 headers are available. See the SDK release notes for more information.</p> </blockquote> <p>Any idea what is going on?</p> <p>It builds and links fine. </p> <p>I have VC6, VS2005 and 2008 on my XP machine. </p> <p>Perhaps my Platform SDK is not up to date?</p>
[ { "answer_id": 236209, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 2, "selected": true, "text": "WINVER" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10755/" ]
235,880
<p>How can I convert an <code>Int64</code> to an <code>Int32</code> type in F# without using the <code>Microsoft.FSharp.Compatibility.Int32.of_int64</code>?</p> <p>I'm doing this because interactive doesn't seem to work when I try:</p> <pre><code>open Microsoft.FSharp.Compatibility </code></pre> <p>With <code>FSharp.PowerPack</code> added as a reference it says: </p> <blockquote> <p>error FS0039: The namespace 'Compatibility' is not defined.</p> </blockquote> <p><strong>Edit:</strong> Does anyone have an answer to the question? The suggestions about the int types are useful and informative, but I'm having the same issue opening the powerpack namespace in F# interactive.</p>
[ { "answer_id": 235893, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 5, "selected": false, "text": "let num = 1000\nlet num64 = int64(num)\n" }, { "answer_id": 235913, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "> let bignum = 4294967297L;;\nval bignum : int64\n\n> let myint = int32(bignum);;\nval myint : int32\n\n> myint;;\nval it : int32 = 1\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,927
<p>I created a simple .NET windows application in Visual Studio 2005 and on just entering the main form load event my threads window is as in the following image:</p> <p><a href="http://img519.imageshack.us/my.php?image=threadshh4.jpg" rel="nofollow noreferrer">http://img519.imageshack.us/my.php?image=threadshh4.jpg</a></p> <p>My questions are</p> <p>1)Why are there so many threads in the first place when I haven't started any(apart from my application's 'Main Thread')</p> <p>2)What does this thread named '.Net SystemEvents' do?</p> <p>3)Why are the entries under the column 'Location' for all threads except the Main Thread empty?</p> <p><strong>EDIT:</strong><br> 4) Is it possible to make these thread not start? or go away after some time?<br> 5) What are they meant to do? what is their purpose?</p>
[ { "answer_id": 799074, "author": "GregC", "author_id": 90475, "author_profile": "https://Stackoverflow.com/users/90475", "pm_score": 0, "selected": false, "text": "public static class ThreadingHelper_NativeMethods\n{\n [DllImport(\"user32.dll\")]\n public static extern bool IsGUIThread(bool bConvert);\n}\n\n\n // This code forces initialization of .NET BroadcastEventWindow to the UI thread.\n // http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/fb267827-1765-4bd9-ae2f-0abbd5a2ae22\n if (ThreadingHelper_NativeMethods.IsGUIThread(false))\n {\n Microsoft.Win32.SystemEvents.InvokeOnEventsThread(new MethodInvoker(delegate()\n {\n int x = 0;\n }));\n }\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25125/" ]
235,940
<p>Making a small app, and I want a function to execute 50% of the time. So if I were to dbl click the exe half the time the function would execute, and the other half it wouldn't. I can't seem to find anyway to easily do this, the one solution I tried seemed to determine the chance on compile rather than on run. Thanks in advance!</p>
[ { "answer_id": 235948, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 2, "selected": false, "text": "Private Sub Main()\n If Rnd > 0.5 Then\n ExecuteFunction ()\n End If\nEnd Sub\n" }, { "answer_id": 236196, "author": "Alex Warren", "author_id": 31280, "author_profile": "https://Stackoverflow.com/users/31280", "pm_score": 2, "selected": false, "text": "Randomize Timer" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,950
<p>I am writing an application where I will be accessing the database from django and from a stand alone application. Both need to do session verification and the session should be the same for both of them. Django has a built in authentication/session verification, which is what I am using, now I need to figure out how to reuse the same session for my stand alone application.</p> <p>My question is how can I look up a session_key for a particular user?</p> <p>From what it looks there is nothing that ties together auth_user and django_session</p>
[ { "answer_id": 237206, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 6, "selected": true, "text": "django_session" }, { "answer_id": 4892370, "author": "Joe", "author_id": 602342, "author_profile": "https://Stackoverflow.com/users/602342", "pm_score": 3, "selected": false, "text": "class Session(models.Model):\n\n ...\n\n user_id = models.IntegerField(_('user_id'), null=True)\n\n ...\n\n def save(self, *args, **kwargs):\n user_id = self.get_decoded().get('_auth_user_id')\n if ( user_id != None ):\n self.user_id = user_id\n\n # Call the \"real\" save() method.\n super(Session, self).save(*args, **kwargs)\n" }, { "answer_id": 6238346, "author": "michael", "author_id": 72514, "author_profile": "https://Stackoverflow.com/users/72514", "pm_score": 5, "selected": false, "text": "from django.contrib.sessions.models import Session\nfrom django.contrib.auth.models import User\n\nsession_key = '8cae76c505f15432b48c8292a7dd0e54'\n\nsession = Session.objects.get(session_key=session_key)\nuid = session.get_decoded().get('_auth_user_id')\nuser = User.objects.get(pk=uid)\n\nprint user.username, user.get_full_name(), user.email\n" }, { "answer_id": 11540241, "author": "hwjp", "author_id": 366221, "author_profile": "https://Stackoverflow.com/users/366221", "pm_score": 3, "selected": false, "text": "last_login" }, { "answer_id": 26097566, "author": "Gavin Ballard", "author_id": 641127, "author_profile": "https://Stackoverflow.com/users/641127", "pm_score": 6, "selected": false, "text": "UserSession" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26592/" ]
235,959
<p>I have a (derived) Menu control, that displays a rather large list of items from a custom data source. I need to disable ViewState on the menu to avoid the very annoying "Can't select a disabled or unselectable menu item" when some other control causes the current selection to change on a postback.</p> <p>Unfortunately, when ViewState is disabled for the Menu, the postbacks generated <em>by</em> the menu aren't raising any events. If I enable ViewState, the OnMenuItemClick event is raised. If I disable ViewState, OnMenuItemClick is not raised. I'm perplexed.</p> <p>I need to leave ViewState off for the menu, so how can I handle postbacks from the actual menu?</p> <p>At this point I'm leaning towards using the Menu's Load event, parsing the __EVENTTARGET to see if it's the Menu, and going from there. This would technically process the postback event before it would normally but that's ok, I guess.</p> <p>Any better ideas?</p>
[ { "answer_id": 237490, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 1, "selected": true, "text": "string str = HttpUtility.HtmlDecode(eventArgument);\n...\nMenuItem item = this.Items.FindItem(str.Split(new char[] { '\\\\' }), 0);\nif (item != null)\n this.OnMenuItemClick(new MenuEventArgs(item));\n" }, { "answer_id": 24745490, "author": "Nicolò Beltrame", "author_id": 2713895, "author_profile": "https://Stackoverflow.com/users/2713895", "pm_score": 0, "selected": false, "text": "if (IsPostBack) {\n Menu.DataBind();\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31385/" ]
235,967
<p>I am working on a web page that is using jQuery. I have an Ajax call that gets data from the server and updates a div. Inside that data there is a jQuery function, but the function is not being called after the data is loaded into the page. I have the proper js files included in the page already.</p> <p>This is what is returned from the Ajax call and placed into a div:</p> <pre><code>&lt;script type="text/javascript"&gt; $(function() { $('input').myFunction('param'); }); &lt;/script&gt; &lt;p&gt; other html &lt;/p&gt; </code></pre> <p>How do I get the returned javascript to run after the html is inserted into the page?</p> <p>(I am using Rails with the jRails plugin )</p>
[ { "answer_id": 235990, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": true, "text": "$.ajax({\n type: \"GET\",\n url: \"yourPage.htm\",\n dataType: \"html\"\n});\n" }, { "answer_id": 573484, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\">\n $(function() {\n $('input').myFunction('param'); \n }); \n</script>\n<p> other html </p>\n" }, { "answer_id": 847480, "author": "ajitatif", "author_id": 104696, "author_profile": "https://Stackoverflow.com/users/104696", "pm_score": -1, "selected": false, "text": " $(document).ready(function()\n {\n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler); \n }\n );\n function endRequestHandler(sender, args)\n {\n // whatever\n }\n" }, { "answer_id": 1833027, "author": "dc2009", "author_id": 167239, "author_profile": "https://Stackoverflow.com/users/167239", "pm_score": -1, "selected": false, "text": "endRequestHandler(sender, args)" }, { "answer_id": 7677801, "author": "JimFing", "author_id": 700956, "author_profile": "https://Stackoverflow.com/users/700956", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\">\n...\n</script>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
235,972
<p>I have a windows application running at the backend. I have functions in this applications mapped to hot keys. Like if I put a message box into this function and give hot key as <kbd>Alt</kbd>+<kbd>Ctrl</kbd>+<kbd>D</kbd>. then on pressing <kbd>Alt</kbd>, <kbd>Ctrl</kbd> and <kbd>D</kbd> together the message box comes up. My application is working fine till this point. </p> <p>Now I want to write a code inside this function so that when I am using another application like notepad, I select a particular line of text and press the hot key <kbd>Alt</kbd> + <kbd>Ctrl</kbd> + <kbd>D</kbd> it is supposed to copy the selected text append it with "_copied" and paste it back to notepad. </p> <p>Anyone who has tried a similar application please help me with your valuable inputs.</p>
[ { "answer_id": 273163, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 5, "selected": true, "text": "BOOL RegisterHotKey(\n HWND hWnd, // window to receive hot-key notification\n int id, // identifier of hot key\n UINT fsModifiers, // key-modifier flags\n UINT vk // virtual-key code\n);\n" }, { "answer_id": 59952641, "author": "DurkoMatko", "author_id": 3356517, "author_profile": "https://Stackoverflow.com/users/3356517", "pm_score": 2, "selected": false, "text": "user32.dll" }, { "answer_id": 74170233, "author": "obviliontsk", "author_id": 18531761, "author_profile": "https://Stackoverflow.com/users/18531761", "pm_score": 0, "selected": false, "text": "[DllImport(\"USER32.DLL\", CharSet = CharSet.Unicode)]\npublic static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n[DllImport(\"USER32.DLL\")]\npublic static extern bool SetForegroundWindow(IntPtr hWnd);\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
235,982
<p>The most favorite feature of StackOverflow for me is that it can automatically detect code in post and set appropriate color to the code.</p> <p>I'm wondering how the color is set. When I do a <kbd>Ctrl</kbd>+<kbd>F5</kbd> on a page, the code seems first be black text, then change to be colorful. Is it done by jQuery?</p>
[ { "answer_id": 236062, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 5, "selected": true, "text": "AFunction(\"a string\")\n1 + 4 # <- numbers\n # /\\ a comment\n // also a comment..\n" }, { "answer_id": 236450, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "For id = 1 To 10 Do\n CallSomething() // It likes CamelCase identifiers...\nEnd\n\nfor id = 1 to 10 do # Also highlight some common keywords...\n if id % 2 then call_something(); x++; end\nend\n\n'str' \"str\" 12 + 15.6 * -7e+9 /* Some common constant forms */\n=/regex/ ~/regex/ +/RE/ !/regexpr/ but not /[^regex]/ (no operator before it)\n\n(* Some comment conventions are overlooked... *)\n-- Lua's (and some other languages')\n; So are these comments...\n' And these (Basic)\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
236,001
<p>My understanding is that in unix, when memory is freed, the memory doesn't get returned back to the operating system, it stays in the process to be used again for the next call to malloc.</p> <p>On windows, I understand that the memory actually gets returned to the operating system.</p> <p>Is there any big difference between these two ways of doing things or are they just two different ways of doing the same thing? And if there are any pros/cons to these two methods, what are they?</p> <p><strong>EDIT:</strong> Thanks for the clarification. I had always thought this was an OS thing (since processes never seem to decrease in size in UNIX-like systems, but do in windows).</p>
[ { "answer_id": 236016, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "brk()" }, { "answer_id": 236112, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "int main(void)\n{\n\n void *p = malloc(AS_MUCH_MEMORY_AS_I_WILL_EVER_NEED);\n\n if (p != 0)\n {\n free(p);\n /* malloc should always work for rest of program */\n }\n}\n" }, { "answer_id": 236337, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 5, "selected": true, "text": "brk" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
236,031
<p>How can I implement a <code>diff</code> function, such as Stack Overflow's question revision history?</p>
[ { "answer_id": 236034, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "diffString( String oldFile, String newFile )\n" }, { "answer_id": 236041, "author": "Vhaerun", "author_id": 11234, "author_profile": "https://Stackoverflow.com/users/11234", "pm_score": 0, "selected": false, "text": "\nvoid diff(String first,String second) {\n int biggest = (first.length() > second.length()) ? first.length() : second.length();\n for(int i = 0;i < biggest;i++) {\n //compare each char from the longest string with each char from the shorter\n // do something with them if they're not equal\n }\n}\n" }, { "answer_id": 236067, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 0, "selected": false, "text": "git diff --color-words" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20191/" ]
236,035
<p>I've been reading many a tutorial/article on unmanaged DLLs in C++. For the life of me, however, I cannot seem to grasp the concept. I'm easily confused by the seeming disagreement about whether it needs a header file, how to export it, whether I need a .lib file and what have you.</p> <p>So, let's assume I have just a function like so:</p> <pre><code>public int calculateSquare(int num) { return num*num; } </code></pre> <p>Ignoring the actual code, what do I require to make this simple function, by itself, into a DLL which I can then call? Do I just add __dllexport or whatever it is to the first line or do I require a header? I am perplexed by all of this.</p>
[ { "answer_id": 236052, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 5, "selected": true, "text": "#ifdef SOME_CONDITION\n#define MYIMPORTEXPORT __declspec( dllexport )\n#else\n#define MYIMPORTEXPORT __declspec( dllimport )\n#endif\n" }, { "answer_id": 236053, "author": "Roman Plášil", "author_id": 16590, "author_profile": "https://Stackoverflow.com/users/16590", "pm_score": 0, "selected": false, "text": "__declspec( dllexport )" }, { "answer_id": 236167, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 1, "selected": false, "text": "__stdcall" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31389/" ]
236,038
<p>I am facing this peculiar problem. My webapp, works fine on my localhost. Its a JSP/Struts-Tomcat-MySQL app. However, when I host it on hostjava.net (shared tomcat), it is unable to connect to the database.</p> <p>After some debugging, I have identified the problem, to be with JNDI lookup for datasource. If you want, you can take a look at the log at <a href="http://rohitesh.hostjava.net/MapsDummyLog.htm" rel="nofollow noreferrer">http://rohitesh.hostjava.net/MapsDummyLog.htm</a></p> <p>Some details on the context information location : /META-INF/context.xml contains :</p> <pre><code>&lt;Context path="" docBase="" debug="5" reloadable="true" crossContext="true" override="true"&gt; &lt;Resource name="jdbc/ConnectionPooling" auth="Container" type="javax.sql.DataSource" maxActive="10" maxIdle="5" username="[username]" password="[password]" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/[db name]?autoReconnect=true" /&gt; &lt;/Context&gt; </code></pre> <p>Can anyone help me find out, where am going wrong, please?</p> <p>Cheers, Rohitesh.</p>
[ { "answer_id": 236482, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 2, "selected": false, "text": "url=\"jdbc:mysql://localhost/[db name]?autoReconnect=true\"\n" }, { "answer_id": 237437, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 2, "selected": false, "text": "<Context path=\"\" \n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8056/" ]
236,047
<p>I need a code documentation tool similar to javadoc or c# xml doc for delphi code. What is the best tool? I prefer a technology, which is in the future compatible to the Microsoft sandcastle project.</p>
[ { "answer_id": 34854271, "author": "Daniel Marschall", "author_id": 488539, "author_profile": "https://Stackoverflow.com/users/488539", "pm_score": 1, "selected": false, "text": "/// <summary>\n/// Summary of the function / class\n/// </summary>\n/// <param name=\"param1\">Description of the parameter param1</param>\n/// <param name=\"param2\">Description of the parameter param2</param>\n/// <param name=\"param3\">Description of the parameter param3</param>\n/// <returns>Description of the return value</returns>\nfunction test(param1, param2, param3: string): string;\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205962/" ]
236,070
<p>How can I check the version of my script against an online file to see if it's the latest version?</p> <p><em>For clarification, I'm talking about a script I wrote, not the version of PHP. I'd like to incorporate a way for the end user to tell when I've updated the script.</em></p>
[ { "answer_id": 236100, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "// Substitue path to script with the version information in place of __FILE__ if necessary\n$script = file_get_contents(__FILE__);\n$version = SOME_SENSIBLE_DEFAULT_IN_CASE_OF_FAILURE;\nif(preg_match('/<!-- Script version (\\d*(\\.\\d+)*) -->/', $script, $version_match)) {\n $version = $version_match[1];\n}\n" }, { "answer_id": 236115, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 5, "selected": true, "text": "version.txt" }, { "answer_id": 4807515, "author": "Nick Winstanley", "author_id": 590983, "author_profile": "https://Stackoverflow.com/users/590983", "pm_score": 2, "selected": false, "text": "define('REMOTE_VERSION', 'http://your.public.server/version.txt');\ndefine('VERSION', '1.0.1');\n$script = file_get_contents(REMOTE_VERSION);\n$version = VERSION;\nif($version == $script) {\n echo \"<div class=success> \n<p>You have the latest version!</p> \n</div>\";\n} else {\n echo \"<div class=error> \n<p>There is a update available!</p> \n</div>\";\n}\n" }, { "answer_id": 69425740, "author": "Mukesh Yadav", "author_id": 11812099, "author_profile": "https://Stackoverflow.com/users/11812099", "pm_score": -1, "selected": false, "text": "if($version == $script) \n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
236,073
<p>Why do some sites (or advertisers that give clients javascript code) employ a technique of splitting the <code>&lt;script&gt;</code> and/or <code>&lt;/script&gt;</code> tags up within <code>document.write()</code> calls?</p> <p>I noticed that Amazon does this as well, for example:</p> <pre><code>&lt;script type='text/javascript'&gt; if (typeof window['jQuery'] == 'undefined') document.write('&lt;scr'+'ipt type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"&gt;&lt;/sc'+'ript&gt;'); &lt;/script&gt; </code></pre>
[ { "answer_id": 236083, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "var newScript = document.createElement(\"script\");\n...\n" }, { "answer_id": 236106, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 10, "selected": true, "text": "</script>" }, { "answer_id": 18832826, "author": "Stoffe", "author_id": 134276, "author_profile": "https://Stackoverflow.com/users/134276", "pm_score": 5, "selected": false, "text": "<script>\n var script = document.createElement('script');\n script.src = '/path/to/script.js';\n document.write(script.outerHTML);\n</script>\n" }, { "answer_id": 20376002, "author": "Jongosi", "author_id": 1330505, "author_profile": "https://Stackoverflow.com/users/1330505", "pm_score": 3, "selected": false, "text": "if (typeof(jQuery) == 'undefined') {\n (function() {\n var sct = document.createElement('script');\n sct.src = ('https:' == document.location.protocol ? 'https' : 'http') +\n '://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';\n sct.type = 'text/javascript';\n sct.async = 'true';\n var domel = document.getElementsByTagName('script')[0];\n domel.parentNode.insertBefore(sct, domel);\n })();\n}\n" }, { "answer_id": 27123725, "author": "Mathieu Rodic", "author_id": 734335, "author_profile": "https://Stackoverflow.com/users/734335", "pm_score": 4, "selected": false, "text": "</script>" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2929/" ]
236,086
<p>I've recently been trying to create units tests for some legacy code.</p> <p>I've been taking the approach of using the linker to show me which functions cause link errors, greping the source to find the definition and creating a stub from that. </p> <p>Is there an easier way? Is there some kind of C++ parser that can give me class definitions, in some easy to use form, from which I can generate stubs?</p>
[ { "answer_id": 12546962, "author": "linuxbuild", "author_id": 241776, "author_profile": "https://Stackoverflow.com/users/241776", "pm_score": 2, "selected": false, "text": "abi-compliance-checker -lib NAME -dump VER.xml -headers-only -xml -stdout > api.xml\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1575281/" ]
236,097
<p>In XEmacs this is done by the calling the function char-to-ucs on a character. GNU Emacs does not seem to have this function. In GNU Emacs, characters seem to be ordinary integers. Running C-x = on a latin character reveals that the Emacs codepoint is different from the Unicode codepoint for the corresponding character. How do I find the Unicode codepoint of the character at point in GNU Emacs?</p>
[ { "answer_id": 236160, "author": "Dwight Holman", "author_id": 2667, "author_profile": "https://Stackoverflow.com/users/2667", "pm_score": 6, "selected": false, "text": " character: ¢ (2210, #o4242, #x8a2, U+00A2)\n charset: latin-iso8859-1\n (Right-Hand Part of Latin Alphabet 1 (ISO/IEC 8859-1): ISO-IR-100.)\n code point: #x22\n syntax: w which means: word\n category: l:Latin\nbuffer code: #x81 #xA2\n file code: #xC2 #xA2 (encoded by coding system utf-8)\n display: by this font (glyph code)\n -apple-monaco-medium-r-normal--12-120-72-72-m-120-mac-roman (#xA2)\n" }, { "answer_id": 236176, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "(or (get-char-property (point) 'untranslated-utf-8)\n (encode-char (char-after) 'ucs))\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,125
<p>Suppose I have this Windows wchar_t string:</p> <pre><code>L"\x4f60\x597d" </code></pre> <p>and</p> <pre><code>L"\x00e4\x00a0\x597d" </code></pre> <p>and would like to convert it (not necessarily programmatically; it will be a one-time thing) to GCC/Linux wchar_t format, which is UTF-32 AFAIK. How do I do it? (a general explanation would be nice, but example based on this concrete case would be helpful as well)</p> <p><em>Please don't direct me to character conversion sites. I would like to convert from L"\x(something)" form and not "end character" form.</em></p>
[ { "answer_id": 236574, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 2, "selected": false, "text": "wchar_t" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
236,129
<p>How do I iterate over the words of a string composed of words separated by whitespace?</p> <p>Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; using namespace std; int main() { string s = &quot;Somewhere down the road&quot;; istringstream iss(s); do { string subs; iss &gt;&gt; subs; cout &lt;&lt; &quot;Substring: &quot; &lt;&lt; subs &lt;&lt; endl; } while (iss); } </code></pre>
[ { "answer_id": 236137, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "strtok()" }, { "answer_id": 236146, "author": "gnomed", "author_id": 27739, "author_profile": "https://Stackoverflow.com/users/27739", "pm_score": 7, "selected": false, "text": "string line = \"a line of text to iterate through\";\nstring word;\n\nistringstream iss(line, istringstream::in);\n\nwhile( iss >> word ) \n{\n // Do something on `word` here...\n}\n" }, { "answer_id": 236153, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 5, "selected": false, "text": "std::stringstream" }, { "answer_id": 236158, "author": "Peter C.", "author_id": 31389, "author_profile": "https://Stackoverflow.com/users/31389", "pm_score": -1, "selected": false, "text": "string stringlist[10];\nint count = 0;\n\nfor (int i = 0; i < sequence.length(); i++)\n{\n if (sequence[i] == ' ')\n {\n stringlist[count] = sequence.substr(0, i);\n sequence.erase(0, i+1);\n i = 0;\n count++;\n }\n else if (i == sequence.length()-1) // Last word\n {\n stringlist[count] = sequence.substr(0, i+1);\n }\n}\n" }, { "answer_id": 236180, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 6, "selected": false, "text": "#include <ostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <iterator>\nusing namespace std;\n\nvector<string> split(const string& s, const string& delim, const bool keep_empty = true) {\n vector<string> result;\n if (delim.empty()) {\n result.push_back(s);\n return result;\n }\n string::const_iterator substart = s.begin(), subend;\n while (true) {\n subend = search(substart, s.end(), delim.begin(), delim.end());\n string temp(substart, subend);\n if (keep_empty || !temp.empty()) {\n result.push_back(temp);\n }\n if (subend == s.end()) {\n break;\n }\n substart = subend + delim.size();\n }\n return result;\n}\n\nint main() {\n const vector<string> words = split(\"So close no matter how far\", \" \");\n copy(words.begin(), words.end(), ostream_iterator<string>(cout, \"\\n\"));\n}\n" }, { "answer_id": 236234, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 6, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <boost/tokenizer.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nint main(int argc, char** argv)\n{\n string text = \"token test\\tstring\";\n\n char_separator<char> sep(\" \\t\");\n tokenizer<char_separator<char>> tokens(text, sep);\n for (const string& t : tokens)\n {\n cout << t << \".\" << endl;\n }\n}\n" }, { "answer_id": 236803, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 11, "selected": false, "text": "#include <string>\n#include <sstream>\n#include <vector>\n#include <iterator>\n\ntemplate <typename Out>\nvoid split(const std::string &s, char delim, Out result) {\n std::istringstream iss(s);\n std::string item;\n while (std::getline(iss, item, delim)) {\n *result++ = item;\n }\n}\n\nstd::vector<std::string> split(const std::string &s, char delim) {\n std::vector<std::string> elems;\n split(s, delim, std::back_inserter(elems));\n return elems;\n}\n" }, { "answer_id": 236976, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 10, "selected": false, "text": "#include <boost/algorithm/string.hpp>\nstd::vector<std::string> strs;\nboost::split(strs, \"string to split\", boost::is_any_of(\"\\t \"));\n" }, { "answer_id": 237280, "author": "Zunino", "author_id": 30767, "author_profile": "https://Stackoverflow.com/users/30767", "pm_score": 12, "selected": true, "text": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n\nint main() {\n using namespace std;\n string sentence = \"And I feel fine...\";\n istringstream iss(sentence);\n copy(istream_iterator<string>(iss),\n istream_iterator<string>(),\n ostream_iterator<string>(cout, \"\\n\"));\n}\n" }, { "answer_id": 1493195, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 8, "selected": false, "text": "template < class ContainerT >\nvoid tokenize(const std::string& str, ContainerT& tokens,\n const std::string& delimiters = \" \", bool trimEmpty = false)\n{\n std::string::size_type pos, lastPos = 0, length = str.length();\n\n using value_type = typename ContainerT::value_type;\n using size_type = typename ContainerT::size_type;\n\n while(lastPos < length + 1)\n {\n pos = str.find_first_of(delimiters, lastPos);\n if(pos == std::string::npos)\n {\n pos = length;\n }\n\n if(pos != lastPos || !trimEmpty)\n tokens.push_back(value_type(str.data()+lastPos,\n (size_type)pos-lastPos ));\n\n lastPos = pos + 1;\n }\n}\n" }, { "answer_id": 2025273, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "void split_string(string text,vector<string>& words)\n{\n int i=0;\n char ch;\n string word;\n\n while(ch=text[i++])\n {\n if (isspace(ch))\n {\n if (!word.empty())\n {\n words.push_back(word);\n }\n word = \"\";\n }\n else\n {\n word += ch;\n }\n }\n if (!word.empty())\n {\n words.push_back(word);\n }\n}\n" }, { "answer_id": 2560993, "author": "Robert", "author_id": 255635, "author_profile": "https://Stackoverflow.com/users/255635", "pm_score": 5, "selected": false, "text": "template<typename Operator>\nvoid tokenize(Operator& op, const char* input, const char* delimiters) {\n const char* s = input;\n const char* e = s;\n while (*e != 0) {\n e = s;\n while (*e != 0 && strchr(delimiters, *e) == 0) ++e;\n if (e - s > 0) {\n op(s, e - s);\n }\n s = e + 1;\n }\n}\n" }, { "answer_id": 3037106, "author": "Pratik Deoghare", "author_id": 58737, "author_profile": "https://Stackoverflow.com/users/58737", "pm_score": 5, "selected": false, "text": "strtok" }, { "answer_id": 3616605, "author": "Abe", "author_id": 436795, "author_profile": "https://Stackoverflow.com/users/436795", "pm_score": 3, "selected": false, "text": "void splitString(const String &s, const String &delim, std::vector<String> &result) {\n const int l = delim.length();\n int f = 0;\n int i = s.indexOf(delim,f);\n while (i>=0) {\n String token( i-f > 0 ? s.substring(f,i-f) : \"\");\n result.push_back(token);\n f=i+l;\n i = s.indexOf(delim,f);\n }\n String token = s.substring(f);\n result.push_back(token);\n}\n" }, { "answer_id": 4081331, "author": "lemic", "author_id": 495167, "author_profile": "https://Stackoverflow.com/users/495167", "pm_score": 1, "selected": false, "text": "getline" }, { "answer_id": 4689579, "author": "Goran", "author_id": 575461, "author_profile": "https://Stackoverflow.com/users/575461", "pm_score": 4, "selected": false, "text": "static void Split(std::vector<std::string>& lst, const std::string& input, const std::string& separators, bool remove_empty = true)\n{\n std::ostringstream word;\n for (size_t n = 0; n < input.size(); ++n)\n {\n if (std::string::npos == separators.find(input[n]))\n word << input[n];\n else\n {\n if (!word.str().empty() || !remove_empty)\n lst.push_back(word.str());\n word.str(\"\");\n }\n }\n if (!word.str().empty() || !remove_empty)\n lst.push_back(word.str());\n}\n" }, { "answer_id": 5208977, "author": "kev", "author_id": 348785, "author_profile": "https://Stackoverflow.com/users/348785", "pm_score": 9, "selected": false, "text": "#include <vector>\n#include <string>\n#include <sstream>\n\nint main()\n{\n std::string str(\"Split me by whitespaces\");\n std::string buf; // Have a buffer string\n std::stringstream ss(str); // Insert the string into a stream\n\n std::vector<std::string> tokens; // Create vector to hold our words\n\n while (ss >> buf)\n tokens.push_back(buf);\n\n return 0;\n}\n" }, { "answer_id": 5419348, "author": "zerm", "author_id": 359335, "author_profile": "https://Stackoverflow.com/users/359335", "pm_score": 5, "selected": false, "text": "boost_split_iterator" }, { "answer_id": 6010463, "author": "Kelly Elton", "author_id": 222054, "author_profile": "https://Stackoverflow.com/users/222054", "pm_score": 3, "selected": false, "text": "#pragma once\n#include <vector>\n#include <sstream>\nusing namespace std;\nclass Helpers\n{\n public:\n static vector<string> split(string s, char delim)\n {\n stringstream temp (stringstream::in | stringstream::out);\n vector<string> elems(0);\n if (s.size() == 0 || delim == 0)\n return elems;\n for(char c : s)\n {\n if(c == delim)\n {\n elems.push_back(temp.str());\n temp = stringstream(stringstream::in | stringstream::out);\n }\n else\n temp << c;\n }\n if (temp.str().size() > 0)\n elems.push_back(temp.str());\n return elems;\n }\n\n //Splits string s with a list of delimiters in delims (it's just a list, like if we wanted to\n //split at the following letters, a, b, c we would make delims=\"abc\".\n static vector<string> split(string s, string delims)\n {\n stringstream temp (stringstream::in | stringstream::out);\n vector<string> elems(0);\n bool found;\n if(s.size() == 0 || delims.size() == 0)\n return elems;\n for(char c : s)\n {\n found = false;\n for(char d : delims)\n {\n if (c == d)\n {\n elems.push_back(temp.str());\n temp = stringstream(stringstream::in | stringstream::out);\n found = true;\n break;\n }\n }\n if(!found)\n temp << c;\n }\n if(temp.str().size() > 0)\n elems.push_back(temp.str());\n return elems;\n }\n};\n" }, { "answer_id": 6321203, "author": "Marty B", "author_id": 790360, "author_profile": "https://Stackoverflow.com/users/790360", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <boost/regex.hpp>\n\nint main() {\n std::string line(\"A:::line::to:split\");\n const boost::regex re(\":+\"); // one or more colons\n\n // -1 means find inverse matches aka split\n boost::sregex_token_iterator tokens(line.begin(),line.end(),re,-1);\n boost::sregex_token_iterator end;\n\n for (; tokens != end; ++tokens)\n std::cout << *tokens << std::endl;\n}\n" }, { "answer_id": 6461136, "author": "gibbz", "author_id": 813184, "author_profile": "https://Stackoverflow.com/users/813184", "pm_score": 4, "selected": false, "text": "#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> split(string str, const char delim) {\n vector<string> v;\n string tmp;\n\n for(string::const_iterator i; i = str.begin(); i <= str.end(); ++i) {\n if(*i != delim && i != str.end()) {\n tmp += *i; \n } else {\n v.push_back(tmp);\n tmp = \"\"; \n } \n } \n\n return v;\n}\n" }, { "answer_id": 6859092, "author": "Jairo Abdiel Toribio Cisneros", "author_id": 867443, "author_profile": "https://Stackoverflow.com/users/867443", "pm_score": 2, "selected": false, "text": "#include <string>\n#include <vector>\nvoid split(vector<string> &result, string str, char delim ) {\n string tmp;\n string::iterator i;\n result.clear();\n\n for(i = str.begin(); i <= str.end(); ++i) {\n if((const char)*i != delim && i != str.end()) {\n tmp += *i;\n } else {\n result.push_back(tmp);\n tmp = \"\";\n }\n }\n}\n" }, { "answer_id": 7045104, "author": "lukmac", "author_id": 555951, "author_profile": "https://Stackoverflow.com/users/555951", "pm_score": 4, "selected": false, "text": "string s = \"Name:JAck; Spouse:Susan; ...\";\nstring dummy, name, spouse;\n\nistringstream iss(s);\ngetline(iss, dummy, ':');\ngetline(iss, name, ';');\ngetline(iss, dummy, ':');\ngetline(iss, spouse, ';')\n" }, { "answer_id": 7408245, "author": "Alec Thomas", "author_id": 7980, "author_profile": "https://Stackoverflow.com/users/7980", "pm_score": 7, "selected": false, "text": "std::vector<std::string> split(const std::string &text, char sep) {\n std::vector<std::string> tokens;\n std::size_t start = 0, end = 0;\n while ((end = text.find(sep, start)) != std::string::npos) {\n tokens.push_back(text.substr(start, end - start));\n start = end + 1;\n }\n tokens.push_back(text.substr(start));\n return tokens;\n}\n" }, { "answer_id": 7414250, "author": "Andreas Spindler", "author_id": 887771, "author_profile": "https://Stackoverflow.com/users/887771", "pm_score": 3, "selected": false, "text": "#include <string>\n#include <list>\n#include <locale> // std::isupper\n\ntemplate<class String>\nconst std::list<String> split_camel_case_string(const String &s)\n{\n std::list<String> R;\n String w;\n\n for (String::const_iterator i = s.begin(); i < s.end(); ++i) { {\n if (std::isupper(*i)) {\n if (w.length()) {\n R.push_back(w);\n w.clear();\n }\n }\n w += *i;\n }\n\n if (w.length())\n R.push_back(w);\n return R;\n}\n" }, { "answer_id": 8457004, "author": "Software_Designer", "author_id": 999884, "author_profile": "https://Stackoverflow.com/users/999884", "pm_score": 3, "selected": false, "text": "strtok()" }, { "answer_id": 9385486, "author": "landen", "author_id": 1224414, "author_profile": "https://Stackoverflow.com/users/1224414", "pm_score": 2, "selected": false, "text": "vector" }, { "answer_id": 9619583, "author": "ManiP", "author_id": 576294, "author_profile": "https://Stackoverflow.com/users/576294", "pm_score": 2, "selected": false, "text": "void split(string in, vector<string>& parts, char separator) {\n string::iterator ts, curr;\n ts = curr = in.begin();\n for(; curr <= in.end(); curr++ ) {\n if( (curr == in.end() || *curr == separator) && curr > ts )\n parts.push_back( string( ts, curr ));\n if( curr == in.end() )\n break;\n if( *curr == separator ) ts = curr + 1; \n }\n}\n" }, { "answer_id": 9676623, "author": "Marco M.", "author_id": 140311, "author_profile": "https://Stackoverflow.com/users/140311", "pm_score": 6, "selected": false, "text": "template<typename T>\nvector<T> \nsplit(const T & str, const T & delimiters) {\n vector<T> v;\n typename T::size_type start = 0;\n auto pos = str.find_first_of(delimiters, start);\n while(pos != T::npos) {\n if(pos != start) // ignore empty tokens\n v.emplace_back(str, start, pos - start);\n start = pos + 1;\n pos = str.find_first_of(delimiters, start);\n }\n if(start < str.length()) // ignore trailing delimiter\n v.emplace_back(str, start, str.length() - start); // add what's left of the string\n return v;\n}\n" }, { "answer_id": 9688149, "author": "doicanhden", "author_id": 1178154, "author_profile": "https://Stackoverflow.com/users/1178154", "pm_score": 0, "selected": false, "text": "#include <list>\n#include <string>\ntemplate<class StringType = std::string, class ContainerType = std::list<StringType> >\nclass DSplitString:public ContainerType\n{\npublic:\n explicit DSplitString(const StringType& strString, char cChar, bool bSkipEmptyParts = true)\n {\n size_t iPos = 0;\n size_t iPos_char = 0;\n while(StringType::npos != (iPos_char = strString.find(cChar, iPos)))\n {\n StringType strTemp = strString.substr(iPos, iPos_char - iPos);\n if((bSkipEmptyParts && !strTemp.empty()) || (!bSkipEmptyParts))\n push_back(strTemp);\n iPos = iPos_char + 1;\n }\n }\n explicit DSplitString(const StringType& strString, const StringType& strSub, bool bSkipEmptyParts = true)\n {\n size_t iPos = 0;\n size_t iPos_char = 0;\n while(StringType::npos != (iPos_char = strString.find(strSub, iPos)))\n {\n StringType strTemp = strString.substr(iPos, iPos_char - iPos);\n if((bSkipEmptyParts && !strTemp.empty()) || (!bSkipEmptyParts))\n push_back(strTemp);\n iPos = iPos_char + strSub.length();\n }\n }\n};\n" }, { "answer_id": 11652347, "author": "Dmitry", "author_id": 1551989, "author_profile": "https://Stackoverflow.com/users/1551989", "pm_score": 2, "selected": false, "text": "namespace Core\n{\n typedef std::wstring String;\n\n void SplitString(const Core::String& input, const Core::String& splitter, std::list<Core::String>& output)\n {\n if (splitter.empty())\n {\n throw std::invalid_argument(); // for example\n }\n\n std::list<Core::String> lines;\n\n Core::String::size_type offset = 0;\n\n for (;;)\n {\n Core::String::size_type splitterPos = input.find(splitter, offset);\n\n if (splitterPos != Core::String::npos)\n {\n lines.push_back(input.substr(offset, splitterPos - offset));\n offset = splitterPos + splitter.size();\n }\n else\n {\n lines.push_back(input.substr(offset));\n break;\n }\n }\n\n lines.swap(output);\n }\n}\n\n// gtest:\n\nclass SplitStringTest: public testing::Test\n{\n};\n\nTEST_F(SplitStringTest, EmptyStringAndSplitter)\n{\n std::list<Core::String> result;\n ASSERT_ANY_THROW(Core::SplitString(Core::String(), Core::String(), result));\n}\n\nTEST_F(SplitStringTest, NonEmptyStringAndEmptySplitter)\n{\n std::list<Core::String> result;\n ASSERT_ANY_THROW(Core::SplitString(L\"xy\", Core::String(), result));\n}\n\nTEST_F(SplitStringTest, EmptyStringAndNonEmptySplitter)\n{\n std::list<Core::String> result;\n Core::SplitString(Core::String(), Core::String(L\",\"), result);\n ASSERT_EQ(1, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n}\n\nTEST_F(SplitStringTest, OneCharSplitter)\n{\n std::list<Core::String> result;\n\n Core::SplitString(L\"x,y\", L\",\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\"y\", *result.rbegin());\n\n Core::SplitString(L\",xy\", L\",\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n ASSERT_EQ(L\"xy\", *result.rbegin());\n\n Core::SplitString(L\"xy,\", L\",\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"xy\", *result.begin());\n ASSERT_EQ(Core::String(), *result.rbegin());\n}\n\nTEST_F(SplitStringTest, TwoCharsSplitter)\n{\n std::list<Core::String> result;\n\n Core::SplitString(L\"x,.y,z\", L\",.\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\"y,z\", *result.rbegin());\n\n Core::SplitString(L\"x,,y,z\", L\",,\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\"y,z\", *result.rbegin());\n}\n\nTEST_F(SplitStringTest, RecursiveSplitter)\n{\n std::list<Core::String> result;\n\n Core::SplitString(L\",,,\", L\",,\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n ASSERT_EQ(L\",\", *result.rbegin());\n\n Core::SplitString(L\",.,.,\", L\",.,\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n ASSERT_EQ(L\".,\", *result.rbegin());\n\n Core::SplitString(L\"x,.,.,y\", L\",.,\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\".,y\", *result.rbegin());\n\n Core::SplitString(L\",.,,.,\", L\",.,\", result);\n ASSERT_EQ(3, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n ASSERT_EQ(Core::String(), *(++result.begin()));\n ASSERT_EQ(Core::String(), *result.rbegin());\n}\n\nTEST_F(SplitStringTest, NullTerminators)\n{\n std::list<Core::String> result;\n\n Core::SplitString(L\"xy\", Core::String(L\"\\0\", 1), result);\n ASSERT_EQ(1, result.size());\n ASSERT_EQ(L\"xy\", *result.begin());\n\n Core::SplitString(Core::String(L\"x\\0y\", 3), Core::String(L\"\\0\", 1), result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\"y\", *result.rbegin());\n}\n" }, { "answer_id": 12221291, "author": "Steve Dell", "author_id": 1639427, "author_profile": "https://Stackoverflow.com/users/1639427", "pm_score": 4, "selected": false, "text": "#include <vector>\n#include <iostream>\n#include <string.h>\n\nusing namespace std;\n\nclass StringSplit\n{\nprivate:\n void copy_fragment(char*, char*, char*);\n void copy_fragment(char*, char*, char);\n bool match_fragment(char*, char*, int);\n int untilnextdelim(char*, char);\n int untilnextdelim(char*, char*);\n void assimilate(char*, char);\n void assimilate(char*, char*);\n bool string_contains(char*, char*);\n long calc_string_size(char*);\n void copy_string(char*, char*);\n\npublic:\n vector<char*> split_cstr(char);\n vector<char*> split_cstr(char*);\n vector<string> split_string(char);\n vector<string> split_string(char*);\n char* String;\n bool do_string;\n bool keep_empty;\n vector<char*> Container;\n vector<string> ContainerS;\n\n StringSplit(char * in)\n {\n String = in;\n }\n\n StringSplit(string in)\n {\n size_t len = calc_string_size((char*)in.c_str());\n String = new char[len + 1];\n memset(String, 0, len + 1);\n copy_string(String, (char*)in.c_str());\n do_string = true;\n }\n\n ~StringSplit()\n {\n for (int i = 0; i < Container.size(); i++)\n {\n if (Container[i] != NULL)\n {\n delete[] Container[i];\n }\n }\n if (do_string)\n {\n delete[] String;\n }\n }\n};\n" }, { "answer_id": 12447526, "author": "rhomu", "author_id": 1435414, "author_profile": "https://Stackoverflow.com/users/1435414", "pm_score": 5, "selected": false, "text": "char sep = ' ';\nstd::string s=\"1 This is an example\";\n\nfor(size_t p=0, q=0; p!=s.npos; p=q)\n std::cout << s.substr(p+(p!=0), (q=s.find(sep, p+1))-p-(p!=0)) << std::endl;\n" }, { "answer_id": 12617462, "author": "User", "author_id": 1475556, "author_profile": "https://Stackoverflow.com/users/1475556", "pm_score": 2, "selected": false, "text": "WebSockets" }, { "answer_id": 12766351, "author": "Jim Huang", "author_id": 862149, "author_profile": "https://Stackoverflow.com/users/862149", "pm_score": 3, "selected": false, "text": "0 <len:0>\n1 PICK <len:4>\n2 ANY <len:3>\n3 TWO: <len:4>\n4 <len:0>\n" }, { "answer_id": 13125497, "author": "AJMansfield", "author_id": 1324631, "author_profile": "https://Stackoverflow.com/users/1324631", "pm_score": 5, "selected": false, "text": "#include <regex.h>\n#include <string.h>\n#include <vector.h>\n\nusing namespace std;\n\nvector<string> split(string s){\n regex r (\"\\\\w+\"); //regex matches whole words, (greedy, so no fragment words)\n regex_iterator<string::iterator> rit ( s.begin(), s.end(), r );\n regex_iterator<string::iterator> rend; //iterators to iterate thru words\n vector<string> result<regex_iterator>(rit, rend);\n return result; //iterates through the matches to fill the vector\n}\n" }, { "answer_id": 13713420, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "void splitString(string str, char delim, string array[], const int arraySize)\n{\n int delimPosition, subStrSize, subStrStart = 0;\n\n for (int index = 0; delimPosition != -1; index++)\n {\n delimPosition = str.find(delim, subStrStart);\n subStrSize = delimPosition - subStrStart;\n array[index] = str.substr(subStrStart, subStrSize);\n subStrStart =+ (delimPosition + 1);\n }\n}\n" }, { "answer_id": 15864515, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string.hpp>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\nusing namespace boost;\n\nint main(int argc, char**argv) {\n typedef vector < string > list_type;\n\n list_type list;\n string line;\n\n line = \"Somewhere down the road\";\n split(list, line, is_any_of(\" \"));\n\n for(int i = 0; i < list.size(); i++)\n {\n cout << list[i] << endl;\n }\n\n return 0;\n}\n" }, { "answer_id": 17904439, "author": "LLLL", "author_id": 2261292, "author_profile": "https://Stackoverflow.com/users/2261292", "pm_score": 1, "selected": false, "text": "template <class Container, class String, class Predicate>\nvoid split(Container& output, const String& input,\n const Predicate& pred, bool trimEmpty = false) {\n auto it = begin(input);\n auto itLast = it;\n while (it = find_if(it, end(input), pred), it != end(input)) {\n if (not (trimEmpty and it == itLast)) {\n output.emplace_back(itLast, it);\n }\n ++it;\n itLast = it;\n }\n}\n" }, { "answer_id": 18039502, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "#include <vector>\n#include <string>\n#include <iostream>\n\nvoid push(std::vector<std::string> &WORDS, std::string &TMP){\n WORDS.push_back(TMP);\n TMP = \"\";\n}\nstd::vector<std::string> mySplit(char STRING[]){\n std::vector<std::string> words;\n std::string s;\n for(unsigned short i = 0; i < strlen(STRING); i++){\n if(STRING[i] != ' '){\n s += STRING[i];\n }else{\n push(words, s);\n }\n }\n push(words, s);//Used to get last split\n return words;\n}\n\nint main(){\n char string[] = \"My awesome string.\";\n std::cout << mySplit(string)[2];\n std::cin.get();\n return 0;\n}\n" }, { "answer_id": 18151541, "author": "hkBattousai", "author_id": 245376, "author_profile": "https://Stackoverflow.com/users/245376", "pm_score": 0, "selected": false, "text": "std::vector<std::wstring> SplitString(const std::wstring & String, const std::wstring & Seperator)\n{\n std::vector<std::wstring> Lines;\n size_t stSearchPos = 0;\n size_t stFoundPos;\n while (stSearchPos < String.size() - 1)\n {\n stFoundPos = String.find(Seperator, stSearchPos);\n stFoundPos = (stFoundPos == std::string::npos) ? String.size() : stFoundPos;\n Lines.push_back(String.substr(stSearchPos, stFoundPos - stSearchPos));\n stSearchPos = stFoundPos + Seperator.size();\n }\n return Lines;\n}\n" }, { "answer_id": 19154603, "author": "san45", "author_id": 2673037, "author_profile": "https://Stackoverflow.com/users/2673037", "pm_score": 3, "selected": false, "text": "#include<iostream>\n#include<string>\n#include<sstream>\n#include<vector>\nusing namespace std;\n\n vector<string> split(const string &s, char delim) {\n vector<string> elems;\n stringstream ss(s);\n string item;\n while (getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n }\n\nint main() {\n\n vector<string> x = split(\"thi is an sample test\",' ');\n unsigned int i;\n for(i=0;i<x.size();i++)\n cout<<i<<\":\"<<x[i]<<endl;\n return 0;\n}\n" }, { "answer_id": 20807773, "author": "smac89", "author_id": 2089675, "author_profile": "https://Stackoverflow.com/users/2089675", "pm_score": 2, "selected": false, "text": "#include <string>\n#include <algorithm>\n#include <unordered_set>\n\nusing namespace std;\n\nclass LazyStringSplitter\n{\n string::const_iterator start, finish;\n unordered_set<char> chop;\n\npublic:\n\n // Empty Constructor\n explicit LazyStringSplitter()\n {}\n\n explicit LazyStringSplitter (const string cstr, const string delims)\n : start(cstr.begin())\n , finish(cstr.end())\n , chop(delims.begin(), delims.end())\n {}\n\n void operator () (const string cstr, const string delims)\n {\n chop.insert(delims.begin(), delims.end());\n start = cstr.begin();\n finish = cstr.end();\n }\n\n bool empty() const { return (start >= finish); }\n\n string next()\n {\n // return empty string\n // if ran out of characters\n if (empty())\n return string(\"\");\n\n auto runner = find_if(start, finish, [&](char c) {\n return chop.count(c) == 1;\n });\n\n // construct next string\n string ret(start, runner);\n start = runner + 1;\n\n // Never return empty string\n // + tail recursion makes this method efficient\n return !ret.empty() ? ret : next();\n }\n};\n" }, { "answer_id": 20981222, "author": "DannyK", "author_id": 969968, "author_profile": "https://Stackoverflow.com/users/969968", "pm_score": 4, "selected": false, "text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <strtk.hpp>\n\nconst char *whitespace = \" \\t\\r\\n\\f\";\nconst char *whitespace_and_punctuation = \" \\t\\r\\n\\f;,=\";\n\nint main()\n{\n { // normal parsing of a string into a vector of strings\n std::string s(\"Somewhere down the road\");\n std::vector<std::string> result;\n if( strtk::parse( s, whitespace, result ) )\n {\n for(size_t i = 0; i < result.size(); ++i )\n std::cout << result[i] << std::endl;\n }\n }\n\n { // parsing a string into a vector of floats with other separators\n // besides spaces\n\n std::string s(\"3.0, 3.14; 4.0\");\n std::vector<float> values;\n if( strtk::parse( s, whitespace_and_punctuation, values ) )\n {\n for(size_t i = 0; i < values.size(); ++i )\n std::cout << values[i] << std::endl;\n }\n }\n\n { // parsing a string into specific variables\n\n std::string s(\"angle = 45; radius = 9.9\");\n std::string w1, w2;\n float v1, v2;\n if( strtk::parse( s, whitespace_and_punctuation, w1, v1, w2, v2) )\n {\n std::cout << \"word \" << w1 << \", value \" << v1 << std::endl;\n std::cout << \"word \" << w2 << \", value \" << v2 << std::endl;\n }\n }\n\n return 0;\n}\n" }, { "answer_id": 22460128, "author": "robcsi", "author_id": 3257292, "author_profile": "https://Stackoverflow.com/users/3257292", "pm_score": 2, "selected": false, "text": "//use like this\n//std::vector<std::wstring> vec = Split<std::wstring> (L\"Hello##world##!\", L\"##\");\n\ntemplate <typename valueType>\nstatic std::vector <valueType> Split (valueType text, const valueType& delimiter)\n{\n std::vector <valueType> tokens;\n size_t pos = 0;\n valueType token;\n\n while ((pos = text.find(delimiter)) != valueType::npos) \n {\n token = text.substr(0, pos);\n tokens.push_back (token);\n text.erase(0, pos + delimiter.length());\n }\n tokens.push_back (text);\n\n return tokens;\n}\n" }, { "answer_id": 22925061, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 2, "selected": false, "text": "std::string" }, { "answer_id": 23486832, "author": "dk123", "author_id": 1709725, "author_profile": "https://Stackoverflow.com/users/1709725", "pm_score": 5, "selected": false, "text": "#include <regex>\n#include <string>\n#include <vector>\n\nstd::vector<string> Tokenize( const string str, const std::regex regex )\n{\n using namespace std;\n\n std::vector<string> result;\n\n sregex_token_iterator it( str.begin(), str.end(), regex, -1 );\n sregex_token_iterator reg_end;\n\n for ( ; it != reg_end; ++it ) {\n if ( !it->str().empty() ) //token could be empty:check\n result.emplace_back( it->str() );\n }\n\n return result;\n}\n" }, { "answer_id": 23776789, "author": "Khaled.K", "author_id": 2128327, "author_profile": "https://Stackoverflow.com/users/2128327", "pm_score": -1, "selected": false, "text": "string cut (string& str, const string& del)\n{\n string f = str;\n\n if (in.find_first_of(del) != string::npos)\n {\n f = str.substr(0,str.find_first_of(del));\n str = str.substr(str.find_first_of(del)+del.length());\n }\n\n return f;\n}\n\nvector<string> split (const string& in, const string& del=\" \")\n{\n vector<string> out();\n string t = in;\n\n while (t.length() > del.length())\n out.push_back(cut(t,del));\n\n return out;\n}\n" }, { "answer_id": 24964916, "author": "tony gil", "author_id": 1166727, "author_profile": "https://Stackoverflow.com/users/1166727", "pm_score": 1, "selected": false, "text": "// adapted from a \"regular\" csv parse\nstd::string stringIn = \"my csv is 10233478 NOTseparated by commas\";\nstd::vector<std::string> commaSeparated(1);\nint commaCounter = 0;\nfor (int i=0; i<stringIn.size(); i++) {\n if (stringIn[i] == \" \") {\n commaSeparated.push_back(\"\");\n commaCounter++;\n } else {\n commaSeparated.at(commaCounter) += stringIn[i];\n }\n}\n" }, { "answer_id": 25383354, "author": "mchiasson", "author_id": 1620670, "author_profile": "https://Stackoverflow.com/users/1620670", "pm_score": 2, "selected": false, "text": "#include <vector>\n\ninline std::vector<std::string> Split(const std::string &str, const std::string &delim = \" \")\n{\n std::vector<std::string> tokens;\n if (str.size() > 0)\n {\n if (delim.size() > 0)\n {\n std::string::size_type currPos = 0, prevPos = 0;\n while ((currPos = str.find(delim, prevPos)) != std::string::npos)\n {\n std::string item = str.substr(prevPos, currPos - prevPos);\n if (item.size() > 0)\n {\n tokens.push_back(item);\n }\n prevPos = currPos + 1;\n }\n tokens.push_back(str.substr(prevPos));\n }\n else\n {\n tokens.push_back(str);\n }\n }\n return tokens;\n}\n" }, { "answer_id": 27125803, "author": "Galik", "author_id": 3807729, "author_profile": "https://Stackoverflow.com/users/3807729", "pm_score": 3, "selected": false, "text": "#include <vector>\n#include <string>\n#include <cstring>\n#include <iostream>\n#include <algorithm>\n#include <functional>\n\nstd::vector<std::string> split(const std::string& s)\n{\n std::vector<std::string> v;\n\n const auto end = s.end();\n auto to = s.begin();\n decltype(to) from;\n\n while((from = std::find_if(to, end,\n [](char c){ return !std::isspace(c); })) != end)\n {\n to = std::find_if(from, end, [](char c){ return std::isspace(c); });\n v.emplace_back(from, to);\n }\n\n return v;\n}\n\nint main()\n{\n std::string s = \"this is the string to split\";\n\n auto v = split(s);\n\n for(auto&& s: v)\n std::cout << s << '\\n';\n}\n" }, { "answer_id": 27512317, "author": "Richard Hodges", "author_id": 2015579, "author_profile": "https://Stackoverflow.com/users/2015579", "pm_score": 0, "selected": false, "text": "template<class Container>\nstd::vector<std::string> split_by_delimiters(const std::string& input, const Container& delimiters)\n{\n std::vector<std::string> result;\n\n for (auto current = begin(input) ; current != end(input) ; )\n {\n auto first = find_if(current, end(input), not_in(delimiters));\n if (first == end(input)) break;\n auto last = find_if(first, end(input), is_in(delimiters));\n result.emplace_back(first, last);\n current = last;\n }\n return result;\n}\n" }, { "answer_id": 27556071, "author": "Dietmar Kühl", "author_id": 1120273, "author_profile": "https://Stackoverflow.com/users/1120273", "pm_score": 3, "selected": false, "text": "std::istream_iterator<T>" }, { "answer_id": 29007199, "author": "Kakashi", "author_id": 2049325, "author_profile": "https://Stackoverflow.com/users/2049325", "pm_score": 0, "selected": false, "text": "std::vector<std::string> split(std::string str, const char* delim) {\n std::vector<std::string> v;\n std::string tmp;\n\n for(std::string::const_iterator i = str.begin(); i <= str.end(); ++i) {\n if(*i != *delim && i != str.end()) {\n tmp += *i;\n } else {\n if (tmp.length() > 0) {\n v.push_back(tmp);\n }\n tmp = \"\";\n }\n }\n\n return v;\n}\n" }, { "answer_id": 30619990, "author": "Venkata Naidu M", "author_id": 2119671, "author_profile": "https://Stackoverflow.com/users/2119671", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <cstring>\nusing namespace std;\n\nint main()\n{\n char str[]=\"Mickey M;12034;911416313;M;01a;9001;NULL;0;13;12;0;CPP,C;MSC,3D;FEND,BEND,SEC;\";\n char *pch = strtok (str,\";,\");\n while (pch != NULL)\n {\n cout<<pch<<\"\\n\";\n pch = strtok (NULL, \";,\");\n }\n return 0;\n}\n" }, { "answer_id": 31170110, "author": "abe312", "author_id": 3719699, "author_profile": "https://Stackoverflow.com/users/3719699", "pm_score": -1, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n\nint main() {\n using namespace std;\n int n=8;\n string sentence = \"10 20 30 40 5 6 7 8\";\n istringstream iss(sentence);\n\n vector<string> tokens;\ncopy(istream_iterator<string>(iss),\n istream_iterator<string>(),\n back_inserter(tokens));\n\n for(int i=0;i<n;i++){\n cout<<tokens.at(i);\n }\n\n\n}\n" }, { "answer_id": 32356675, "author": "Jehjoa", "author_id": 365908, "author_profile": "https://Stackoverflow.com/users/365908", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <vector>\n\nstd::vector<std::string> split(const std::string &s, const std::string &delims)\n{\n std::vector<std::string> result;\n std::string::size_type pos = 0;\n while (std::string::npos != (pos = s.find_first_not_of(delims, pos))) {\n auto pos2 = s.find_first_of(delims, pos);\n result.emplace_back(s.substr(pos, std::string::npos == pos2 ? pos2 : pos2 - pos));\n pos = pos2;\n }\n return result;\n}\n\nint main()\n{\n std::string text{\"And then I said: \\\"I don't get it, why would you even do that!?\\\"\"};\n std::string delims{\" :;\\\".,?!\"};\n auto words = split(text, delims);\n std::cout << \"\\nSentence:\\n \" << text << \"\\n\\nWords:\";\n for (const auto &w : words) {\n std::cout << \"\\n \" << w;\n }\n return 0;\n}\n" }, { "answer_id": 32920320, "author": "Tristan Brindle", "author_id": 2797826, "author_profile": "https://Stackoverflow.com/users/2797826", "pm_score": 2, "selected": false, "text": "template <typename Container, typename InputIter, typename ForwardIter>\nContainer\nsplit(InputIter first, InputIter last,\n ForwardIter s_first, ForwardIter s_last)\n{\n Container output;\n\n while (true) {\n auto pos = std::find_first_of(first, last, s_first, s_last);\n output.emplace_back(first, pos);\n if (pos == last) {\n break;\n }\n\n first = ++pos;\n }\n\n return output;\n}\n\ntemplate <typename Output = std::vector<std::string>,\n typename Input = std::string,\n typename Delims = std::string>\nOutput\nsplit(const Input& input, const Delims& delims = \" \")\n{\n using std::cbegin;\n using std::cend;\n return split<Output>(cbegin(input), cend(input),\n cbegin(delims), cend(delims));\n}\n\nauto vec = split(\"Mary had a little lamb\");\n" }, { "answer_id": 33287535, "author": "Bushuev", "author_id": 5457601, "author_profile": "https://Stackoverflow.com/users/5457601", "pm_score": 0, "selected": false, "text": "#include<iostream>\n#include<string>\n#include<vector>\n#include<iterator>\n#include<sstream>\n#include<string>\n\nusing namespace std;\nvoid replaceOtherChars(string &input, vector<char> &dividers)\n{\n const char divider = dividers.at(0);\n int replaceIndex = 0;\n vector<char>::iterator it_begin = dividers.begin()+1,\n it_end= dividers.end();\n for(;it_begin!=it_end;++it_begin)\n {\n replaceIndex = 0;\n while(true)\n {\n replaceIndex=input.find_first_of(*it_begin,replaceIndex);\n if(replaceIndex==-1)\n break;\n input.at(replaceIndex)=divider;\n }\n }\n}\nvector<string> split(string str, vector<char> chars, bool missEmptySpace =true )\n{\n vector<string> result;\n const char divider = chars.at(0);\n replaceOtherChars(str,chars);\n stringstream stream;\n stream<<str; \n string temp;\n while(getline(stream,temp,divider))\n {\n if(missEmptySpace && temp.empty())\n continue;\n result.push_back(temp);\n }\n return result;\n}\nint main()\n{\n string str =\"milk, pigs.... hot-dogs \";\n vector<char> arr;\n arr.push_back(' '); arr.push_back(','); arr.push_back('.');\n vector<string> result = split(str,arr);\n vector<string>::iterator it_begin= result.begin(),\n it_end= result.end();\n for(;it_begin!=it_end;++it_begin)\n {\n cout<<*it_begin<<endl;\n }\nreturn 0;\n}\n" }, { "answer_id": 33404623, "author": "Jonny", "author_id": 129202, "author_profile": "https://Stackoverflow.com/users/129202", "pm_score": 0, "selected": false, "text": "class Myneatclass {\npublic:\n static std::vector<std::string>& split(const std::string &s, char delim, std::vector<std::string> &elems, const size_t MAXELEMENTS = 0);\n static std::vector<std::string> split(const std::string &s, char delim, const size_t MAXELEMENTS = 0);\n};\n" }, { "answer_id": 33480125, "author": "user1438233", "author_id": 1438233, "author_profile": "https://Stackoverflow.com/users/1438233", "pm_score": 4, "selected": false, "text": "#include <vector>\n#include <string>\nusing namespace std;\n\nvector<string> split(string data, string token)\n{\n vector<string> output;\n size_t pos = string::npos; // size_t to avoid improbable overflow\n do\n {\n pos = data.find(token);\n output.push_back(data.substr(0, pos));\n if (string::npos != pos)\n data = data.substr(pos + token.size());\n } while (string::npos != pos);\n return output;\n}\n" }, { "answer_id": 34703527, "author": "torayeff", "author_id": 1385385, "author_profile": "https://Stackoverflow.com/users/1385385", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n string str = \"ABC AABCD CDDD RABC GHTTYU FR\";\n str += \" \"; //dirty hack: adding extra space to the end\n vector<string> v;\n\n for (int i=0; i<(int)str.size(); i++) {\n int a, b;\n a = i;\n\n for (int j=i; j<(int)str.size(); j++) {\n if (str[j] == ' ') {\n b = j;\n i = j;\n break;\n }\n }\n v.push_back(str.substr(a, b-a));\n }\n\n for (int i=0; i<v.size(); i++) {\n cout<<v[i].size()<<\" \"<<v[i]<<endl;\n }\n return 0;\n}\n" }, { "answer_id": 34705440, "author": "AlwaysLearning", "author_id": 2725810, "author_profile": "https://Stackoverflow.com/users/2725810", "pm_score": 1, "selected": false, "text": "template<class V, typename T>\nbool in(const V &v, const T &el) {\n return std::find(v.begin(), v.end(), el) != v.end();\n}\n" }, { "answer_id": 36739701, "author": "yunhasnawa", "author_id": 1179484, "author_profile": "https://Stackoverflow.com/users/1179484", "pm_score": 2, "selected": false, "text": "std::vector<size_t> str_pos(const std::string &search, const std::string &target)\n{\n std::vector<size_t> founds;\n\n if(!search.empty())\n {\n size_t start_pos = 0;\n\n while (true)\n {\n size_t found_pos = target.find(search, start_pos);\n\n if(found_pos != std::string::npos)\n {\n size_t found = found_pos;\n\n founds.push_back(found);\n\n start_pos = (found_pos + 1);\n }\n else\n {\n break;\n }\n }\n }\n\n return founds;\n}\n\nstd::string str_sub_index(size_t begin_index, size_t end_index, const std::string &target)\n{\n std::string sub;\n\n size_t size = target.length();\n\n const char* copy = target.c_str();\n\n for(size_t i = begin_index; i <= end_index; i++)\n {\n if(i >= size)\n {\n break;\n }\n else\n {\n char c = copy[i];\n\n sub += c;\n }\n }\n\n return sub;\n}\n\nstd::vector<std::string> str_split(const std::string &delimiter, const std::string &target)\n{\n std::vector<std::string> splits;\n\n if(!delimiter.empty())\n {\n std::vector<size_t> founds = str_pos(delimiter, target);\n\n size_t founds_size = founds.size();\n\n if(founds_size > 0)\n {\n size_t search_len = delimiter.length();\n\n size_t begin_index = 0;\n\n for(int i = 0; i <= founds_size; i++)\n {\n std::string sub;\n\n if(i != founds_size)\n {\n size_t pos = founds.at(i);\n\n sub = str_sub_index(begin_index, pos - 1, target);\n\n begin_index = (pos + search_len);\n }\n else\n {\n sub = str_sub_index(begin_index, (target.length() - 1), target);\n }\n\n splits.push_back(sub);\n }\n }\n }\n\n return splits;\n}\n" }, { "answer_id": 39334298, "author": "pz64_", "author_id": 6737471, "author_profile": "https://Stackoverflow.com/users/6737471", "pm_score": 2, "selected": false, "text": "vector<string> get_tokens(string str) {\n vector<string> dt;\n stringstream ss;\n string tmp; \n ss << str;\n for (size_t i; !ss.eof(); ++i) {\n ss >> tmp;\n dt.push_back(tmp);\n }\n return dt;\n}\n" }, { "answer_id": 39359311, "author": "solstice333", "author_id": 2630028, "author_profile": "https://Stackoverflow.com/users/2630028", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <regex>\n\nusing namespace std;\n\nint main() {\n string s = \"foo bar baz\";\n regex e(\"\\\\s+\");\n regex_token_iterator<string::iterator> i(s.begin(), s.end(), e, -1);\n regex_token_iterator<string::iterator> end;\n while (i != end)\n cout << \" [\" << *i++ << \"]\";\n}\n" }, { "answer_id": 39428548, "author": "Saksham Sharma", "author_id": 2928458, "author_profile": "https://Stackoverflow.com/users/2928458", "pm_score": 2, "selected": false, "text": "#include<iostream>\n#include<vector>\n#include<string>\n#include<stdio.h>\nusing namespace std;\nint main()\n{\n char x = '\\0';\n string s = \"\";\n vector<string> q;\n x = getchar();\n while(x != '\\n')\n {\n if(x == ' ')\n {\n q.push_back(s);\n s = \"\";\n x = getchar();\n continue;\n }\n s = s + x;\n x = getchar();\n }\n q.push_back(s);\n for(int i = 0; i<q.size(); i++)\n cout<<q[i]<<\" \";\n return 0;\n}\n" }, { "answer_id": 43999194, "author": "Timmmm", "author_id": 265521, "author_profile": "https://Stackoverflow.com/users/265521", "pm_score": 2, "selected": false, "text": "\"\\r\\n\"" }, { "answer_id": 44246368, "author": "小文件", "author_id": 4869018, "author_profile": "https://Stackoverflow.com/users/4869018", "pm_score": 0, "selected": false, "text": "string" }, { "answer_id": 44294208, "author": "Romário", "author_id": 2507567, "author_profile": "https://Stackoverflow.com/users/2507567", "pm_score": 2, "selected": false, "text": "split" }, { "answer_id": 44776084, "author": "Joakim L. Christiansen", "author_id": 4216153, "author_profile": "https://Stackoverflow.com/users/4216153", "pm_score": -1, "selected": false, "text": "std::vector <std::string> split(const string &input, auto delimiter, bool skipEmpty=true) {\n /*\n Splits a string at each delimiter and returns these strings as a string vector.\n If the delimiter is not found then nothing is returned.\n If skipEmpty is true then strings between delimiters that are 0 in length will be skipped.\n */\n bool delimiterFound = false;\n int pos=0, pPos=0;\n std::vector <std::string> result;\n while (true) {\n pos = input.find(delimiter,pPos);\n if (pos != std::string::npos) {\n if (skipEmpty==false or pos-pPos > 0) // if empty values are to be kept or not\n result.push_back(input.substr(pPos,pos-pPos));\n delimiterFound = true;\n } else {\n if (pPos < input.length() and delimiterFound) {\n if (skipEmpty==false or input.length()-pPos > 0) // if empty values are to be kept or not\n result.push_back(input.substr(pPos,input.length()-pPos));\n }\n break;\n }\n pPos = pos+1;\n }\n return result;\n}\n" }, { "answer_id": 47473248, "author": "Oleg", "author_id": 8766845, "author_profile": "https://Stackoverflow.com/users/8766845", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <deque>\n\nstd::deque<std::string> split(\n const std::string& line, \n std::string::value_type delimiter,\n bool skipEmpty = false\n) {\n std::deque<std::string> parts{};\n\n if (!skipEmpty && !line.empty() && delimiter == line.at(0)) {\n parts.push_back({});\n }\n\n for (const std::string::value_type& c : line) {\n if (\n (\n c == delimiter \n &&\n (skipEmpty ? (!parts.empty() && !parts.back().empty()) : true)\n )\n ||\n (c != delimiter && parts.empty())\n ) {\n parts.push_back({});\n }\n\n if (c != delimiter) {\n parts.back().push_back(c);\n }\n }\n\n if (skipEmpty && !parts.empty() && parts.back().empty()) {\n parts.pop_back();\n }\n\n return parts;\n}\n\nvoid test(const std::string& line) {\n std::cout << line << std::endl;\n\n std::cout << \"skipEmpty=0 |\";\n for (const std::string& part : split(line, ':')) {\n std::cout << part << '|';\n }\n std::cout << std::endl;\n\n std::cout << \"skipEmpty=1 |\";\n for (const std::string& part : split(line, ':', true)) {\n std::cout << part << '|';\n }\n std::cout << std::endl;\n\n std::cout << std::endl;\n}\n\nint main() {\n test(\"foo:bar:::baz\");\n test(\"\");\n test(\"foo\");\n test(\":\");\n test(\"::\");\n test(\":foo\");\n test(\"::foo\");\n test(\":foo:\");\n test(\":foo::\");\n\n return 0;\n}\n" }, { "answer_id": 47733270, "author": "NL628", "author_id": 8925851, "author_profile": "https://Stackoverflow.com/users/8925851", "pm_score": 4, "selected": false, "text": "#include <boost/algorithm/string.hpp>\nstd::vector<std::string> strs;\nboost::split(strs, \"string to split\", boost::is_any_of(\"\\t \"));\n" }, { "answer_id": 54134243, "author": "Porsche9II", "author_id": 1683850, "author_profile": "https://Stackoverflow.com/users/1683850", "pm_score": 4, "selected": false, "text": "std::string_view" }, { "answer_id": 54220083, "author": "okovko", "author_id": 5122006, "author_profile": "https://Stackoverflow.com/users/5122006", "pm_score": 1, "selected": false, "text": "<tag></tag>" }, { "answer_id": 60732623, "author": "balki", "author_id": 463758, "author_profile": "https://Stackoverflow.com/users/463758", "pm_score": 1, "selected": false, "text": "std::function" }, { "answer_id": 61621475, "author": "J. Willus", "author_id": 6327684, "author_profile": "https://Stackoverflow.com/users/6327684", "pm_score": 4, "selected": false, "text": "split" }, { "answer_id": 62244701, "author": "Nur Bijoy", "author_id": 9162697, "author_profile": "https://Stackoverflow.com/users/9162697", "pm_score": 3, "selected": false, "text": "#include <bits/stdc++.h>\n\nusing namespace std ;\nint main()\n{\n string str, token ;\n getline(cin, str) ; // get the string as input\n istringstream ss(str); // insert the string into tokenizer\n\n vector<string> tokens; // vector tokens holds the tokens\n\n while (ss >> token) tokens.push_back(token); // splits the tokens\n for(auto x : tokens) cout << x << endl ; // prints the tokens\n\n return 0;\n}\n\n\n" }, { "answer_id": 68655819, "author": "Kaznov", "author_id": 6401179, "author_profile": "https://Stackoverflow.com/users/6401179", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <ranges>\n#include <string_view>\n\nnamespace views = std::views;\nusing str = std::string_view;\n\nconstexpr str text = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit.\";\n\nauto splitByWords(str input) {\n return input\n | views::split(' ')\n | views::transform([](auto &&r) -> str {\n return {r.begin(), r.end()};\n });\n}\n\nauto main() -> int {\n for (str &&word : splitByWords(text)) {\n std::cout << word << '\\n';\n }\n}\n" }, { "answer_id": 69210405, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#include <vector>\n#include <string>\nstd::vector<std::string> splitby(std::string string, char splitter) {\n int splits = 0;\n std::vector<std::string> result = {};\n std::string locresult = \"\";\n for (unsigned int i = 0; i < string.size(); i++) {\n if ((char)string.at(i) != splitter) {\n locresult += string.at(i);\n }\n else {\n result.push_back(locresult);\n locresult = \"\";\n }\n }\n if (splits == 0) {\n result.push_back(locresult);\n }\n return result;\n}\n\nvoid printvector(std::vector<std::string> v) {\n std::cout << '{';\n for (unsigned int i = 0; i < v.size(); i++) {\n if (i < v.size() - 1) {\n std::cout << '\"' << v.at(i) << \"\\\",\";\n }\n else {\n std::cout << '\"' << v.at(i) << \"\\\"\";\n }\n }\n std::cout << \"}\\n\";\n}\n" }, { "answer_id": 69676745, "author": "AlQuemist", "author_id": 3484761, "author_profile": "https://Stackoverflow.com/users/3484761", "pm_score": 1, "selected": false, "text": "std::string" }, { "answer_id": 71207982, "author": "Sam B", "author_id": 1058419, "author_profile": "https://Stackoverflow.com/users/1058419", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <sstream>\n\nstd::string input = \"This is a sentence to read\";\nstd::istringstream ss(input);\nstd::string token;\n\nwhile(std::getline(ss, token, ' ')) {\n std::cout << token << endl;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
236,151
<p>I recently started using Git as my version control system for some Cocoa projects I'm working on and wondered if there are best practices for working with version control systems on Cocoa projects.</p> <p>There is the obvious "build" directory which I exclude from versioning as it's not important and can change quite a bit when debugging some code and then there are those .pbxuser and .perspectivev3 which change ever time I open the project in Xcode but I don't really know if they are "important" enough to be checked in.</p> <p>Is there a commonly used configuration for excluding unimportant files?</p> <p>Thanks in advance</p>
[ { "answer_id": 236189, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 4, "selected": true, "text": ".hgignore" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29618/" ]
236,166
<p>I am using System.IO.Directory.GetCurrentDirectory() to get the current directory in my web service, but that does not give me the current directory. How do I get the current directory in a web service?</p> <p>Thanks Stuart </p>
[ { "answer_id": 236169, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 6, "selected": false, "text": "HttpContext.Current.Server.MapPath(\"~/\") \n" }, { "answer_id": 236289, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 3, "selected": false, "text": "HttpContext.Current.Server.MapPath(\"~/\")" }, { "answer_id": 2851750, "author": "felickz", "author_id": 343347, "author_profile": "https://Stackoverflow.com/users/343347", "pm_score": 5, "selected": false, "text": "HttpContext.Current.Server.MapPath(\".\")" }, { "answer_id": 6916691, "author": "Damith", "author_id": 2558060, "author_profile": "https://Stackoverflow.com/users/2558060", "pm_score": 4, "selected": false, "text": "HostingEnvironment.ApplicationPhysicalPath" }, { "answer_id": 24895963, "author": "user3866085", "author_id": 3866085, "author_profile": "https://Stackoverflow.com/users/3866085", "pm_score": 5, "selected": false, "text": "AppDomain.CurrentDomain.BaseDirectory;\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23149/" ]
236,172
<p>I have several <code>std::vector</code>, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold <code>int</code>s and some of them <code>std::string</code>s.</p> <p>Pseudo code:</p> <pre><code>std::vector&lt;int&gt; Index = { 3, 1, 2 }; std::vector&lt;std::string&gt; Values = { "Third", "First", "Second" }; Transformation = sort(Index); Index is now { 1, 2, 3}; ... magic happens as Transformation is applied to Values ... Values are now { "First", "Second", "Third" }; </code></pre>
[ { "answer_id": 236199, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "typedef vector<int>::const_iterator myiter;\n\nvector<pair<size_t, myiter> > order(Index.size());\n\nsize_t n = 0;\nfor (myiter it = Index.begin(); it != Index.end(); ++it, ++n)\n order[n] = make_pair(n, it);\n" }, { "answer_id": 238075, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": "using namespace std;\n\ntemplate< typename Iterator, typename Comparator >\nstruct Index {\n vector<Iterator> v;\n\n Index( Iterator from, Iterator end, Comparator& c ){\n v.reserve( std::distance(from,end) );\n for( ; from != end; ++from ){\n v.push_back(from); // no deref!\n }\n sort( v.begin(), v.end(), c );\n }\n\n};\n\ntemplate< typename Iterator, typename Comparator >\nIndex<Iterator,Comparator> index ( Iterator from, Iterator end, Comparator& c ){\n return Index<Iterator,Comparator>(from,end,c);\n}\n\nstruct mytype {\n string name;\n double number;\n};\n\ntemplate< typename Iter >\nstruct NameLess : public binary_function<Iter, Iter, bool> {\n bool operator()( const Iter& t1, const Iter& t2 ) const { return t1->name < t2->name; }\n};\n\ntemplate< typename Iter >\nstruct NumLess : public binary_function<Iter, Iter, bool> {\n bool operator()( const Iter& t1, const Iter& t2 ) const { return t1->number < t2->number; }\n};\n\nvoid indices() {\n\n mytype v[] = { { \"me\" , 0.0 }\n , { \"you\" , 1.0 }\n , { \"them\" , -1.0 }\n };\n mytype* vend = v + _countof(v);\n\n Index<mytype*, NameLess<mytype*> > byname( v, vend, NameLess<mytype*>() );\n Index<mytype*, NumLess <mytype*> > bynum ( v, vend, NumLess <mytype*>() );\n\n assert( byname.v[0] == v+0 );\n assert( byname.v[1] == v+2 );\n assert( byname.v[2] == v+1 );\n\n assert( bynum.v[0] == v+2 );\n assert( bynum.v[1] == v+0 );\n assert( bynum.v[2] == v+1 );\n\n}\n" }, { "answer_id": 342940, "author": "lalitm", "author_id": 28555, "author_profile": "https://Stackoverflow.com/users/28555", "pm_score": 3, "selected": false, "text": "typedef std::vector<int> int_vec_t;\ntypedef std::vector<std::string> str_vec_t;\ntypedef std::vector<size_t> index_vec_t;\n\nclass SequenceGen {\n public:\n SequenceGen (int start = 0) : current(start) { }\n int operator() () { return current++; }\n private:\n int current;\n};\n\nclass Comp{\n int_vec_t& _v;\n public:\n Comp(int_vec_t& v) : _v(v) {}\n bool operator()(size_t i, size_t j){\n return _v[i] < _v[j];\n }\n};\n\nindex_vec_t indices(3);\nstd::generate(indices.begin(), indices.end(), SequenceGen(0));\n//indices are {0, 1, 2}\n\nint_vec_t Index = { 3, 1, 2 };\nstr_vec_t Values = { \"Third\", \"First\", \"Second\" };\n\nstd::sort(indices.begin(), indices.end(), Comp(Index));\n//now indices are {1,2,0}\n" }, { "answer_id": 26533002, "author": "Tim MB", "author_id": 794283, "author_profile": "https://Stackoverflow.com/users/794283", "pm_score": 2, "selected": false, "text": "keys" }, { "answer_id": 27423416, "author": "user1596722", "author_id": 1596722, "author_profile": "https://Stackoverflow.com/users/1596722", "pm_score": 1, "selected": false, "text": "template<typename T>\nstruct applyOrderinPlace\n{\nvoid operator()(const vector<size_t>& order, vector<T>& vectoOrder)\n{\nvector<bool> indicator(order.size(),0);\nsize_t start = 0, cur = 0, next = order[cur];\nsize_t indx = 0;\nT tmp; \n\nwhile(indx < order.size())\n{\n//find unprocessed index\nif(indicator[indx])\n{ \n++indx;\ncontinue;\n}\n\nstart = indx;\ncur = start;\nnext = order[cur];\ntmp = vectoOrder[start];\n\nwhile(next != start)\n{\nvectoOrder[cur] = vectoOrder[next];\nindicator[cur] = true; \ncur = next;\nnext = order[next];\n}\nvectoOrder[cur] = tmp;\nindicator[cur] = true;\n}\n}\n};\n" }, { "answer_id": 35901428, "author": "Ziezi", "author_id": 3313438, "author_profile": "https://Stackoverflow.com/users/3313438", "pm_score": 0, "selected": false, "text": "names" }, { "answer_id": 44987027, "author": "umair butt", "author_id": 8078229, "author_profile": "https://Stackoverflow.com/users/8078229", "pm_score": 0, "selected": false, "text": "**// C++ program to demonstrate sorting in vector\n// of pair according to 2nd element of pair\n#include <iostream>\n#include<string>\n#include<vector>\n#include <algorithm>\n\nusing namespace std;\n\n// Driver function to sort the vector elements\n// by second element of pairs\nbool sortbysec(const pair<char,char> &a,\n const pair<int,int> &b)\n{\n return (a.second < b.second);\n}\n\nint main()\n{\n // declaring vector of pairs\n vector< pair <char, int> > vect;\n\n // Initialising 1st and 2nd element of pairs\n // with array values\n //int arr[] = {10, 20, 5, 40 };\n //int arr1[] = {30, 60, 20, 50};\n char arr[] = { ' a', 'b', 'c' };\n int arr1[] = { 4, 7, 1 };\n\n int n = sizeof(arr)/sizeof(arr[0]);\n\n // Entering values in vector of pairs\n for (int i=0; i<n; i++)\n vect.push_back( make_pair(arr[i],arr1[i]) );\n\n // Printing the original vector(before sort())\n cout << \"The vector before sort operation is:\\n\" ;\n for (int i=0; i<n; i++)\n {\n // \"first\" and \"second\" are used to access\n // 1st and 2nd element of pair respectively\n cout << vect[i].first << \" \"\n << vect[i].second << endl;\n\n }\n\n // Using sort() function to sort by 2nd element\n // of pair\n sort(vect.begin(), vect.end(), sortbysec);\n\n // Printing the sorted vector(after using sort())\n cout << \"The vector after sort operation is:\\n\" ;\n for (int i=0; i<n; i++)\n {\n // \"first\" and \"second\" are used to access\n // 1st and 2nd element of pair respectively\n cout << vect[i].first << \" \"\n << vect[i].second << endl;\n }\n getchar();\n return 0;`enter code here`\n}**\n" }, { "answer_id": 56044446, "author": "kingusiu", "author_id": 328071, "author_profile": "https://Stackoverflow.com/users/328071", "pm_score": 0, "selected": false, "text": "template< typename T, typename U >\nstd::vector<T> sortVecAByVecB( std::vector<T> & a, std::vector<U> & b ){\n\n // zip the two vectors (A,B)\n std::vector<std::pair<T,U>> zipped(a.size());\n for( size_t i = 0; i < a.size(); i++ ) zipped[i] = std::make_pair( a[i], b[i] );\n\n // sort according to B\n std::sort(zipped.begin(), zipped.end(), []( auto & lop, auto & rop ) { return lop.second < rop.second; }); \n\n // extract sorted A\n std::vector<T> sorted;\n std::transform(zipped.begin(), zipped.end(), std::back_inserter(sorted), []( auto & pair ){ return pair.first; }); \n\n return sorted;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8331/" ]
236,183
<p>I want to be able to put preformatted text (i.e. containing line breaks) into a single cell of a FitNesse fixture table. Is there a way to manipulate the FitNesse wiki markup to do this?</p>
[ { "answer_id": 236207, "author": "Matthew Murdoch", "author_id": 4023, "author_profile": "https://Stackoverflow.com/users/4023", "pm_score": 2, "selected": false, "text": "!define sql { SELECT *\n FROM bar\n WHERE gaz = 14\n}\n\n|sql|\n|${sql}|\n" }, { "answer_id": 587889, "author": "Johannes Brodwall", "author_id": 27658, "author_profile": "https://Stackoverflow.com/users/27658", "pm_score": 5, "selected": true, "text": "|sql|\n|{{{!- SELECT *\n FROM bar\n WHERE gaz = 14\n-!}}}|\n" }, { "answer_id": 25571927, "author": "Kenny Evitt", "author_id": 173497, "author_profile": "https://Stackoverflow.com/users/173497", "pm_score": 1, "selected": false, "text": "|sql|\n|!-Some text\nthat spans\nmultiple lines.\n-!|\n" }, { "answer_id": 26120457, "author": "Michael Técourt", "author_id": 2187110, "author_profile": "https://Stackoverflow.com/users/2187110", "pm_score": 1, "selected": false, "text": "| col1 | col2 |\n| !- col1 cell <br /> with line break -! | col2 cell without line break |\n" }, { "answer_id": 64265787, "author": "Jason Slobotski", "author_id": 5665753, "author_profile": "https://Stackoverflow.com/users/5665753", "pm_score": 1, "selected": false, "text": "define myVarWithLineBreaks {!-This is my\ntext with line\nbreaks-!}\n\n|col |col2 |\n|${myVarWithLineBreaks}|other value|\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
236,203
<p>I have a div with a <code>&lt;h1&gt;</code> tag in a div, with no margins. If I define any doctype, a white space appears above the div.</p> <p>If I remove the <code>&lt;h1&gt;</code> tags, or remove the doctype definition, there is no space (as there should be. Why?</p> <p>Example HTML:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; body { margin:0 } #thediv { background-color:green } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="thediv"&gt; &lt;h1&gt;test&lt;/h1&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The problem is the space above the green div, remove the DOCTYPE and the space disappears, change the <code>&lt;h1&gt;</code> tag to <code>&lt;b&gt;</code> and the space also disappears. It happens with any doctype (XHTML/HTML, strict/transitional/etc)</p> <p>Happens in almost all browsers (Using <a href="http://browsershots.org" rel="nofollow noreferrer">http://browsershots.org</a>). Amusingly, the only browser that seems to display it correctly was Internet Explorer 6.0..</p>
[ { "answer_id": 236227, "author": "Phil Ross", "author_id": 5981, "author_profile": "https://Stackoverflow.com/users/5981", "pm_score": 4, "selected": true, "text": "#thediv{ background-color:green; border: 1px transparent solid; }\n" }, { "answer_id": 236678, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 0, "selected": false, "text": "body" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
236,211
<p>Is it good practice to let abstract classes define instance variables?</p> <pre><code>public abstract class ExternalScript extends Script { String source; public abstract void setSource(String file); public abstract String getSource(); } </code></pre> <p>The sub class, ExternalJavaScript.class, would then automatically get the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance. </p> <p>What is your advice?</p> <p>/Adam</p>
[ { "answer_id": 236229, "author": "Egwor", "author_id": 25308, "author_profile": "https://Stackoverflow.com/users/25308", "pm_score": 6, "selected": true, "text": "public abstract class ExternalScript extends Script {\n\n private String source;\n\n public void setSource(String file) {\n source = file;\n }\n\n public String getSource() {\n return source;\n }\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31518/" ]
236,220
<p>Is there a correct way in Windows Forms to flash a titlebar without having to drop to P/Invoking FlashWindow?</p> <p>I'm using .NET 2.0 for compatibility and size reasons, so maybe I just missed the method because it's in newer versions of the .NET framework.</p>
[ { "answer_id": 236247, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 4, "selected": true, "text": "FlashWindowEx" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6061/" ]
236,231
<p>How should I choose an IPv4 multicast address for my application's use? I may need more than one (a whole range perhaps ultimately) but just want to avoid conflicts with other applications.</p> <ul> <li>Packets will be entirely contained within an administrative domain, probably a LAN</li> <li>If several independent instances of my application are in use on the same network, they could each use their own multicast address - but if they don't, they will be able to coexist anyway, they'll just have a small amount of overhead ignoring each others' packets.</li> <li>My packets already contain a "magic number" to avoid problems</li> <li>I will be checking the originator address (which I know can be spoofed of course), TTL and other things to try to prevent unexpected packets mucking things up.</li> </ul> <p>Ideas please :)</p> <p>Currently I've just allocated an arbitrary one from the "local use" space, 239.255.42.99</p>
[ { "answer_id": 258126, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 5, "selected": false, "text": "http://www.iana.org/assignments/multicast-addresses" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13724/" ]
236,235
<p><em>(This question specifically in C#, but applies generally to .NET)</em> </p> <p>I have a largish application that has a fairly good design, and is broken into major sections over interfaces (this was done to assist parallel development).</p> <p>We now have a primary set of concrete classes that implement the required interfaces, but we also have additional sets of concrete classes for alternative situations and testing.</p> <p>At the moment we pull all these classes together at the top level in code:</p> <pre><code>IMyInterface xComponent = new ConcreteXComponent1(); </code></pre> <p>If I want to swap out components then I only have to change that line and recompile:</p> <pre><code>// IMyInterface xComponent = new ConcreteXComponent1(); IMyInterface xComponent = new ConcreteXComponentAlternative(); </code></pre> <p>That works great, but obviously requires a recompile -- I'd rather the concrete class was chosen using a value from a config file. </p> <p>What's the standard pattern for changing concrete classes using a configuration file? Is there standard library I can use that solves this problem for me?</p> <p>Thanks!</p>
[ { "answer_id": 236245, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "Activator.CreateInstance" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
236,236
<p>I have a select query that currently produces the following results: <BR></p> <pre><code>Description Code Price Product 1 A 5 Product 1 B 4 Product 1 C 2 </code></pre> <p>Using the following query: </p> <pre><code>SELECT DISTINCT np.Description, p.promotionalCode, p.Price FROM Price AS p INNER JOIN nProduct AS np ON p.nProduct = np.Id </code></pre> <p>I want to produce the following: </p> <pre><code>Description A B C Product 1 5 4 2 </code></pre>
[ { "answer_id": 236252, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 4, "selected": true, "text": "SELECT \n np.Id, \n np.Description, \n MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',\n MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',\n MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'\nFROM \n Price AS p \nINNER JOIN nProduct AS np ON p.nProduct = np.Id\nGROUP BY \n np.Id,\n np.Description\n" }, { "answer_id": 236453, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "CREATE TABLE Sales.[Order]\n (Customer varchar(8), Product varchar(5), Quantity int)\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,239
<p>I have an <em>SQLite</em> table that contains prices for various products. It's a snapshot table, so it contains the prices on 5 minute intervals. I would like to write a query that would return the difference in price from one row to the next on each item.</p> <p>The columns are id (auto inc), record_id (id of the product), price (price at that point in time), time (just seconds since epoch)</p> <p>I'm trying to return a 'difference' column that contains a value of difference between intervals.</p> <pre> Given the following id record_id price time 1 apple001 36.00 ... 67 apple001 37.87 ... 765 apple001 45.82 ... 892 apple001 26.76 ... I'd like it to return id record_id price time difference 1 apple001 36.00 ... 0 67 apple001 37.87 ... 1.87 765 apple001 45.82 ... 7.95 892 apple001 26.76 ... -19.06 </pre> <p>Is it possible with SQLite?</p> <p>Secondly, should it be possible - is there a way to limit it to the last 5 or so records?</p> <p>I'd appreciate any help, thanks.</p> <hr> <p>Just wanted to add a few things. I've found ways to do so in other databases, but I'm using XULRunner, thus SQLite. Which is why I'm working with it instead. </p> <p>The secondary question may need clarifying, I'm looking to order by the time and take and analyze the last 5 records. It's an issue I can tackle separately if need be.</p> <p>Here's a MySQL <a href="http://www.freeopenbook.com/mysqlcookbook/mysqlckbk-CHP-12-SECT-13.html" rel="noreferrer">solution</a>, kind of. It's the approach I'm heading towards, but the deal breaker is "If the table contains a sequence column but there are gaps, renumber it. If the table contains no such column, add one". By design this scenario has gaps as there is many records updated at once and won't be in order.</p>
[ { "answer_id": 236286, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "SELECT A.id, A.record_id, A.price, A.time, ISNULL(A.price - B.price, 0) AS difference\nFROM Table1 as A \n LEFT OUTER JOIN Table1 B ON A.record_id = B.record_id AND A.time - B.time = 5\n" }, { "answer_id": 61020620, "author": "Jeroen", "author_id": 7043928, "author_profile": "https://Stackoverflow.com/users/7043928", "pm_score": 4, "selected": false, "text": "sqlite> .mode columns\nsqlite> .headers on\nsqlite> CREATE TABLE data(id INT, record_id TEXT, price REAL);\nsqlite> INSERT INTO data VALUES(1,\"apple001\",36.00);\nsqlite> INSERT INTO data VALUES(67,\"apple001\",37.87);\nsqlite> INSERT INTO data VALUES(765,\"apple001\",45.82);\nsqlite> INSERT INTO data VALUES(892,\"apple001\",26.76);\nsqlite> SELECT id, record_id, price, (price - LAG(price, 1) OVER (ORDER BY id)) AS difference FROM data;\nid record_id price difference\n---------- ---------- ---------- ----------\n1 apple001 36.0 \n67 apple001 37.87 1.87 \n765 apple001 45.82 7.95 \n892 apple001 26.76 -19.06\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,279
<pre><code>&lt;?php function toconv(string) { $gogo = array("a" =&gt; "b","cd" =&gt; "e"); $string = str_replace( array_keys( $gogo ), array_values( $gogo ), $string ); return $string; } ?&gt; </code></pre> <p>How can I implement that in JavaScript?</p>
[ { "answer_id": 236287, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<script>\nfunction toconv(str) {\n replacements = ['b','e'];\n regexes = [/a/g,/cd/g];\n\n for (i=0; i < regexes.length; i++) {\n str = str.replace(regexes[i],replacements[i]);\n }\n return str;\n}\n\nalert(toconv('acdacd'));\nalert(toconv('foobar'));\n</script>\n" }, { "answer_id": 236370, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": true, "text": "<script type=\"text/javascript\">\nfunction toconv(string){\n var gogo = {\"a\":\"b\", \"cd\":\"e\"}, reg;\n for(x in gogo) {\n reg = new RegExp(x, \"g\");\n string.replace(x, gogo[x]);\n }\n return string;\n}\n</script>\n" }, { "answer_id": 33118570, "author": "alamin", "author_id": 4685044, "author_profile": "https://Stackoverflow.com/users/4685044", "pm_score": -1, "selected": false, "text": "if (preg_match('/0/', $check) || preg_match('/1/', $check) || preg_match('/2/', $check) || preg_match('/3/', $check) || preg_match('/4/', $check) || preg_match('/5/', $check) || preg_match('/6/', $check) || preg_match('/7/', $check) || preg_match('/8/', $check) || preg_match('/9/', $check))\n{\n exception(\"personal info not allowed\");\n redirect(base_url() . 'edit_profile');\n}\nelse if ((preg_match(\"~\\b@\\b~\",$check)) || (preg_match(\"~\\b.net\\b~\",$check)) || (preg_match(\"~\\b.com\\b~\",$check)) || (preg_match(\"~\\b@\\b~\",$check)) || (preg_match(\"~\\b.edu\\b~\",$check)) || (preg_match(\"~\\b.gov\\b~\",$check)))\n{\n exception(\"personal info not allowed\");\n redirect(base_url() . 'edit_profile');\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21559/" ]
236,283
<p>I am using the following function to load a PlayList of Songs from 'PlayListJSON.aspx' but somethings seems wrong,evrytime OnFailure is getting called, I am unable to debug it further. any help would be really gr8.</p> <pre><code>Player.prototype.loadPlaylist = function(playlistId, play) { req = new Ajax.Request('/PlaylistJSON.aspx?id=' + playlistId, { method: 'GET', onSuccess: function(transport, json) { eval(transport.responseText); player.setPlaylist(playlist.tracklist, playlist.title, playlistId); player.firstTrack(); if (play) player.playSong(); }, onFailure: function() { //error } }); } </code></pre>
[ { "answer_id": 236299, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 1, "selected": false, "text": "req = new Ajax.Request('/PlaylistJSON.aspx', \n { \n\n method: 'GET', \n parameters: {\n 'id': playlistId\n },\n onSuccess: function(transport,json){ \n\n eval(transport.responseText); \n\n player.setPlaylist(playlist.tracklist,playlist.title, playlistId);\n player.firstTrack();\n\n if (play)\n player.playSong(); \n\n },\n onFailure: function() {\n //error\n\n }\n });\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,290
<p>For example, say one was to include a 'delete' keyword in C# 4. Would it be possible to guarantee that you'd never have wild pointers, but still be able to rely on the garbage collecter, due to the reference-based system?</p> <p>The only way I could see it possibly happening is if instead of references to memory locations, a reference would be an index to a table of pointers to actual objects. However, I'm sure that there'd be some condition where that would break, and it'd be possible to break type safety/have dangling pointers.</p> <p>EDIT: I'm not talking about just .net. I was just using C# as an example.</p>
[ { "answer_id": 236304, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "obj1 = new instance;\nobj2 = obj1;\n\n// \n\ndelete obj2;\n// obj1 now references the twilightzone.\n" }, { "answer_id": 237165, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 0, "selected": false, "text": "String s = \"Here is a string.\"; \nString t = s;\nString u = s;\njunk( s );\n" }, { "answer_id": 8566198, "author": "Liran", "author_id": 2164233, "author_profile": "https://Stackoverflow.com/users/2164233", "pm_score": 0, "selected": false, "text": "Marshal" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18658/" ]
236,322
<p>I'm using Visual Studio icon library (VS2008ImageLibrary), there are some BMP files with a pink background. How can I make the pink background become transparent? What software can I use to do this? Any free one? </p> <p>Thanks</p>
[ { "answer_id": 21974614, "author": "Mamad Asgari", "author_id": 588149, "author_profile": "https://Stackoverflow.com/users/588149", "pm_score": 1, "selected": false, "text": "convert input.png -transparent magenta output.png\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,323
<p>I need to compare the integer part of two doubles for inequality and I'm currently doing this:</p> <pre><code>int iA = (int)dA; int iB = (int)dB; if( iA != iB ) { ... } </code></pre> <p>but I wonder if there's a better approach than this.</p> <p>Thanks.</p> <p>If I used Math.Truncate() instead of a cast to int, would it still be accurate to compare the two resulting double values for equality?</p> <p>About the hungarian notation comments:</p> <p>I never use HN myself, not at least in the way most of people do. But this is one of these rare cases where the semantic of a variable directly relates to its type. I could have chosen another syntax like A_As_Integer and B_As_NonInteger but what would have been the difference then?</p>
[ { "answer_id": 236333, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 1, "selected": false, "text": "if ( (int)dA != (int)dB ) {\n ...\n}\n" }, { "answer_id": 236340, "author": "biozinc", "author_id": 30698, "author_profile": "https://Stackoverflow.com/users/30698", "pm_score": 4, "selected": true, "text": "if (Math.Truncate(x) == Math.Truncate(y))\n" }, { "answer_id": 236410, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "double floatNumber;\n\nfloatNumber = 32.7865;\n// Displays 32 \nConsole.WriteLine(Math.Truncate(floatNumber));\n\nfloatNumber = -32.9012;\n// Displays -32 \nConsole.WriteLine(Math.Truncate(floatNumber));\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
236,335
<p>So, simple procedure, calculate a factorial number. Code is as follows.</p> <pre><code>int calcFactorial(int num) { int total = 1; if (num == 0) { return 0; } for (num; num &gt; 0; num--) { total *= num; } return total; } </code></pre> <p>Now, this works fine and dandy (There are certainly quicker and more elegant solutions, but this works for me) for most numbers. However when inputting larger numbers such as 250 it, to put it bluntly, craps out. Now, the first couple factorial "bits" for 250 are { 250, 62250, 15126750, 15438000, 3813186000 } for reference.</p> <p>My code spits out { 250, 62250, 15126750, 15438000, <strong>-481781296</strong> } which is obviously off. My first suspicion was perhaps that I had breached the limit of a 32 bit integer, but given that 2^32 is 4294967296 I don't think so. The only thing I can think of is perhaps that it breaches a <strong>signed</strong> 32-bit limit, but shouldn't it be able to think about this sort of thing? If being signed is the problem I can solve this by making the integer unsigned but this would only be a temporary solution, as the next iteration yields 938043756000 which is far above the 4294967296 limit.</p> <p>So, is my problem the signed limit? If so, what can I do to calculate large numbers (Though I've a "LargeInteger" class I made a while ago that may be suited!) without coming across this problem again?</p>
[ { "answer_id": 236352, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": "hex (3813186000) = E34899D0\nhex (-481781296) = FFFFFFFFE34899D0\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31389/" ]
236,349
<p>What's the best way to handle a visitor constructing their own URL and replacing what we expect to be an ID with anything they like?</p> <p>For example:</p> <p><a href="https://stackoverflow.com/questions/236349">ASP.Net MVC - handling bad URL parameters</a></p> <p>But the user could just as easily replace the URL with:</p> <p><a href="https://stackoverflow.com/questions/foo">https://stackoverflow.com/questions/foo</a></p> <p>I've thought of making every Controller Function parameter a <code>String</code>, and using <code>Integer.TryParse()</code> on them - if that passes then I have an ID and can continue, otherwise I can redirect the user to an Unknown / not-found or index View.</p> <p>Stack Overflow handles it nicely, and I'd like to too - how do you do it, or what would you suggest?</p>
[ { "answer_id": 237232, "author": "Schotime", "author_id": 29376, "author_profile": "https://Stackoverflow.com/users/29376", "pm_score": 3, "selected": false, "text": "public ActionResult Edit(int? id)\n{}\n" }, { "answer_id": 237390, "author": "Dan Atkinson", "author_id": 31532, "author_profile": "https://Stackoverflow.com/users/31532", "pm_score": 5, "selected": true, "text": "routes.MapRoute(\n \"Question\",\n \"questions/{questionID}\",\n new { controller = \"StackOverflow\", action = \"Question\" },\n new { questionID = @\"\\d+\" } //Regex constraint specifying that it must be a number.\n);\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
236,354
<p>I am a beginner in c++ and I have a small problem:</p> <p>my code displays a simple menu to the user providing three options:</p> <pre><code>cout &lt;&lt; "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout &lt;&lt; "\n &lt;r&gt; Give new coefficients"; cout &lt;&lt; "\n &lt;c&gt; Calculate equations solutions"; cout &lt;&lt; "\n &lt;t&gt; Terminate the program"; </code></pre> <p>What I want is now is that, when a user enters:</p> <ul> <li>aer ->invalid input entered, try again </li> <li>1 or any other number->invalid input entered, try again </li> <li>rt ->invalid input entered,try again (here the first character is correct but he entered 2 characters)</li> <li>cf ->invalid input entered, try again</li> </ul> <p>ONLY IF THE USER ENTERS CORRECTLY ONE OF THE 3 SIMPLE CHARACTERS (r,c,t NONSENSITIVE CASE) to do sth. Otherwise a massage for invalid input should be printed and then the main menu should appear again</p> <p>I tried this but it doesnt work:</p> <pre><code>char displayMainMenu() { char mainMenuChoice; cout &lt;&lt; "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout &lt;&lt; "\n &lt;r&gt; Give new coefficients"; cout &lt;&lt; "\n &lt;c&gt; Calculate equations solutions"; cout &lt;&lt; "\n &lt;t&gt; Terminate the program"; cout&lt;&lt;"Enter choice : "; cin&gt;&gt;mainMenuChoice; return mainMenuChoice; } int main() { bool done = false; while(!done) { char choice = displayMainMenu(); if( isalpha(choice) ) { switch(tolower(choice)) { case 'r': DoSTH1(); break; case 'c': DoSTH2(); break; case 't': DoSTH3(); break; default: cout&lt;&lt;"Invalid choice!\n"&lt;&lt;endl; } } } return 0; } </code></pre> <p>I hope u can help me</p> <p>ADDED: When i enter by mistake for example: cbbbbbb it takes it as if it was 'c'</p>
[ { "answer_id": 236366, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "cout<<\"Enter choice : \" << std::endl;\n // ^^^^^^^^^^^^^^^\n" }, { "answer_id": 236369, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": "if( isalpha(choice) )" }, { "answer_id": 236373, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 1, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\nchar displayMainMenu() {\n char mainMenuChoice;\n cout << \"\\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: \";\n cout << \"\\n <r> Give new coefficients\";\n cout << \"\\n <c> Calculate equations solutions\";\n cout << \"\\n <t> Terminate the program\";\n cout<<\"\\nEnter choice : \";\n cin>>mainMenuChoice;\n return mainMenuChoice;\n}\n\nint main() {\n bool done = false;\n while(!done) {\n char choice = displayMainMenu();\n\n if( isalpha(choice) ) {\n\n switch(tolower(choice))\n {\n case 'r':\n cout << \"got 'r'\\n\";\n break;\n case 'c':\n cout << \"got 'c'\\n\";\n break;\n case 't':\n cout << \"got 't'\\n\";\n done = true;\n break;\n default:\n cout<<\"Invalid choice!\\n\"<<endl;\n }\n }\n }\n return 0;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,359
<p>I know most of the ins and outs of Python's approach to private variables/members/functions/...</p> <p>However, I can't make my mind up on how to distinguish between methods for external use or subclassing use.</p> <p>Consider the following example:</p> <pre><code>class EventMixin(object): def subscribe(self, **kwargs): '''kwargs should be a dict of event -&gt; callable, to be specialized in the subclass''' def event(self, name, *args, **kwargs): ... def _somePrivateMethod(self): ... </code></pre> <p>In this example, I want to make it clear that subscribe is a method to be used by external users of the class/object, while event is a method that should not be called from the outside, but rather by subclass implementations.</p> <p>Right now, I consider both part of the public API, hence don't use any underscores. However, for this particular situation, it would feel cleaner to, for example, use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API. However, that would become unwieldy because then the internal API would need to be invoked as</p> <pre><code>self._EventMixin__somePrivateMethod() </code></pre> <p>So, what are your conventions, coding-wise, documentationwise, or otherwise ?</p>
[ { "answer_id": 236402, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "use no underscores for the external API,\none underscore for the subclassable API,\nand two underscores for the private/internal API\n" }, { "answer_id": 237976, "author": "mithrandi", "author_id": 31490, "author_profile": "https://Stackoverflow.com/users/31490", "pm_score": 2, "selected": false, "text": "EventMixin" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ]
236,362
<p>I have a web application that makes heavy use of the Session state to store information about the current user, their personal settings, record their session history and so on. </p> <p>I have found myself retrieving this session information in my business layer, like so:</p> <pre><code>((UserSession)HttpContext.Current.Session["UserSession"]).User.Info </code></pre> <p>This poses a problem - at some point in the future my application will have a Windows client which obviously cannot reference the web Session state. So I need a host or customized session class that I can reference in my business layer that is agnostic of whether the application is running on the web or desktop. Something like:</p> <pre><code>IHost.User.Info </code></pre> <p>Behind the scenes, the web implementation will obviously utilize the Session state to store information, but I need to hide this away from my business layer. Has anyone solved this problem or got any practival advice on how best to approach this?</p> <p>Help appreciated. </p>
[ { "answer_id": 236454, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": true, "text": "System.Web" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
236,376
<p>I remember reading somewhere that you can provide your own icons without having them pass them through the automatic gloss effect when compiling an iphone app, but I can't remember how to do it, and not sure where it was in the docs. Anyone here remembers?</p> <p>thanks!</p>
[ { "answer_id": 236446, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": " <key>UIPrerenderedIcon</key>\n <true/>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
236,381
<p>I have a web application that requires a server based component to periodically access POP3 email boxes and retrieve emails. The service then needs to process the emails which will involve:</p> <ul> <li>Validating the email against some business rules (does it contain a valid reference in the subject line, which user sent the mail, etc.)</li> <li>Analysing and saving any attachments to disk</li> <li>Take the email body and attachment details and create a new item in the database</li> <li>Or update an existing item where the reference matches the incoming email subject line</li> </ul> <p>What is the best way to approach this? I really don't want to have to write a POP3 client from scratch, but I need to be able to customize the processing of emails. Ideally I would be able to plug in some component that does the access and retrieval for me, returning arrays of attachments, body text, subject line, etc. ready for my processing...</p> <p><strong>[ UPDATE: Reviews ]</strong></p> <p>OK, so I have spent a fair amount of time looking into (mainly free) .NET POP3 libraries so I thought I'd provide a short review of some of those mentioned below and a few others:</p> <ul> <li><a href="http://weblogs.shockbyte.com.ar/rodolfof/archive/2008/07/07/pop3.net-library.aspx" rel="noreferrer">Pop3.net</a> - free - works OK, very basic in terms of functionality provided. This is pretty much just the POP3 commands and some base64 encoding, but it's very straight forward - probably a good introduction</li> <li><a href="http://www.componentsource.com/products/seekford-net-pop3-wizard/index.html" rel="noreferrer">Pop3 Wizard</a> - commercial / some open source code - couldn't get this to build, missing DLLs, I wouldn't bother with this </li> <li><a href="http://www.codeplex.com/csharpmail" rel="noreferrer">C#Mail</a> - free for personal use - works well, comes with Mime parser and SMTP client, however the comments are in Japanese (not a big deal) and it didn't work with SSL 'out of the box' - I had to change the SslStream constructor after which it worked no problem</li> <li><a href="http://sourceforge.net/projects/hpop/" rel="noreferrer">OpenPOP</a> - free - hasn't been updated for about 5 years so it's current state is .NET 1.0, doesn't support SSL but that was no problem to resolve - I just replaced the existing stream with an SslStream and it worked. Comes with Mime parser.</li> </ul> <p>Of the free libraries, I'd go for C#Mail or OpenPOP.</p> <p>I looked at a few commercial libraries: <a href="http://www.chilkatsoft.com/" rel="noreferrer">Chillkat</a>, <a href="http://www.rebex.net/" rel="noreferrer">Rebex</a>, <a href="http://remobjects.com/" rel="noreferrer">RemObjects</a>, <a href="http://tech.dimac.net/default2.asp?M=Products/MenuDOTNET.asp&amp;P=Products/JMaildotnet/start.htm" rel="noreferrer">JMail.net</a>. Based on features, price and impression of the company I would probably go for Rebex and may in the future if my requirements change or I run into production issues with either of C#Mail or OpenPOP.</p> <p>In case anyone's needs it, this is the replacement SslStream constructor that I used to enable SSL with C#Mail and OpenPOP:</p> <pre><code>SslStream stream = new SslStream(clientSocket.GetStream(), false, delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) { return true; }); </code></pre>
[ { "answer_id": 2856484, "author": "Pawel Lesnikowski", "author_id": 80894, "author_profile": "https://Stackoverflow.com/users/80894", "pm_score": 2, "selected": false, "text": "using(Pop3 pop3 = new Pop3())\n{\n pop3.Connect(\"mail.host.com\"); // Connect to server\n pop3.Login(\"user\", \"password\"); // Login\n\n foreach(string uid in pop3.GetAll())\n {\n IMail email = new MailBuilder()\n .CreateFromEml(pop3.GetMessageByUID(uid));\n\n Console.WriteLine(email.Subject);\n }\n pop3.Close(true); \n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
236,387
<p>I'm not sure if the title is very clear, but basically what I have to do is read a line of text from a file and split it up into 8 different string variables. Each line will have the same 8 chunks in the same order (title, author, price, etc). So for each line of text, I want to end up with 8 strings.</p> <p>The first problem is that the last two fields in the line may or may not be present, so I need to do something with stringTokenizer.hasMoreTokens, otherwise it will die messily when fields 7 and 8 are not present.</p> <p>I would ideally like to do it in one while of for loop, but I'm not sure how to tell that loop what the order of the fields is going to be so it can fill all 8 (or 6) strings correctly. Please tell me there's a better way that using 8 nested if statements! </p> <p>EDIT: The String.split solution seems definitely part of it, so I will use that instead of stringTokenizer. However, I'm still not sure what the best way of feeding the individual strings into the constructor. Would the best way be to have the class expecting an array, and then just do something like this in the constructor:</p> <pre><code>line[1] = isbn; line[2] = title; </code></pre>
[ { "answer_id": 236425, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": true, "text": "String[] tokens = line.split(\"#\");\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31429/" ]
236,406
<p>Is one more preferred, or performs better over the other?</p>
[ { "answer_id": 236411, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 8, "selected": true, "text": "is_int()" }, { "answer_id": 7439191, "author": "esd", "author_id": 947947, "author_profile": "https://Stackoverflow.com/users/947947", "pm_score": 2, "selected": false, "text": "foreach(range(-1000 , 1000)as $num){\n if(ctype_digit($num)){\n echo $num . \", \";\n } \n}\n" }, { "answer_id": 17124362, "author": "masakielastic", "author_id": 531320, "author_profile": "https://Stackoverflow.com/users/531320", "pm_score": 0, "selected": false, "text": "setlocale(LC_ALL, 'en_US.UTF-8');\nvar_dump(\n true === array_every(range(-1000, -1), 'ctype_digit_returns_false'),\n true === array_every(range(0, 47), 'ctype_digit_returns_false'),\n true === array_every(range(48, 57), 'ctype_digit_returns_true'),\n true === array_every(range(58, 255), 'ctype_digit_returns_false'),\n true === array_every(range(256, 1000), 'ctype_digit_returns_true')\n);\n\n// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/every\nfunction array_every(array $array, $callable)\n{\n $count = count($array);\n\n for ($i = 0; $i < $count; $i +=1) {\n\n if (!$callable($array[$i])) {\n\n return false;\n\n }\n\n }\n\n return true;\n}\n\nfunction ctype_digit_returns_true($v)\n{\n return true === ctype_digit($v);\n}\n\nfunction ctype_digit_returns_false($v)\n{\n return false === ctype_digit($v);\n}\n" }, { "answer_id": 37585691, "author": "Buksy", "author_id": 619616, "author_profile": "https://Stackoverflow.com/users/619616", "pm_score": 3, "selected": false, "text": "is_numeric" }, { "answer_id": 42679183, "author": "Nono", "author_id": 584262, "author_profile": "https://Stackoverflow.com/users/584262", "pm_score": 2, "selected": false, "text": "is_numeric:" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,407
<p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p> <ul> <li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li> <li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li> <li><p>How do you handle/prevent typing errors (typos)?</p></li> <li><p>Are UnitTest's used as a substitute for static type checking?</p></li> </ul> <p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
[ { "answer_id": 236445, "author": "rony l", "author_id": 16418, "author_profile": "https://Stackoverflow.com/users/16418", "pm_score": 5, "selected": false, "text": "__getattr__" }, { "answer_id": 236718, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": " >>> x= SomeClass()\n >>> dir(x)\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,412
<p>I have a web application that comprises the following:</p> <ul> <li>A web project (with a web.config file containing a connection string - but no data access code in the web project)</li> <li>A data access project that uses LINQ-SQL classes to provide entities to the web project UI (this project has a settings file and an app.config - both of which have connection strings)</li> </ul> <p>When I build and deploy, there is no settings file or app.config in the Bin directory with the data access .dll, but changing the connection string in the web.config file doesn't change the database accordingly - so the connection string must be compiled into the data access dll. </p> <p>What I need is one config file for my entire deployment - website, data access dlls, everything - that has one connection string which gets used. At the moment there appear to be multiple connection strings getting used or hardcoded all over the place. </p> <p>How do I best resolve this mess?</p> <p>Thanks for any help.</p>
[ { "answer_id": 236442, "author": "TGnat", "author_id": 25121, "author_profile": "https://Stackoverflow.com/users/25121", "pm_score": 2, "selected": false, "text": "<configSections>\n <sectionGroup name=\"applicationSettings\" type=\"System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" >\n <section name=\"YourAssembly.My.MySettings\" type=\"System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" />\n </sectionGroup></configSections>\n" }, { "answer_id": 236464, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 5, "selected": true, "text": "web.config" }, { "answer_id": 236808, "author": "flesh", "author_id": 27805, "author_profile": "https://Stackoverflow.com/users/27805", "pm_score": 2, "selected": false, "text": "_connectionString = ConfigurationManager.AppSettings[\"ConnectionString\"];\n" }, { "answer_id": 780592, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "namespace MyApplication {\n /// <summary>\n /// Summary description for MyDataContext\n /// </summary>\n /// \n public partial class MyDataContext\n {\n public MyDataContext() :\n base(global::System.Configuration.ConfigurationManager.ConnectionStrings[\"MyConnectionString\"].ConnectionString, mappingSource)\n {\n OnCreated();\n }\n }\n}\n" }, { "answer_id": 3486654, "author": "Seba Illingworth", "author_id": 93451, "author_profile": "https://Stackoverflow.com/users/93451", "pm_score": 2, "selected": false, "text": "using System.Configuration;\nnamespace MyApplication \n{\n partial void OnCreated()\n {\n // attempt to use named connection string from the calling config file\n var conn = ConfigurationManager.ConnectionStrings[\"MyConnectionString\"];\n if (conn != null) Connection.ConnectionString = conn.ConnectionString;\n }\n}\n" }, { "answer_id": 4310454, "author": "Joe Niland", "author_id": 366965, "author_profile": "https://Stackoverflow.com/users/366965", "pm_score": 0, "selected": false, "text": " Imports System.Configuration\n\nPublic Class CustomDataContextBase\n Inherits System.Data.Linq.DataContext\n Implements IDisposable\n\n Private Shared overrideConnectionString As String\n\n Public Shared ReadOnly Property CustomConnectionString As String\n Get\n If String.IsNullOrEmpty(overrideConnectionString) Then\n overrideConnectionString = ConfigurationManager.ConnectionStrings(\"MyAppConnectionString\").ConnectionString\n End If\n\n Return overrideConnectionString\n End Get\n End Property\n\n Public Sub New()\n MyBase.New(CustomConnectionString)\n End Sub\n\n Public Sub New(ByVal connectionString As String)\n MyBase.New(CustomConnectionString)\n End Sub\n\n Public Sub New(ByVal connectionString As String, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)\n MyBase.New(CustomConnectionString, mappingSource)\n End Sub\n\n Public Sub New(ByVal connection As IDbConnection, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)\n MyBase.New(CustomConnectionString, mappingSource)\n End Sub\n\nEnd Class\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
236,436
<p>I made previously a question: <a href="https://stackoverflow.com/questions/236354/error-handling-when-taking-user-input">error handling when taking user input</a></p> <p>and I made the suggested changes:</p> <pre><code>char displayMainMenu() { char mainMenuChoice; cout &lt;&lt; "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout &lt;&lt; "\n &lt;r&gt; Give new coefficients"; cout &lt;&lt; "\n &lt;c&gt; Calculate equations solutions"; cout &lt;&lt; "\n &lt;t&gt; Terminate the program"; cout&lt;&lt;"Enter choice : "; cin&gt;&gt;mainMenuChoice; return mainMenuChoice; } int main() { bool done = false; while(!done) { char choice = displayMainMenu(); switch(tolower(choice)) { case 'r': cout&lt;&lt;"Entered case 'r'"; break; case 'c': cout&lt;&lt;"Entered case 'c'"; break; case 't': cout&lt;&lt;"Entered case 't'"; break; default: cout&lt;&lt;"Invalid choice! Try again"&lt;&lt;endl; } } return 0; } </code></pre> <p>The new problem is that if the user enters by mistake lets say "ter" i get the following :( :</p> <pre><code>Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : ter Entered case 't' Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : Invalid choice! Try again Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : Invalid choice! Try again </code></pre> <p>How could I avoid this from happening??</p>
[ { "answer_id": 236461, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "displayMainMenu()" }, { "answer_id": 237022, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 1, "selected": false, "text": "string displayMainMenu()\n{\n string mainMenuChoice;\n cout << \"\\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: \"; \n cout << \"\\n <r> Give new coefficients\"; \n cout << \"\\n <c> Calculate equations solutions\"; \n cout << \"\\n <t> Terminate the program\";\n cout << \"\\nEnter choice : \";\n getline(cin, mainMenuChoice);\n return mainMenuChoice;\n}\n\nint main()\n{\n bool done = false;\n while(!done)\n {\n string choice = displayMainMenu();\n if (choice.size() > 1 || choice.size() < 0)\n cout<<\"Invalid choice! Try again\"<<endl;\n\n switch(tolower(choice[0]))\n {\n case 'r':\n cout<<\"Entered case 'r'\";\n break;\n case 'c':\n cout<<\"Entered case 'c'\";\n break; \n case 't':\n cout<<\"Entered case 't'\";\n break;\n default:\n cout<<\"Invalid choice! Try again\"<<endl; \n }\n }\n return 0;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,439
<p>Or is there a chance that the operation will fail?</p> <p>Thanks.</p> <p>I chose the wrong term and what I really meant was rounding to 0, not truncation.</p> <p>The point is, I need to compare the integer part of two doubles and I'm just casting them to int and then using ==, but, as someone pointed out in one of my earlier questions, this could throw an overflow exception if the double can't fit into the integer.</p> <p>So the question would be 'Is it correct to use the == operator to compare two doubles that have previously been rounded to 0, or should I stick to the casting to int method and catch a possible exception?</p>
[ { "answer_id": 236479, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "==" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
236,456
<p>In honor of the <a href="http://prize.hutter1.net/" rel="noreferrer">Hutter Prize</a>, what are the top algorithms (and a quick description of each) for text compression?</p> <p>Note: The intent of this question is to get a description of compression algorithms, not of compression programs.</p>
[ { "answer_id": 236477, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "DEFLATE" }, { "answer_id": 48366018, "author": "serv-inc", "author_id": 1587329, "author_profile": "https://Stackoverflow.com/users/1587329", "pm_score": 2, "selected": false, "text": "zpaq" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
236,463
<p>When I type the following code in Emacs ruby-mode, the "#{foo}" is fontified in a different color than the enclosing string. How do I do this in my own Emacs mode? I tried to decipher the ruby-mode source code but couldn't understand it in a reasonable amount of time.</p> <pre><code>"a #{foo} a" </code></pre>
[ { "answer_id": 236592, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 1, "selected": false, "text": "font-lock-syntactic-keywords" }, { "answer_id": 236601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "(define-derived-mode temp-mode fundamental-mode \"Temp\"\n \"Temporary major mode.\"\n (set (make-local-variable 'font-lock-defaults)\n '((temp-mode-font-lock-keywords) nil nil nil nil)))\n\n(defconst temp-mode-font-lock-keywords\n (list (list \"$[A-Za-z0-9]+\" 0 font-lock-variable-name-face t)))\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,493
<p>The Zend Framework coding standard mentions the following:</p> <blockquote> For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it prevents the accidental injection of trailing whitespace into the response. </blockquote> <ul> <li><a href="http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html" rel="noreferrer">Zend Framework coding standard: file formatting</a></li> </ul> <p>However I do remember hearing about an issue (with tooling or including maybe?) where files needed to have closing tag.</p> <p>Does anyone know of any issues (other than the developer issue of wanting symmetry) where you would need to have closing tags or are they generally a bad idea?</p>
[ { "answer_id": 245446, "author": "Bob Fanger", "author_id": 19165, "author_profile": "https://Stackoverflow.com/users/19165", "pm_score": 1, "selected": false, "text": "find . -name '*.php' | xargs cat | php -l\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4512/" ]
236,517
<p>Is there any way to make Visual Studio word-wrap at 80 characters? I'm using VS2008.</p> <p><a href="https://stackoverflow.com/questions/84209/vertical-line-after-a-certain-amount-characters-in-visual-studio">This post is loosely related.</a></p>
[ { "answer_id": 28883599, "author": "Cory Koch", "author_id": 1467005, "author_profile": "https://Stackoverflow.com/users/1467005", "pm_score": 5, "selected": false, "text": "Ctrl+E, Ctrl+W" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
236,530
<p>I'd like to do the same in C#. Is there anyway of using properties in C# with parameters in the same way I've done with the parameter 'Key' in this VB.NET example?</p> <blockquote> <pre><code>Private Shared m_Dictionary As IDictionary(Of String, Object) = New Dictionary(Of String, Object) </code></pre> </blockquote> <pre><code>Public Shared Property DictionaryElement(ByVal Key As String) As Object Get If m_Dictionary.ContainsKey(Key) Then Return m_Dictionary(Key) Else Return [String].Empty End If End Get Set(ByVal value As Object) If m_Dictionary.ContainsKey(Key) Then m_Dictionary(Key) = value Else m_Dictionary.Add(Key, value) End If End Set End Property </code></pre> <p>Thanks</p>
[ { "answer_id": 236539, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "public T this[string key] {\n get { return m_Dictionary[key]; }\n set { m_Dictionary[key] = value; }\n}\n" }, { "answer_id": 236548, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "AddOrUpdateKey" }, { "answer_id": 236860, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\n\npublic class Test\n{\n public FakeIndexedPropertyInCSharp DictionaryElement { get; set; }\n\n public Test()\n {\n DictionaryElement = new FakeIndexedPropertyInCSharp();\n }\n\n public class FakeIndexedPropertyInCSharp\n {\n private Dictionary<string, object> m_Dictionary = new Dictionary<string, object>();\n\n public object this[string index]\n {\n get \n {\n object result;\n return m_Dictionary.TryGetValue(index, out result) ? result : null;\n }\n set \n {\n m_Dictionary[index] = value; \n }\n }\n }\n\n\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Test t = new Test();\n t.DictionaryElement[\"hello\"] = \"world\";\n Console.WriteLine(t.DictionaryElement[\"hello\"]);\n }\n}\n" }, { "answer_id": 6313390, "author": "Mark Jones", "author_id": 703178, "author_profile": "https://Stackoverflow.com/users/703178", "pm_score": 2, "selected": false, "text": " // Generic, parameterized (indexed) \"property\" template\n public class Property<T>\n {\n // The internal property value\n private T PropVal = default(T);\n\n // The indexed property get/set accessor \n // (Property<T>[index] = newvalue; value = Property<T>[index];)\n public T this[object key]\n {\n get { return PropVal; } // Get the value\n set { PropVal = value; } // Set the value\n }\n }\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31434/" ]
236,533
<p>I want to be able to selectively copy a list of files and preserve their directory structure. The problem is that there are quite a few files that their path exceeds 256 character. How is this problem usually handled?</p> <p>Edit: I should make it clear that I only want to selectively copy files, not folders. I don't think robocopy can be efficiently used to copy an individual file and it's folder structure effectively.</p>
[ { "answer_id": 236536, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "subst" }, { "answer_id": 3320216, "author": "gonsalu", "author_id": 144399, "author_profile": "https://Stackoverflow.com/users/144399", "pm_score": 0, "selected": false, "text": "robocopy empty_dir base_nested_dir /purge\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469014/" ]
236,538
<p>How do I get the directory where the rakefile.rb is located?</p> <p>I want to use this as my root directory to locate everything off.</p>
[ { "answer_id": 236554, "author": "TonyLa", "author_id": 1295, "author_profile": "https://Stackoverflow.com/users/1295", "pm_score": 2, "selected": false, "text": " config.load_paths += %W( #{RAILS_ROOT}/extras )\n" }, { "answer_id": 236557, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 6, "selected": true, "text": "__FILE__" }, { "answer_id": 51484507, "author": "David Moles", "author_id": 27358, "author_profile": "https://Stackoverflow.com/users/27358", "pm_score": 2, "selected": false, "text": "__dir__" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11755/" ]
236,555
<p>I built an application which displays the records from database in the window and checks the the database for new records every couple of seconds. The problem is that the window blinks each time I check for new records and I want to fix it. I have tried to compare the old datatable with the new one and refresh only if they are different. Does anyone know what is the best practice for such cases? I tried to do it the following way but it doesn't work:</p> <pre><code>private bool GetBelongingMessages() { bool result = false; DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID); if(dtTemp != dtMessages) { dtMessages = dtTemp; result = true; } else { result = false; } return result; } </code></pre>
[ { "answer_id": 236577, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": true, "text": "//This assumes the datatables have the same schema...\n public bool DatatablesAreSame(DataTable t1, DataTable t2) { \n if (t1.Rows.Count != t2.Rows.Count)\n return false;\n\n foreach (DataColumn dc in t1.Columns) {\n for (int i = 0; i < t1.Rows.Count; i++) {\n if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {\n return false;\n }\n }\n }\n return true;\n }\n" }, { "answer_id": 236623, "author": "Niko Gamulin", "author_id": 22996, "author_profile": "https://Stackoverflow.com/users/22996", "pm_score": 0, "selected": false, "text": "for(int i = 0; i < t1.Rows.Count; i++)\n {\n if((string)t1.Rows[i][1] != (string)t2.Rows[i][1])\n return false;\n }\n" }, { "answer_id": 761872, "author": "FlyinFish", "author_id": 88376, "author_profile": "https://Stackoverflow.com/users/88376", "pm_score": 1, "selected": false, "text": "bool tablesAreIdentical = true;\n\n// loop through first table\nforeach (DataRow row in firstTable.Rows)\n{\n foundIdenticalRow = false;\n\n // loop through tempTable to find an identical row\n foreach (DataRow tempRow in tempTable.Rows)\n {\n allFieldsAreIdentical = true;\n\n // compare fields, if any fields are different move on to next row in tempTable\n for (int i = 0; i < row.ItemArray.Length && allFieldsAreIdentical; i++)\n {\n if (!row[i].Equals(tempRow[i]))\n {\n allFieldsAreIdentical = false;\n }\n }\n\n // if an identical row is found, remove this row from tempTable \n // (in case of duplicated row exist in firstTable, so tempTable needs\n // to have the same number of duplicated rows to be considered equivalent)\n // and move on to next row in firstTable\n if (allFieldsAreIdentical)\n {\n tempTable.Rows.Remove(tempRow);\n foundIdenticalRow = true;\n break;\n }\n }\n // if no identical row is found for current row in firstTable, \n // the two tables are different\n if (!foundIdenticalRow)\n {\n tablesAreIdentical = false;\n break;\n }\n}\n\nreturn tablesAreIdentical;\n" }, { "answer_id": 18525907, "author": "Ganesh Rana", "author_id": 2515476, "author_profile": "https://Stackoverflow.com/users/2515476", "pm_score": 0, "selected": false, "text": " public Boolean CompareDataTables(DataTable table1, DataTable table2)\n {\n bool flag = true;\n DataRow[] row3 = table2.Select();\n int i = 0;// row3.Length;\n if (table1.Rows.Count == table2.Rows.Count)\n {\n foreach (DataRow row1 in table1.Rows)\n {\n if (!row1.ItemArray.SequenceEqual(row3[i].ItemArray))\n {\n flag = false;\n break;\n }\n i++;\n }\n\n }\n else\n {\n flag = false;\n }\n return flag;\n }\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
236,575
<p>Given an EmployeeId, how can I construct a Linq to Sql query to find all of the ancestors of the employee? Each EmployeeId has an associated SupervisorId (see below).</p> <p>For example, a query of the ancestors for EmployeeId 6 (Frank Black) should return Jane Doe, Bob Smith, Joe Bloggs, and Head Honcho.</p> <p>If necessary, I can cache the list of all employees to improve performance.</p> <p><strong>UPDATE:</strong></p> <p>I've created the following crude method to accomplish the task. It traverses the employee.Supervisor relationship all the way to the root node. However, this will issue one database call for each employee. Anyone have a more succinct or more performant method? Thanks.</p> <pre><code>private List&lt;Employee&gt; GetAncestors(int EmployeeId) { List&lt;Employee&gt; emps = new List&lt;Employee&gt;(); using (L2STestDataContext dc = new L2STestDataContext()) { Employee emp = dc.Employees.FirstOrDefault(p =&gt; p.EmployeeId == EmployeeId); if (emp != null) { while (emp.Supervisor != null) { emps.Add(emp.Supervisor); emp = emp.Supervisor; } } } return emps; } </code></pre>
[ { "answer_id": 236577, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": true, "text": "//This assumes the datatables have the same schema...\n public bool DatatablesAreSame(DataTable t1, DataTable t2) { \n if (t1.Rows.Count != t2.Rows.Count)\n return false;\n\n foreach (DataColumn dc in t1.Columns) {\n for (int i = 0; i < t1.Rows.Count; i++) {\n if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {\n return false;\n }\n }\n }\n return true;\n }\n" }, { "answer_id": 236623, "author": "Niko Gamulin", "author_id": 22996, "author_profile": "https://Stackoverflow.com/users/22996", "pm_score": 0, "selected": false, "text": "for(int i = 0; i < t1.Rows.Count; i++)\n {\n if((string)t1.Rows[i][1] != (string)t2.Rows[i][1])\n return false;\n }\n" }, { "answer_id": 761872, "author": "FlyinFish", "author_id": 88376, "author_profile": "https://Stackoverflow.com/users/88376", "pm_score": 1, "selected": false, "text": "bool tablesAreIdentical = true;\n\n// loop through first table\nforeach (DataRow row in firstTable.Rows)\n{\n foundIdenticalRow = false;\n\n // loop through tempTable to find an identical row\n foreach (DataRow tempRow in tempTable.Rows)\n {\n allFieldsAreIdentical = true;\n\n // compare fields, if any fields are different move on to next row in tempTable\n for (int i = 0; i < row.ItemArray.Length && allFieldsAreIdentical; i++)\n {\n if (!row[i].Equals(tempRow[i]))\n {\n allFieldsAreIdentical = false;\n }\n }\n\n // if an identical row is found, remove this row from tempTable \n // (in case of duplicated row exist in firstTable, so tempTable needs\n // to have the same number of duplicated rows to be considered equivalent)\n // and move on to next row in firstTable\n if (allFieldsAreIdentical)\n {\n tempTable.Rows.Remove(tempRow);\n foundIdenticalRow = true;\n break;\n }\n }\n // if no identical row is found for current row in firstTable, \n // the two tables are different\n if (!foundIdenticalRow)\n {\n tablesAreIdentical = false;\n break;\n }\n}\n\nreturn tablesAreIdentical;\n" }, { "answer_id": 18525907, "author": "Ganesh Rana", "author_id": 2515476, "author_profile": "https://Stackoverflow.com/users/2515476", "pm_score": 0, "selected": false, "text": " public Boolean CompareDataTables(DataTable table1, DataTable table2)\n {\n bool flag = true;\n DataRow[] row3 = table2.Select();\n int i = 0;// row3.Length;\n if (table1.Rows.Count == table2.Rows.Count)\n {\n foreach (DataRow row1 in table1.Rows)\n {\n if (!row1.ItemArray.SequenceEqual(row3[i].ItemArray))\n {\n flag = false;\n break;\n }\n i++;\n }\n\n }\n else\n {\n flag = false;\n }\n return flag;\n }\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24358/" ]
236,593
<p>How to do svn update of multiple files located across different directories ? </p> <p>For committing multiple files from different directories, we can put them all up in a text file and give that file as an argument to svn commit and it will happily commit all those files. But <b>update</b> ?</p> <p><b>EDIT:</b> Mr. Fooz's answer is definitely an option whereby I can create a .bat or .sh file with all the svn updates. But I would like to know if there are any special arguments that svn provide that can be used instead of a file with loads of svn update commands in it. Please note that the file that is used by svn commit contains <i>only</i> the filenames and no svn commands. </p>
[ { "answer_id": 236626, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "svn update docs foo/bar/ /repos/bar\n" }, { "answer_id": 236992, "author": "rjray", "author_id": 6421, "author_profile": "https://Stackoverflow.com/users/6421", "pm_score": 4, "selected": true, "text": "svn update `cat list_of_files`\n" }, { "answer_id": 236999, "author": "mithrandi", "author_id": 31490, "author_profile": "https://Stackoverflow.com/users/31490", "pm_score": 3, "selected": false, "text": "svn changelist yourlist file1 file2 file3 ...\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27474/" ]
236,599
<p>I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates).</p> <p>How can I create a Unit Test to be sure that my object is safely serializable?</p>
[ { "answer_id": 236602, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 5, "selected": true, "text": "MyComplexObject dto = new MyComplexObject();\nMemoryStream mem = new MemoryStream();\nBinaryFormatter b = new BinaryFormatter();\ntry\n{\n b.Serialize(mem, dto);\n}\ncatch (Exception ex)\n{\n Assert.Fail(ex.Message);\n}\n" }, { "answer_id": 236698, "author": "GeverGever", "author_id": 31460, "author_profile": "https://Stackoverflow.com/users/31460", "pm_score": 6, "selected": false, "text": "public static Stream Serialize(object source)\n{\n IFormatter formatter = new BinaryFormatter();\n Stream stream = new MemoryStream();\n formatter.Serialize(stream, source);\n return stream;\n}\n\npublic static T Deserialize<T>(Stream stream)\n{\n IFormatter formatter = new BinaryFormatter();\n stream.Position = 0;\n return (T)formatter.Deserialize(stream);\n}\n\npublic static T Clone<T>(object source)\n{\n return Deserialize<T>(Serialize(source));\n}\n" }, { "answer_id": 4071843, "author": "Zaid Masud", "author_id": 374420, "author_profile": "https://Stackoverflow.com/users/374420", "pm_score": 2, "selected": false, "text": " private static void AssertThatTypeAndPropertiesAreSerializable(Type type)\n {\n // base case\n if (type.IsValueType || type == typeof(string)) return;\n\n Assert.IsTrue(type.IsSerializable, type + \" must be marked [Serializable]\");\n\n foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))\n {\n if (propertyInfo.PropertyType.IsGenericType)\n {\n foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())\n {\n if (genericArgument == type) continue; // base case for circularly referenced properties\n AssertThatTypeAndPropertiesAreSerializable(genericArgument);\n }\n }\n else if (propertyInfo.GetType() != type) // base case for circularly referenced properties\n AssertThatTypeAndPropertiesAreSerializable(propertyInfo.PropertyType);\n }\n }\n" }, { "answer_id": 4464479, "author": "erikkallen", "author_id": 47161, "author_profile": "https://Stackoverflow.com/users/47161", "pm_score": 1, "selected": false, "text": "[Serializable]\nclass Foo {\n public Bar MyBar { get; set; }\n}\n\n[Serializable]\nclass Bar {\n int x;\n}\n\nclass DerivedBar : Bar {\n}\n\npublic void TestSerializeFoo() {\n Serialize(new Foo()); // OK\n Serialize(new Foo() { MyBar = new Bar() }; // OK\n Serialize(new Foo() { MyBar = new DerivedBar() }; // Boom\n}\n" }, { "answer_id": 44877512, "author": "David Keaveny", "author_id": 319980, "author_profile": "https://Stackoverflow.com/users/319980", "pm_score": 2, "selected": false, "text": "theObject.Should().BeXmlSerializable();\ntheObject.Should().BeBinarySerializable();\ntheObject.Should().BeDataContractSerializable();\n\ntheObject.Should().BeBinarySerializable<MyClass>(\n options => options.Excluding(s => s.SomeNonSerializableProperty));\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21386/" ]
236,624
<p>For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?</p> <pre><code>&lt;div id='header-inner'&gt; &lt;div class='titlewrapper'&gt; &lt;h1 class='title'&gt; Some text I want to change &lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Thanks!</p>
[ { "answer_id": 236655, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 6, "selected": true, "text": "function findFirstDescendant(parent, tagname)\n{\n parent = document.getElementById(parent);\n var descendants = parent.getElementsByTagName(tagname);\n if ( descendants.length )\n return descendants[0];\n return null;\n}\n\nvar header = findFirstDescendant(\"header-inner\", \"h1\");\n" }, { "answer_id": 236659, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 3, "selected": false, "text": "var parent = document.getElementById('header-inner');\nvar element = parent.GetElementsByTagName('h1')[0];\n" }, { "answer_id": 236664, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 0, "selected": false, "text": "var nodes = document.getElementById(\"mydiv\")\n .getElementsByTagName(\"H1\");\n\nfor(i=0;i<nodes.length;i++)\n{\n if(nodes.item(i).getAttribute(\"class\") == \"myheader\")\n alert(nodes.item(i).innerHTML);\n} \n" }, { "answer_id": 236667, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 1, "selected": false, "text": "document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';" }, { "answer_id": 236671, "author": "RogueOne", "author_id": 31019, "author_profile": "https://Stackoverflow.com/users/31019", "pm_score": 1, "selected": false, "text": "obj.childNodes" }, { "answer_id": 236682, "author": "patmortech", "author_id": 19090, "author_profile": "https://Stackoverflow.com/users/19090", "pm_score": 3, "selected": false, "text": "var element = $('#header-inner h1');\n" }, { "answer_id": 72916985, "author": "Heretic Monkey", "author_id": 215552, "author_profile": "https://Stackoverflow.com/users/215552", "pm_score": 2, "selected": false, "text": "querySelector" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311500/" ]
236,629
<p>I may be in the minority here, but I very much enjoy <a href="https://perldoc.perl.org/perlform" rel="nofollow noreferrer">Perl's formats</a>. I especially like being able to wrap a long piece of text within a column (&quot;~~ ^&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot; type stuff). Are there any other programming languages that have similar features, or libraries that implement similar features? I am especially interested in any libraries that implement something similar for Ruby, but I'm also curious about any other options.</p>
[ { "answer_id": 236651, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 2, "selected": false, "text": "(format ...)" }, { "answer_id": 236654, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": true, "text": "require \"formatr\"\ninclude FormatR\n\ntop_ex = <<DOT\n Piggy Locations for @<< @#, @###\n month, day, year\n\nNumber: location toe size\n-------------------------------------------\nDOT\n\nex = <<TOD\n@) @<<<<<<<<<<<<<<<< @#.##\nnum, location, toe_size\nTOD\n\nbody_fmt = Format.new (top_ex, ex)\n\nbody_fmt.setPageLength(10)\nnum = 1\n\nmonth = \"Sep\"\nday = 18\nyear = 2001\n[\"Market\", \"Home\", \"Eating Roast Beef\", \"Having None\", \"On the way home\"].each {|location|\n toe_size = (num * 3.5)\n body_fmt.printFormat(binding)\n num += 1\n}\n" }, { "answer_id": 237031, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 4, "selected": false, "text": "Perl6::Form" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5922/" ]
236,630
<p>I have a web page that displays a long line graph inside a div with overflow-x: scroll. This works well as a web page allowing the use to scroll back and forward through the graph.</p> <p>However, when printing the page the scroll position is reset to zero. Is there a way to overcome this?</p>
[ { "answer_id": 236641, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 2, "selected": false, "text": "<link rel=\"stylesheet\" type=\"text/css” href=\"sheet.css\" media=\"print\" />\n" }, { "answer_id": 236690, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 0, "selected": false, "text": "overflow:hidden" }, { "answer_id": 236862, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 2, "selected": true, "text": "style=\"left: -293px; overflow: hidden;\"" }, { "answer_id": 39473143, "author": "FlorianB", "author_id": 3105222, "author_profile": "https://Stackoverflow.com/users/3105222", "pm_score": 0, "selected": false, "text": "<html>\n<head>\n<style>\n#wrapper {\n width:800px;\n overflow-x:scroll;\n}\n#content {\n width:2000px;\n border:2px solid red;\n}\n@media print { /* This overwrites the css when printing */\n #wrapper {\n overflow-x:hidden;\n }\n}\n</style>\n</head>\n<body>\n<a href=\"#\" onclick=\"printGo()\">Print</a><br>\n<a href=\"#\" onclick=\"printDone()\">I'm done printing!</a>\n<div id=wrapper>\n <div id=content>\n Hello this is my content.\n </div>\n</div>\n<script>\nvar wrapper = document.getElementById('wrapper');\nvar content = document.getElementById('content');\nvar scrollPos;\nfunction printGo(){\n scrollPos = wrapper.scrollLeft; // Save scroll position\n wrapper.scrollLeft = 0;\n wrapper.style.overflowX = 'hidden'; // Optional since css does it\n content.style.marginLeft = -scrollPos+'px'; // Put it as a negative margin of child instead\n window.print();\n}\nfunction printDone(){\n wrapper.scrollLeft = scrollPos; // Restore scroll position\n wrapper.style.overflowX = 'scroll'; // Optional since css does it\n content.style.marginLeft = '';\n}\n</script>\n</body></html>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7011/" ]
236,632
<p>Please help me with a sanity check. Assuming a many-to-many relationship:</p> <p><a href="http://www.codingthewheel.com/pics/many_to_many.gif" rel="nofollow noreferrer">Post, PostTagAssoc, Tag http://www.codingthewheel.com/pics/many_to_many.gif</a></p> <p>What's the most succinct way (using LINQ to SQL) to get a result set showing, for <strong>each</strong> tag (or post), the aggregate number of posts (or tags) assigned to it?</p> <p>Thanks!</p>
[ { "answer_id": 236680, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": " from pta in db.PostTagAssoc\n group pta by pta.PostID into t\n select new {PostID = t.Key, TagCount=t.Count()}\n" }, { "answer_id": 625608, "author": "netterdotter", "author_id": 59284, "author_profile": "https://Stackoverflow.com/users/59284", "pm_score": 0, "selected": false, "text": "from p in db.Post\nselect new {PostID = p.ID, TagCount = t.PostTagAssoc.Count}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
236,644
<p>I created the setup project for the application and I can see that the later modifications of the configuration file (Application.exe.config) don't affect the application execution.</p> <p>I am developing an application with the database file included and I want to enable users to move the database file and modify connection strings.</p> <p>Does anyone know what's the best practice for the deployment of the application with the database file?</p>
[ { "answer_id": 236822, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 3, "selected": true, "text": " <connectionStrings>\n <add name=\"YourApp.Properties.Settings.DatabaseConnectionString\"\n connectionString=\"Data Source=localhost;Initial Catalog=xxx;Integrated Security=True;\"\n providerName=\"System.Data.SqlClient\" />\n </connectionStrings>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
236,668
<p>I have been slowly learning SQL the last few weeks. I've picked up all of the relational algebra and the basics of how relational databases work. What I'm trying to do now is learn how it's implemented.</p> <p>A stumbling block I've come across in this, is foreign keys in MySQL. I can't seem to find much about the other than that they exist in the <a href="http://en.wikipedia.org/wiki/InnoDB" rel="noreferrer">InnoDB</a> storage schema that MySQL has.</p> <p>What is a simple example of foreign keys implemented in MySQL?</p> <p>Here's part of a schema I wrote that doesn't seem to be working if you would rather point out my flaw than show me a working example.</p> <pre><code>CREATE TABLE `posts` ( `pID` bigint(20) NOT NULL auto_increment, `content` text NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `uID` bigint(20) NOT NULL, `wikiptr` bigint(20) default NULL, `cID` bigint(20) NOT NULL, PRIMARY KEY (`pID`), Foreign Key(`cID`) references categories, Foreign Key(`uID`) references users ) ENGINE=InnoDB; </code></pre>
[ { "answer_id": 236677, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 3, "selected": false, "text": "CREATE TABLE parent (\n id INT NOT NULL,\n PRIMARY KEY (id)\n) ENGINE=INNODB;\n\nCREATE TABLE child (\n id INT, \n parent_id INT,\n INDEX par_ind (parent_id),\n FOREIGN KEY (parent_id) REFERENCES parent(id)\n ON DELETE CASCADE\n) ENGINE=INNODB;\n" }, { "answer_id": 236684, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 6, "selected": true, "text": "CREATE TABLE `posts` (\n`pID` bigint(20) NOT NULL auto_increment,\n`content` text NOT NULL,\n`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n`uID` bigint(20) NOT NULL,\n`wikiptr` bigint(20) default NULL,\n`cID` bigint(20) NOT NULL,\nPRIMARY KEY (`pID`),\nForeign Key(`cID`) references categories(`cID`),\nForeign Key(`uID`) references users(`uID`)\n) ENGINE=InnoDB;\n" }, { "answer_id": 236693, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "SHOW CREATE TABLE posts;\n" }, { "answer_id": 236931, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": false, "text": "select *\nfrom \n Students\ninner join\n StudentCourses\non Students.StudentId = StudentCourses.StudentId\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1063/" ]
236,675
<p>How to cancel a keypress event in a textbox after pressing the return key.</p>
[ { "answer_id": 236687, "author": "lacop", "author_id": 894, "author_profile": "https://Stackoverflow.com/users/894", "pm_score": 3, "selected": true, "text": "private void keypressed(Object o, KeyPressEventArgs e)\n{\n if (e.KeyChar == (char)Keys.Return)\n {\n e.Handled = true;\n }\n}\n" }, { "answer_id": 236694, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": "private void textBox1_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.KeyCode == Keys.Enter)\n {\n e.SuppressKeyPress = true;\n }\n }\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26087/" ]
236,676
<p>I have an IList of type Breadcrumb which is just a lightweight class that has NavigationTitle, NavigationUrl and IsCurrent properties. It is cached on the webserver. I have a method that builds out the current breadcrumb trail up until the first Breadcrumb that has IsCurrent set to true... using the code below. Its very ugly and definitely a quick dirtbag willie solution, but I was curious, can this be easily refactored into LINQ? </p> <pre><code>IList&lt;Breadcrumb&gt; crumbs = new List&lt;Breadcrumb&gt;(); bool foundCurrent = false; for (int a = 0; a &lt; cachedCrumbs.Count; a++) { crumbs.Add(crumbs[a]); if (foundCurrent) { break; } foundCurrent = (crumbs[a + 1] != null &amp;&amp; ((Breadcrumb)crumbs[a + 1]).IsCurrent); } </code></pre>
[ { "answer_id": 236701, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "IList<Breadcrumb> crumbs = new List<Breadcrumb>();\nfor (int a = 0; a < cachedCrumbs.Count; a++)\n{\n crumbs.Add(cachedCrumbs[a]);\n if (cachedCrumbs[a] != null && cachedCrumbs[a].IsCurrent)\n {\n break;\n }\n}\n" }, { "answer_id": 236705, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "bool foundCurrent = false;\n\nvar crumbs = cachedCrumbs.TakeWhile(crumb => !foundCurrent)\n .Select(crumb => { \n foundCurrent = crumb == null || !crumb.IsCurrent; \n return crumb; });\n" }, { "answer_id": 236707, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "IList<Breadcrumb> crumbs = new List<BreadCrumb>();\nforeach (Breadcrumb crumb in cachedCrumbs)\n{\n crumbs.Add(crumb);\n if (crumb != null && crumb.IsCurrent)\n {\n break;\n }\n}\n" }, { "answer_id": 236739, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "// find the current item\nvar currentItem = cachedCrumbs.First(c => c.IsCurrent);\nvar currentIdx = cachedCrumbs.IndexOf(currentItem);\n\n// get all items upto current item\nvar crumbs = cachedCrumbs.Take(currentIdx + 2);\n" }, { "answer_id": 236874, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "public static IEnumerable<T> TakeUpto<T>(this IEnumerable<T> theList, Func<T, bool> predicate)\n{\n foreach (T element in theList)\n {\n yield return element;\n if (predicate(element))\n {\n break;\n }\n }\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
236,692
<p>I have a device that supports 4-color graphics (much like CGA in the old days).</p> <p>I wanted to use <a href="http://www.pythonware.com/products/pil/" rel="noreferrer">PIL</a> to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people have tried to do so and failed.</p> <p>A simple python example would be much appreciated!</p> <p>Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)</p>
[ { "answer_id": 237193, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": true, "text": "import Image\n\ndef estimate_color(c, bit, c_error):\n c_new= c - c_error\n if c_new > 127:\n c_bit= bit\n c_error= 255 - c_new\n else:\n c_bit= 0\n c_error= -c_new\n return c_bit, c_error\n\ndef image2cga(im):\n \"Produce a sequence of CGA pixels from image im\"\n im_width= im.size[0]\n for index, (r, g, b) in enumerate(im.getdata()):\n if index % im_width == 0: # start of a line\n r_error= g_error= 0\n r_bit, r_error= estimate_color(r, 1, r_error)\n g_bit, g_error= estimate_color(g, 2, g_error)\n yield r_bit|g_bit\n\ndef cvt2cga(imgfn):\n \"Convert an RGB image to (K, R, G, Y) CGA image\"\n inp_im= Image.open(imgfn) # assume it's RGB\n out_im= Image.new(\"P\", inp_im.size, None)\n out_im.putpalette( (\n 0, 0, 0,\n 255, 0, 0,\n 0, 255, 0,\n 255, 255, 0,\n ) )\n out_im.putdata(list(image2cga(inp_im)))\n return out_im\n\nif __name__ == \"__main__\":\n import sys, os\n\n for imgfn in sys.argv[1:]:\n im= cvt2cga(imgfn)\n dirname, filename= os.path.split(imgfn)\n name, ext= os.path.splitext(filename)\n newpathname= os.path.join(dirname, \"cga-%s.png\" % name)\n im.save(newpathname)\n" }, { "answer_id": 237747, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 3, "selected": false, "text": "import sys\n\nimport PIL\nimport Image\n\nPALETTE = [\n 0, 0, 0, # black, 00\n 0, 255, 0, # green, 01\n 255, 0, 0, # red, 10\n 255, 255, 0, # yellow, 11\n] + [0, ] * 252 * 3\n\n# a palette image to use for quant\npimage = Image.new(\"P\", (1, 1), 0)\npimage.putpalette(PALETTE)\n\n# open the source image\nimage = Image.open(sys.argv[1])\nimage = image.convert(\"RGB\")\n\n# quantize it using our palette image\nimagep = image.quantize(palette=pimage)\n\n# save\nimagep.save('/tmp/cga.png')\n" }, { "answer_id": 44673651, "author": "Lady_F", "author_id": 8193638, "author_profile": "https://Stackoverflow.com/users/8193638", "pm_score": 1, "selected": false, "text": "import sys\nimport PIL\nfrom PIL import Image\n\ndef quantizetopalette(silf, palette, dither=False):\n \"\"\"Convert an RGB or L mode image to use a given P image's palette.\"\"\"\n\n silf.load()\n\n # use palette from reference image\n palette.load()\n if palette.mode != \"P\":\n raise ValueError(\"bad mode for palette image\")\n if silf.mode != \"RGB\" and silf.mode != \"L\":\n raise ValueError(\n \"only RGB or L mode images can be quantized to a palette\"\n )\n im = silf.im.convert(\"P\", 1 if dither else 0, palette.im)\n # the 0 above means turn OFF dithering\n return silf._makeself(im)\n\nif __name__ == \"__main__\":\n import sys, os\n\nfor imgfn in sys.argv[1:]:\n palettedata = [ 0, 0, 0, 0, 255, 0, 255, 0, 0, 255, 255, 0,] \n palimage = Image.new('P', (16, 16))\n palimage.putpalette(palettedata + [0, ] * 252 * 3)\n oldimage = Image.open(sys.argv[1])\n newimage = quantizetopalette(oldimage, palimage, dither=False)\n dirname, filename= os.path.split(imgfn)\n name, ext= os.path.splitext(filename)\n newpathname= os.path.join(dirname, \"cga-%s.png\" % name)\n newimage.save(newpathname)\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ]
236,713
<p>Please help, I am stuck here ---</p> <pre><code>irb&gt; a = "line of text\n line two\n line three" irb&gt; system("cat &gt; test_file &lt;&lt; #{a}") cat: of: No such file or directory cat: text: No such file or directory =&gt; false </code></pre>
[ { "answer_id": 236727, "author": "Ivan", "author_id": 16957, "author_profile": "https://Stackoverflow.com/users/16957", "pm_score": 3, "selected": true, "text": "system(\"cat > test_file << \\\"#{a}\\\"\")\n" }, { "answer_id": 236729, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "File.open(\"testfile\", \"w\") do |io| io.print a done\n" }, { "answer_id": 236757, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "IO.popen(\"cat > foo\", \"w\") do\n |f|\n f.write(\"line1\\nline2\\n\")\nend\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31347/" ]
236,715
<p>I am using Ruby on Rails.</p> <p>I want to create a filter field on a page such that whenever the input field's value changes I filter a list shown below via ajax. (Exaclty like the Users search works in Stackoverflow)</p> <p>For now, I made it run with a form_remote_tag containing a text_field_tag and a submit_tag, and it filters my list when I push the submit button. I would like to remove the submit button and execute the filtering every time the value of the text input changes. How can I trigger a form submit every time the text in an input field changes?</p> <p>I tried inside my form</p> <p><code>&lt;%= text_field_tag (:filter), "" , :onchange =&gt; "alert ('This is a Javascript Alert')" %&gt;</code></p> <p>just to get the onchange event, but somehow not even this alert appears...</p>
[ { "answer_id": 236721, "author": "Ricardo Acras", "author_id": 19224, "author_profile": "https://Stackoverflow.com/users/19224", "pm_score": 3, "selected": true, "text": "<%= text_field_tag 'filter' %>\n<%= observe_field 'filter', \n :url => {:controller => 'your_controller', :action => 'filter'},\n :frequency => 1.2,\n :update => 'results',\n :with => \"'typed_filter=' + $('filter').value\" %>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534/" ]
236,737
<p>Perl and PHP do this with backticks. For example,</p> <pre><code>$output = `ls`; </code></pre> <p>Returns a directory listing. A similar function, <code>system("foo")</code>, returns the operating system return code for the given command foo. I'm talking about a variant that returns whatever foo prints to stdout.</p> <p>How do other languages do this? Is there a canonical name for this function? (I'm going with "backtick"; though maybe I could coin "syslurp".)</p>
[ { "answer_id": 236740, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 3, "selected": true, "text": "$output = `foo`;\n" }, { "answer_id": 236742, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 2, "selected": false, "text": "output = Import[\"!foo\", \"Text\"];\n" }, { "answer_id": 236754, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 4, "selected": false, "text": "import os\noutput = os.popen(\"foo\").read()\n" }, { "answer_id": 236764, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "OUTPUT=`ls`\n" }, { "answer_id": 236769, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 3, "selected": false, "text": "puts `ls`;\nputs %x{ls};\n" }, { "answer_id": 236772, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "$output = `ls`;\n" }, { "answer_id": 236781, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "$output = qx/ls/;\n" }, { "answer_id": 236787, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "os:cmd(\"ls\")\n" }, { "answer_id": 236791, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "$output = <<`END`;\nls\nEND\n" }, { "answer_id": 236873, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "E:\\classes\\com\\javaworld\\jpitfalls\\article2>java GoodWindowsExec \"dir *.java\"\nExecuting cmd.exe /C dir *.java\n...\n" }, { "answer_id": 236909, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "from subprocess import check_output as qx\n\noutput = qx(['ls', '-lt'])\n" }, { "answer_id": 236997, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 2, "selected": false, "text": "open my $pipe, 'ps |';\nmy @output = < $pipe >;\nsay @output;\n" }, { "answer_id": 241436, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "glibc" }, { "answer_id": 241445, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "output=:2!:0'ls'\n" }, { "answer_id": 241495, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "import Control.Exception\nimport System.IO\nimport System.Process\nmain = bracket (runInteractiveCommand \"ls\") close $ \\(_, hOut, _, _) -> do\n output <- hGetContents hOut\n putStr output\n where close (hIn, hOut, hErr, pid) =\n mapM_ hClose [hIn, hOut, hErr] >> waitForProcess pid\n" }, { "answer_id": 251792, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 2, "selected": false, "text": "while((String s = stdout.readLine())!=null){...}" }, { "answer_id": 335221, "author": "Dave Ray", "author_id": 40310, "author_profile": "https://Stackoverflow.com/users/40310", "pm_score": 2, "selected": false, "text": "set result [exec ls]\n" }, { "answer_id": 372423, "author": "derobert", "author_id": 27727, "author_profile": "https://Stackoverflow.com/users/27727", "pm_score": 2, "selected": false, "text": "use IPC::Run3\n\nmy ($stdout, $stderr);\nrun3 ['ls'], undef, \\$stdout, \\$stderr\n or die \"ls failed\";\n" }, { "answer_id": 373080, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 2, "selected": false, "text": "#include <stdio.h> \n\nFILE* stream = popen(\"/path/to/program\", \"rw\");\nfprintf(stream, \"foo\\n\"); /* Use like you would a file stream. */\nfclose(stream);\n" }, { "answer_id": 373223, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "Process p = Runtime.getRuntime().exec( \"cmd /c \" + command );\nInputStream i = p.getInputStream();\nStringBuilder sb = new StringBuilder();\nfor( int c = 0 ; ( c = i.read() ) > -1 ; ) {\n sb.append( ( char ) c );\n}\n" }, { "answer_id": 388176, "author": "Gant", "author_id": 12460, "author_profile": "https://Stackoverflow.com/users/12460", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Diagnostics;\n\nnamespace TestConsole\n{\n class Program\n {\n static void Main(string[] args)\n {\n Process p = new Process();\n\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.CreateNoWindow = true;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.RedirectStandardError = true;\n p.StartInfo.FileName = \"cmd\";\n p.StartInfo.Arguments = \"/c dir\";\n p.Start();\n\n string res = p.StandardOutput.ReadToEnd();\n Console.WriteLine(res);\n }\n\n }\n}\n" }, { "answer_id": 388218, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 2, "selected": false, "text": "stream := open(\"ls\", \"p\")\nwhile line := read(stream) do { \n # stuff\n}\n" }, { "answer_id": 432847, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Diagnostics;\n\nclass Program\n{\n static void Main()\n {\n var info = new ProcessStartInfo(\"cmd\", \"/c dir\") { UseShellExecute = false, RedirectStandardOutput = true };\n Console.WriteLine(Process.Start(info).StandardOutput.ReadToEnd());\n }\n}\n" }, { "answer_id": 1371936, "author": "Donnie Cameron", "author_id": 160976, "author_profile": "https://Stackoverflow.com/users/160976", "pm_score": 2, "selected": false, "text": "(defun execute (program parameters &optional (buffer-size 1000))\n (let ((proc (sb-ext:run-program program parameters :search t :output :stream))\n (output (make-array buffer-size :adjustable t :fill-pointer t \n :element-type 'character)))\n (with-open-stream (stream (sb-ext:process-output proc))\n (setf (fill-pointer output) (read-sequence output stream)))\n output))\n" }, { "answer_id": 1371990, "author": "Alexander Gladysh", "author_id": 6236, "author_profile": "https://Stackoverflow.com/users/6236", "pm_score": 2, "selected": false, "text": " foo = io.popen(\"ls\"):read(\"*a\")\n" }, { "answer_id": 1372559, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 2, "selected": false, "text": "(with-output-to-string (stream)\n (run-program \"ls\" '(\"-l\") :output stream))\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]