qid
int64 4
19.1M
| 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 < 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 private string Works()\n{\n var closure = new Closure();\n\n closure.files = new string[3];\n closure.files[0] = \"notfoo\";\n closure.files[1] = \"bar\";\n closure.files[2] = \"notbaz\";\n\n var arrayToSearch = new string[] { \"foo\", \"bar\", \"baz\" };\n\n //this works, because the predicates are being executed during the loop\n for (closure.i = 0; closure.i < closure.files.Length; closure.i++)\n {\n if (Array.Exists(arrayToSearch, closure.YourAnonymousMethod))\n return closure.files[closure.i];\n }\n\n return null;\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 def index():\n session.c=session.c+1 if session.c else 1\n return dict(counter=session.c)\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 def index():\n session.c=session.c+1 if session.c else 1\n return dict(counter=session.c)\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 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 ^\\s*($|#|\\w+\\s*=|(\\*(?:\\/\\d+)?|(?:[0-5]?\\d)(?:-(?:[0-5]?\\d)(?:\\/\\d+)?)?(?:,(?:[0-5]?\\d)(?:-(?:[0-5]?\\d)(?:\\/\\d+)?)?)*)\\s+(\\*(?:\\/\\d+)?|(?:[01]?\\d|2[0-3])(?:-(?:[01]?\\d|2[0-3])(?:\\/\\d+)?)?(?:,(?:[01]?\\d|2[0-3])(?:-(?:[01]?\\d|2[0-3])(?:\\/\\d+)?)?)*)\\s+(\\*(?:\\/\\d+)?|(?:0?[1-9]|[12]\\d|3[01])(?:-(?:0?[1-9]|[12]\\d|3[01])(?:\\/\\d+)?)?(?:,(?:0?[1-9]|[12]\\d|3[01])(?:-(?:0?[1-9]|[12]\\d|3[01])(?:\\/\\d+)?)?)*)\\s+(\\*(?:\\/\\d+)?|(?:[1-9]|1[012])(?:-(?:[1-9]|1[012])(?:\\/\\d+)?)?(?:,(?:[1-9]|1[012])(?:-(?:[1-9]|1[012])(?:\\/\\d+)?)?)*|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\s+(\\*(?:\\/\\d+)?|(?:[0-6])(?:-(?:[0-6])(?:\\/\\d+)?)?(?:,(?:[0-6])(?:-(?:[0-6])(?:\\/\\d+)?)?)*|mon|tue|wed|thu|fri|sat|sun)\\s+|(@reboot|@yearly|@annually|@monthly|@weekly|@daily|@midnight|@hourly)\\s+)([^\\s]+)\\s+(.*)$\n public static String buildRegex(){\n // numbers intervals and regex\n Map<String, String> numbers = new HashMap<String, String>();\n numbers.put(\"min\", \"[0-5]?\\\\d\");\n numbers.put(\"hour\", \"[01]?\\\\d|2[0-3]\");\n numbers.put(\"day\", \"0?[1-9]|[12]\\\\d|3[01]\");\n numbers.put(\"month\", \"[1-9]|1[012]\");\n numbers.put(\"dow\", \"[0-6]\");\n\n Map<String, String> field_re = new HashMap<String, String>();\n\n // expand regex to contain different time specifiers\n for(String field : numbers.keySet()){\n String number = numbers.get(field);\n String range = \"(?:\"+number+\")(?:-(?:\"+number+\")(?:\\\\/\\\\d+)?)?\";\n field_re.put(field, \"\\\\*(?:\\\\/\\\\d+)?|\"+range+\"(?:,\"+range+\")*\");\n }\n\n // add string specifiers\n String monthRE = field_re.get(\"month\");\n monthRE = monthRE + \"|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec\";\n field_re.put(\"month\", monthRE);\n\n String dowRE = field_re.get(\"dow\");\n dowRE = dowRE + \"|mon|tue|wed|thu|fri|sat|sun\";\n field_re.put(\"dow\", dowRE);\n\n StringBuilder fieldsReSB = new StringBuilder();\n fieldsReSB.append(\"^\\\\s*(\")\n .append(\"$\")\n .append(\"|#\")\n .append(\"|\\\\w+\\\\s*=\")\n .append(\"|\"); \n .append(\"(\")\n .append(field_re.get(\"min\")).append(\")\\\\s+(\")\n .append(field_re.get(\"hour\")).append(\")\\\\s+(\")\n .append(field_re.get(\"day\")).append(\")\\\\s+(\")\n .append(field_re.get(\"month\")).append(\")\\\\s+(\")\n .append(field_re.get(\"dow\"))\n .append(\")\")\n .append(\"\\\\s+)\")\n .append(\"([^\\\\s]+)\\\\s+\")\n .append(\"(.*)$\");\n\n return fieldsReSB.toString();\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 <?php \n$cron = \"*/5 1-2 3 3,4,5 *\"; \n$result = preg_match( \"/^((?:[1-9]?\\d|\\*)\\s*(?:(?:[\\/-][1-9]?\\d)|(?:,[1-9]?\\d)+)?\\s*){5}$/\", $cron, $matches); \nprint_r($matches);\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 $isValid = Cron\\CronExpression::isValidExpression($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 ID ParentID Path\n1 NULL 1\n2 NULL 2\n3 NULL 3\n4 1 1/1.1\n5 1 1/1.2\n6 4 1/1.1/1.1.1\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 logrotate"
}
] |
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() r+ fopen() ftell() fgets() fseek() fwrite()"
},
{
"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 <typename T>
void f(const T& 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 in_\nand_\nor_\n _some_what_private\n__a_slightly_more_private_name\n __hash__ # hash(o) = o.__hash__()\n__str__ # str(o) = o.__str__()\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 \"select count(*) cnt from {0}.{1} where {2} is null\" -f $schema, $table, $col.column_name\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<double>::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<double>::signaling_NaN();
my_nan++;
my_nan += 5;
my_nan = my_nan / 10;
my_nan = 15 / my_nan;
cout << my_nan << endl;
</code></pre>
<p><code>numeric_limits<double>::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 const double &real_snan( void )\n{\n static const long long snan = 0x7ff0000080000001LL;\n return *(double*)&snan;\n}\n"
},
{
"answer_id": 236025,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 4,
"selected": true,
"text": "_control87() _control87() signal()"
},
{
"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 false"
}
] |
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 :set guifont?\n set guifont=foo .gvimrc .vimrc if has(\"gui_running\") set guifont=<C-R>=&guifont<CR>\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");
<div id="panel">
<form action="">
< form here >
</form>
</div>
<div class="slide">
<p class="sl"><a href="#" class="btn-slide" id="toggle"><span></span></a></p>
</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");
<script type="text/javascript">
$j(document).ready(function(){
$j(".btn-slide").click(function(){
$j("#panel").slideToggle("slow");
$j(this).toggleClass("active"); return false;
});
});
</script>
</code></pre>
<p>My moo attempt</p>
<pre><code>print("code sample");
<script type="text/javascript">
window.addEvent('domready', function(){
var mySlide = new Fx.Slide('panel');
$('toggle').addEvent('click', function(e){
e = new Event(e);
mySlide.toggle();
e.stop();
});
});
</script>
</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 << 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 product feature 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 >'a a 5>> vjjj>"
},
{
"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 autocmd FileType cpp setlocal expandtab shiftwidth=4 softtabstop=4 cindent\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 >> Indent line by shiftwidth spaces\n<< De-indent line by shiftwidth spaces\n5>> Indent 5 lines\n5== Re-indent 5 lines\n\n>% Increase indent of a braced or bracketed block (place cursor on brace first)\n=% Reindent a braced or bracketed block (cursor on brace)\n<% Decrease indent of a braced or bracketed block (cursor on brace)\n]p Paste text, aligning indentation with surroundings\n\n=i{ Re-indent the 'inner block', i.e. the contents of the block\n=a{ Re-indent 'a block', i.e. block and containing braces\n=2a{ Re-indent '2 blocks', i.e. this block and containing block\n\n>i{ Increase inner block indent\n<i{ Decrease inner block indent\n { } B =iB . Repeat last command\n gg=G Re-indent entire buffer\n \" Re-indent all your C source code:\n:args *.c\n:argdo normal gg=G\n:wall\n \" Re-indent all open buffers:\n:bufdo normal gg=G:wall\n Vjj> Visually mark and then indent three lines\n CTRL-t insert indent at start of line\nCTRL-d remove indent at start of line\n0 CTRL-d remove all indentation from line\n :< and :> Given a range, apply indentation e.g.\n:4,8> indent lines 4 to 8, inclusive\n ma Mark top of block to indent as marker 'a'\n >'a Indent from marker 'a' to current location\n set expandtab \"Use softtabstop spaces instead of tab characters for indentation\nset shiftwidth=4 \"Indent by 4 spaces when using >>, <<, == etc.\nset softtabstop=4 \"Indent by 4 spaces when pressing <TAB>\n\nset autoindent \"Keep indentation from previous line\nset smartindent \"Automatically inserts indentation in some cases\nset cindent \"Like smartindent, but stricter and more customisable\n if has (\"autocmd\")\n \" File type detection. Indent based on filetype. Recommended.\n filetype plugin indent on\nendif\n :help ="
},
{
"answer_id": 8720699,
"author": "Eric Kigathi",
"author_id": 181453,
"author_profile": "https://Stackoverflow.com/users/181453",
"pm_score": 4,
"selected": false,
"text": "VISUAL MODE shiftwidth set -- VISUAL MODE -- : :'<,'>s/^/ /g :'<,'>s/^/\\t/g '<,'> s/^/ /g s/^/\\t/g Tab"
},
{
"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 #!/usr/bin/env bash\n/usr/bin/open -a /Applications/MacPorts/MacVim.app $@\n export PATH=$PATH:$HOME/bin\n"
},
{
"answer_id": 12478748,
"author": "Juan Lanus",
"author_id": 243303,
"author_profile": "https://Stackoverflow.com/users/243303",
"pm_score": 4,
"selected": false,
"text": "' :syn on"
},
{
"answer_id": 16413270,
"author": "rohitkadam19",
"author_id": 1118854,
"author_profile": "https://Stackoverflow.com/users/1118854",
"pm_score": 3,
"selected": false,
"text": "5== == gg=G"
},
{
"answer_id": 17419780,
"author": "John La Rooy",
"author_id": 174728,
"author_profile": "https://Stackoverflow.com/users/174728",
"pm_score": 3,
"selected": false,
"text": "> V5j3>"
},
{
"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": ": :'<,'> le 3 :'<,'>le 3 Vjjjj:le 3\n V jjjj : le 3 jjjj\n"
},
{
"answer_id": 21593765,
"author": "Kamlesh",
"author_id": 413148,
"author_profile": "https://Stackoverflow.com/users/413148",
"pm_score": 3,
"selected": false,
"text": ".vimrc set cindent\n 10== (This will indent 10 lines from the current cursor location)\ngg=G (Complete file will be properly indented)\n"
},
{
"answer_id": 23160198,
"author": "Sagar Jain",
"author_id": 3345302,
"author_profile": "https://Stackoverflow.com/users/3345302",
"pm_score": 6,
"selected": false,
"text": "gg=G == =G n n== 4== =%"
},
{
"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 14,21> shifts line number 14 to 21 to one tab\n 14,21>>> for three tabs\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 :help visual-block\n/indent\n"
},
{
"answer_id": 32141674,
"author": "Nykakin",
"author_id": 1542900,
"author_profile": "https://Stackoverflow.com/users/1542900",
"pm_score": 4,
"selected": false,
"text": "norm i :2,10norm 10i \n :%norm 5i_\n :%norm 2i[ ]\n :1,20norm i#\n :%norm 5x\n"
},
{
"answer_id": 32509423,
"author": "zundarz",
"author_id": 780477,
"author_profile": "https://Stackoverflow.com/users/780477",
"pm_score": 3,
"selected": false,
"text": ":help left ex mode :left :le :left :%le3 :%le 3 :%left3 :%left 3 :5,7 le 3 :le :le 0"
},
{
"answer_id": 46479908,
"author": "sqqqrly",
"author_id": 5474110,
"author_profile": "https://Stackoverflow.com/users/5474110",
"pm_score": 3,
"selected": false,
"text": "I c I"
},
{
"answer_id": 50016181,
"author": "builder-7000",
"author_id": 5411198,
"author_profile": "https://Stackoverflow.com/users/5411198",
"pm_score": 0,
"selected": false,
"text": "| int main() {\nline1\nline2|\nline3\n}\n >i{ > i { int main() {\n line1\n line2|\n line3\n}\n do\nline2|\nline3\nline4\ndone\n > >2j do\n line2|\n line3\n line4\ndone\n >Nj N N set relativenumber"
},
{
"answer_id": 63043192,
"author": "Mamrezo",
"author_id": 3550735,
"author_profile": "https://Stackoverflow.com/users/3550735",
"pm_score": 3,
"selected": false,
"text": "<TAB> <S-TAB> vnoremap <TAB> >gv\nvnoremap <S-TAB> <gv\n V"
}
] |
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 Phrase Chunk ContentByte addTemplate"
},
{
"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 <dependency>\n <groupId>com.itextpdf</groupId>\n <artifactId>itext7-core</artifactId>\n <version>7.1.6</version>\n <type>pom</type>\n</dependency>\n\n<dependency>\n <groupId>com.itextpdf</groupId>\n <artifactId>html2pdf</artifactId>\n <version>2.1.3</version>\n</dependency>\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 { \nbackground-color: green;\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 <link rel=\"stylesheet\" href=\"css/jquery.mobile-1.0.1.min.css\" />\n<script src=\"js/jquery-1.7.1.min.js\"></script>\n<script src=\"js/jquery.mobile-1.0.1.min.js\"></script>\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 # naïve recursion\ndef fib(n):\n if n <= 1:\n return 1\n else:\n return fib(n - 1) + fib(n - 2)\n\n# tail-recursive with accumulator and stack\ndef fib(n):\n def fib_helper(m, k, stack):\n if m <= 1:\n if stack:\n m = stack.pop()\n return fib_helper(m, k + 1, stack)\n else:\n return k + 1\n else:\n stack.append(m - 2)\n return fib_helper(m - 1, k, stack)\n return fib_helper(n, 0, [])\n\n# iterative with accumulator and stack\ndef fib(n):\n k, stack = 0, []\n while 1:\n if n <= 1:\n k = k + 1\n if stack:\n n = stack.pop()\n else:\n break\n else:\n stack.append(n - 2)\n n = n - 1\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 0x0500"
}
] |
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 Private Sub Main()\n Randomize Timer\n If Rnd > 0.5 Then\n ExecuteFunction ()\n End If\nEnd Sub\n"
}
] |
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 user_id django.contrib.session Session.post_save contrib.session.models.Session.save() super(Session, self).save() SessionMiddleware SessionMiddleware REFERER"
},
{
"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 # On login, destroy all prev sessions\n # This disallows multiple logins from different browsers\n dbSessions = Session.objects.filter( user_id = request.user.id )\n for index, dbSession in enumerate( dbSessions ):\n if ( dbSession.session_key != request.session.session_key ):\n dbSession.delete()\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 expire_date from django.contrib.sessions.models import Session\nfrom django.contrib.auth.models import User\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\nbaduser = User.objects.get(username=\"whoever\") \ntwo_weeks = relativedelta(weeks=2)\ntwo_hours = relativedelta(hours=2)\nexpiry = baduser.last_login + two_weeks\nsessions = Session.objects.filter(\n expire_date__gt=expiry - two_hours,\n expire_date__lt=expiry + two_hours\n) \nprint sessions.count() # hopefully a manageable number\n\nfor s in sessions:\n if s.get_decoded().get('_auth_user_id') == baduser.id:\n print(s)\n s.delete()\n"
},
{
"answer_id": 26097566,
"author": "Gavin Ballard",
"author_id": 641127,
"author_profile": "https://Stackoverflow.com/users/641127",
"pm_score": 6,
"selected": false,
"text": "UserSession from django.conf import settings\nfrom django.db import models\nfrom django.contrib.sessions.models import Session\n\nclass UserSession(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL)\n session = models.ForeignKey(Session) \n UserSession from django.contrib.auth.signals import user_logged_in\n\ndef user_logged_in_handler(sender, request, user, **kwargs):\n UserSession.objects.get_or_create(user = user, session_id = request.session.session_key)\n\nuser_logged_in.connect(user_logged_in_handler)\n from .models import UserSession\n\ndef delete_user_sessions(user):\n user_sessions = UserSession.objects.filter(user = user)\n for user_session in user_sessions:\n user_session.session.delete()\n"
}
] |
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><script type="text/javascript">
$(function() {
$('input').myFunction('param');
});
</script>
<p> other html </p>
</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 $.ajax({\n type: \"GET\",\n url: \"test.js\",\n dataType: \"script\"\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 $(function() {\n $('input').myFunction('param'); \n }); \n\n|x|\n\n<p> other html </p>\n r = returnvalfromajax.split(\"|x|\"); \n document.getElementById('whatever').innerHTML = r[1]; \n eval(r[0]);\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 <script>\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 [DllImport(\"User32.dll\")] \nprivate static extern bool SetForegroundWindow(IntPtr hWnd);\n\n[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\nstatic public extern IntPtr GetForegroundWindow();\n\n[DllImport(\"user32.dll\")]\nstatic extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);\n\n\n.....\n\nprivate void SendCtrlC(IntPtr hWnd)\n {\n uint KEYEVENTF_KEYUP = 2;\n byte VK_CONTROL = 0x11;\n SetForegroundWindow(hWnd);\n keybd_event(VK_CONTROL,0,0,0);\n keybd_event (0x43, 0, 0, 0 ); //Send the C key (43 is \"C\")\n keybd_event (0x43, 0, KEYEVENTF_KEYUP, 0);\n keybd_event (VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);// 'Left Control Up\n\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 WM_GETTEXT, WM_COPY SendMessage(handle, WM_GETTEXT, maxLength, sb) // programatically copy selected text into clipboard\nawait System.Threading.Tasks.Task.Factory.StartNew(fetchSelectionToClipboard);\n\n// access clipboard which now contains selected text in foreground window (active application)\nawait System.Threading.Tasks.Task.Factory.StartNew(useClipBoardValue);\n static void fetchSelectionToClipboard()\n{\n Thread.Sleep(400);\n SendKeys.SendWait(\"^c\"); // magic line which copies selected text to clipboard\n Thread.Sleep(400);\n}\n\n// depends on the type of your app, you sometimes need to access clipboard from a Single Thread Appartment model..therefore I'm creating a new thread here\nstatic void useClipBoardValue()\n{\n Exception threadEx = null;\n // Single Thread Apartment model\n Thread staThread = new Thread(\n delegate ()\n {\n try\n {\n Console.WriteLine(Clipboard.GetText());\n }\n catch (Exception ex)\n {\n threadEx = ex;\n }\n });\n staThread.SetApartmentState(ApartmentState.STA);\n staThread.Start();\n staThread.Join();\n}\n"
},
{
"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 Clipboard.Clear();\nawait Task.Delay(300);\nSendKeys.SendWait(\"^{c}\");\nif (!Clipboard.ContainsText()) return;\nvar clipboard = Clipboard.GetText();\n... // modifying logic here\nClipboard.SetText(clipboard)\nSendKeys.SendWait(\"^{v}\");\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 / this [^\\s>/] # is highlighted as a regex, not a comment\n /*\nthis is a multi-line comment\n\"with a string\" =~ /and a regex/\n*/\nbut =~ /this is a regex with a [/*] multiline comment\nmarkers in it! */\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() malloc() top malloc()"
},
{
"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 mmap brk malloc mmap mmap malloc mmap"
}
] |
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 #include <MyImportExport.h>\n\nMYIMPORTEXPORT public int calculateSquare(int num)\n{\n return num*num;\n}\n #define SOME_CONDITION\n\n#include <MyHeader.h>\n #include <MyHeader.h>\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 ) WinAPI LoadLibrary GetProcAddress"
},
{
"answer_id": 236167,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 1,
"selected": false,
"text": "__stdcall __declspec(dllexport)"
}
] |
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><Context path="" docBase="" debug="5" reloadable="true" crossContext="true" override="true">
<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" />
</Context>
</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 <summary> <br />"
}
] |
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 define('REMOTE_VERSION', 'http://your.public.server/version.txt');\n\n// this is the version of the deployed script\ndefine('VERSION', '1.0.1');\n\nfunction isUpToDate()\n{\n $remoteVersion=trim(file_get_contents(REMOTE_VERSION));\n return version_compare(VERSION, $remoteVersion, 'ge');\n}\n version.txt 1.0.2\n"
},
{
"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 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><script></code> and/or <code></script></code> tags up within <code>document.write()</code> calls?</p>
<p>I noticed that Amazon does this as well, for example:</p>
<pre><code><script type='text/javascript'>
if (typeof window['jQuery'] == 'undefined') document.write('<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"></sc'+'ript>');
</script>
</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> <script></script> < / </ </ </script> < & &escaped; <script type=\"text/javascript\">\n document.write('\\x3Cscript type=\"text/javascript\" src=\"foo.js\">\\x3C/script>');\n</script>\n"
},
{
"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 type=\"text/javascript\""
},
{
"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> <script type=\"text/javascript\">\n <!--\n if (jQuery === undefined) {\n document.write('<script type=\"text/javascript\" src=\"http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js\"></script>');\n }\n // -->\n</script>\n document.write <script type=\"text/javascript\">\n <!--\n if (jQuery === undefined) {\n var script = document.createElement('script');\n script.setAttribute('type', 'text/javascript');\n script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');\n document.body.appendChild(script);\n }\n // -->\n</script>\n"
}
] |
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 VER.xml <version>\n 1.0\n</version>\n\n<headers>\n /path1/to/header(s)/\n /path2/to/header(s)/\n ...\n</headers>\n api.xml ...\n<symbol>\n <id>37348</id>\n <mangled>_ZN7MWidget11qt_metacallEN11QMetaObject4CallEiPPv</mangled>\n <short>qt_metacall</short>\n <class>13749</class>\n <header>mwidget.h</header>\n <line>45</line>\n <return>44</return>\n <spec>virtual</spec>\n <parameters>\n <param>\n <name>p1</name>\n <type>4078</type>\n <algn>4</algn>\n <pos>0</pos>\n </param>\n <param>\n <name>p2</name>\n <type>44</type>\n <algn>4</algn>\n <pos>1</pos>\n </param>\n <param>\n <name>p3</name>\n <type>3905</type>\n <algn>8</algn>\n <pos>2</pos>\n </param>\n </parameters>\n</symbol>\n...\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 wchar_t WideCharToMultiByte CP_UTF8 CodePage"
}
] |
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 <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string s = "Somewhere down the road";
istringstream iss(s);
do {
string subs;
iss >> subs;
cout << "Substring: " << subs << 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() std::string::c_str() void Tokenize(const string& str,\n vector<string>& tokens,\n const string& delimiters = \" \")\n{\n // Skip delimiters at beginning.\n string::size_type lastPos = str.find_first_not_of(delimiters, 0);\n // Find first \"non-delimiter\".\n string::size_type pos = str.find_first_of(delimiters, lastPos);\n\n while (string::npos != pos || string::npos != lastPos)\n {\n // Found a token, add it to the vector.\n tokens.push_back(str.substr(lastPos, pos - lastPos));\n // Skip delimiters. Note the \"not_of\"\n lastPos = str.find_first_not_of(delimiters, pos);\n // Find next \"non-delimiter\"\n pos = str.find_first_of(delimiters, lastPos);\n }\n}\n typedef << printf scanf std::cin std::cout fopen"
},
{
"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 std::find() std::find_first_of() std::string::substr() #include <iostream>\n#include <string>\n\nint main()\n{\n std::string s(\"Somewhere down the road\");\n std::string::size_type prev_pos = 0, pos = 0;\n\n while( (pos = s.find(' ', pos)) != std::string::npos )\n {\n std::string substring( s.substr(prev_pos, pos-prev_pos) );\n\n std::cout << substring << '\\n';\n\n prev_pos = ++pos;\n }\n\n std::string substring( s.substr(prev_pos, pos-prev_pos) ); // Last word\n std::cout << substring << '\\n';\n\n return 0;\n}\n"
},
{
"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 split() is_any_of()"
},
{
"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 std::vector<std::string> x = split(\"one:two::three\", ':');\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 stringstream"
},
{
"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 copy vector<string> tokens;\ncopy(istream_iterator<string>(iss),\n istream_iterator<string>(),\n back_inserter(tokens));\n vector vector<string> tokens{istream_iterator<string>{iss},\n istream_iterator<string>{}};\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 std::vector<std::string> ContainerT list<> vector<> std::list<subString> subString std::string"
},
{
"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 template<class ContainerType>\nclass Appender {\npublic:\n Appender(ContainerType& container) : container_(container) {;}\n void operator() (const char* s, unsigned length) { \n container_.push_back(std::string(s,length));\n }\nprivate:\n ContainerType& container_;\n};\n\nstd::vector<std::string> strVector;\nAppender v(strVector);\ntokenize(v, \"A number of words to be tokenized\", \" \\t\");\n class WordCounter {\npublic:\n WordCounter() : noOfWords(0) {}\n void operator() (const char*, unsigned) {\n ++noOfWords;\n }\n unsigned noOfWords;\n};\n\nWordCounter wc;\ntokenize(wc, \"A number of words to be counted\", \" \\t\"); \nASSERT( wc.noOfWords == 7 );\n"
},
{
"answer_id": 3037106,
"author": "Pratik Deoghare",
"author_id": 58737,
"author_profile": "https://Stackoverflow.com/users/58737",
"pm_score": 5,
"selected": false,
"text": "strtok #include<string>\nusing namespace std;\n\nvector<string> split(char* str,const char* delim)\n{\n char* saveptr;\n char* token = strtok_r(str,delim,&saveptr);\n\n vector<string> result;\n\n while(token != NULL)\n {\n result.push_back(token);\n token = strtok_r(NULL,delim,&saveptr);\n }\n return result;\n}\n"
},
{
"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 separators"
},
{
"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 #include <iostream>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n\ntemplate<typename _OutputIterator>\ninline void split(\n const std::string& str, \n const std::string& delim, \n _OutputIterator result)\n{\n using namespace boost::algorithm;\n typedef split_iterator<std::string::const_iterator> It;\n\n for(It iter=make_split_iterator(str, first_finder(delim, is_equal()));\n iter!=It();\n ++iter)\n {\n *(result++) = boost::copy_range<std::string>(*iter);\n }\n}\n\nint main(int argc, char* argv[])\n{\n using namespace std;\n\n vector<string> splitted;\n split(\"HelloFOOworldFOO!\", \"FOO\", back_inserter(splitted));\n\n // or directly to console, for example\n split(\"HelloFOOworldFOO!\", \"FOO\", ostream_iterator<string>(cout, \"\\n\"));\n return 0;\n}\n"
},
{
"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 vector<string> hosts;\nsplit(hosts, \"192.168.1.2,192.168.1.3\", ',');\nfor( size_t i = 0; i < hosts.size(); i++){\n cout << \"Connecting host : \" << hosts.at(i) << \"...\" << endl;\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 \"\" \",\" 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 if (end != start) {\n tokens.push_back(text.substr(start, end - start));\n }\n start = end + 1;\n }\n if (end != start) {\n tokens.push_back(text.substr(start));\n }\n return tokens;\n}\n std::vector<std::string> split(const std::string& text, const std::string& delims)\n{\n std::vector<std::string> tokens;\n std::size_t start = text.find_first_not_of(delims), end = 0;\n\n while((end = text.find_first_of(delims, start)) != std::string::npos)\n {\n tokens.push_back(text.substr(start, end - start));\n start = text.find_first_not_of(delims, end);\n }\n if(start != std::string::npos)\n tokens.push_back(text.substr(start));\n\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 std::upper \",\" \";\" \" \""
},
{
"answer_id": 8457004,
"author": "Software_Designer",
"author_id": 999884,
"author_profile": "https://Stackoverflow.com/users/999884",
"pm_score": 3,
"selected": false,
"text": "strtok() #include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nchar one_line_string[] = \"hello hi how are you nice weather we are having ok then bye\";\nchar seps[] = \" ,\\t\\n\";\nchar *token;\n\n\n\nint main()\n{\n vector<string> vec_String_Lines;\n token = strtok( one_line_string, seps );\n\n cout << \"Extracting and storing data in a vector..\\n\\n\\n\";\n\n while( token != NULL )\n {\n vec_String_Lines.push_back(token);\n token = strtok( NULL, seps );\n }\n cout << \"Displaying end result in vector line storage..\\n\\n\";\n\n for ( int i = 0; i < vec_String_Lines.size(); ++i)\n cout << vec_String_Lines[i] << \"\\n\";\n cout << \"\\n\\n\\n\";\n\n\nreturn 0;\n}\n"
},
{
"answer_id": 9385486,
"author": "landen",
"author_id": 1224414,
"author_profile": "https://Stackoverflow.com/users/1224414",
"pm_score": 2,
"selected": false,
"text": "vector // Split string into parts.\n class Split : public std::vector<std::string>\n {\n public:\n Split(const std::string& str, char* delimList)\n {\n size_t lastPos = 0;\n size_t pos = str.find_first_of(delimList);\n\n while (pos != std::string::npos)\n {\n if (pos != lastPos)\n push_back(str.substr(lastPos, pos-lastPos));\n lastPos = pos + 1;\n pos = str.find_first_of(delimList, lastPos);\n }\n if (lastPos < str.length())\n push_back(str.substr(lastPos, pos-lastPos));\n }\n };\n std::set<std::string> words;\nSplit split(\"Hello,World\", \",\");\nwords.insert(split.begin(), split.end());\n"
},
{
"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 vector<string> v = split<string>(\"Hello, there; World\", \";,\");\n vector<wstring> v = split<wstring>(L\"Hello, there; World\", L\";,\");\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 #include <iostream>\n#include <string>\nint _tmain(int argc, _TCHAR* argv[])\n{\n DSplitString<> aa(\"doicanhden1;doicanhden2;doicanhden3;\", ';');\n for each (std::string var in aa)\n {\n std::cout << var << std::endl;\n }\n std::cin.get();\n return 0;\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 #include <string.h>\n#include <iostream>\n#include <vector>\n#include \"StringSplit.hpp\"\n\nusing namespace std;\n\nvoid StringSplit::assimilate(char*src, char delim)\n{\n int until = untilnextdelim(src, delim);\n if (until > 0)\n {\n char * temp = new char[until + 1];\n memset(temp, 0, until + 1);\n copy_fragment(temp, src, delim);\n if (keep_empty || *temp != 0)\n {\n if (!do_string)\n {\n Container.push_back(temp);\n }\n else\n {\n string x = temp;\n ContainerS.push_back(x);\n }\n\n }\n else\n {\n delete[] temp;\n }\n }\n}\n\nvoid StringSplit::assimilate(char*src, char* delim)\n{\n int until = untilnextdelim(src, delim);\n if (until > 0)\n {\n char * temp = new char[until + 1];\n memset(temp, 0, until + 1);\n copy_fragment(temp, src, delim);\n if (keep_empty || *temp != 0)\n {\n if (!do_string)\n {\n Container.push_back(temp);\n }\n else\n {\n string x = temp;\n ContainerS.push_back(x);\n }\n }\n else\n {\n delete[] temp;\n }\n }\n}\n\nlong StringSplit::calc_string_size(char* _in)\n{\n long i = 0;\n while (*_in++)\n {\n i++;\n }\n return i;\n}\n\nbool StringSplit::string_contains(char* haystack, char* needle)\n{\n size_t len = calc_string_size(needle);\n size_t lenh = calc_string_size(haystack);\n while (lenh--)\n {\n if (match_fragment(haystack + lenh, needle, len))\n {\n return true;\n }\n }\n return false;\n}\n\nbool StringSplit::match_fragment(char* _src, char* cmp, int len)\n{\n while (len--)\n {\n if (*(_src + len) != *(cmp + len))\n {\n return false;\n }\n }\n return true;\n}\n\nint StringSplit::untilnextdelim(char* _in, char delim)\n{\n size_t len = calc_string_size(_in);\n if (*_in == delim)\n {\n _in += 1;\n return len - 1;\n }\n\n int c = 0;\n while (*(_in + c) != delim && c < len)\n {\n c++;\n }\n\n return c;\n}\n\nint StringSplit::untilnextdelim(char* _in, char* delim)\n{\n int s = calc_string_size(delim);\n int c = 1 + s;\n\n if (!string_contains(_in, delim))\n {\n return calc_string_size(_in);\n }\n else if (match_fragment(_in, delim, s))\n {\n _in += s;\n return calc_string_size(_in);\n }\n\n while (!match_fragment(_in + c, delim, s))\n {\n c++;\n }\n\n return c;\n}\n\nvoid StringSplit::copy_fragment(char* dest, char* src, char delim)\n{\n if (*src == delim)\n {\n src++;\n }\n\n int c = 0;\n while (*(src + c) != delim && *(src + c))\n {\n *(dest + c) = *(src + c);\n c++;\n }\n *(dest + c) = 0;\n}\n\nvoid StringSplit::copy_string(char* dest, char* src)\n{\n int i = 0;\n while (*(src + i))\n {\n *(dest + i) = *(src + i);\n i++;\n }\n}\n\nvoid StringSplit::copy_fragment(char* dest, char* src, char* delim)\n{\n size_t len = calc_string_size(delim);\n size_t lens = calc_string_size(src);\n\n if (match_fragment(src, delim, len))\n {\n src += len;\n lens -= len;\n }\n\n int c = 0;\n while (!match_fragment(src + c, delim, len) && (c < lens))\n {\n *(dest + c) = *(src + c);\n c++;\n }\n *(dest + c) = 0;\n}\n\nvector<char*> StringSplit::split_cstr(char Delimiter)\n{\n int i = 0;\n while (*String)\n {\n if (*String != Delimiter && i == 0)\n {\n assimilate(String, Delimiter);\n }\n if (*String == Delimiter)\n {\n assimilate(String, Delimiter);\n }\n i++;\n String++;\n }\n\n String -= i;\n delete[] String;\n\n return Container;\n}\n\nvector<string> StringSplit::split_string(char Delimiter)\n{\n do_string = true;\n\n int i = 0;\n while (*String)\n {\n if (*String != Delimiter && i == 0)\n {\n assimilate(String, Delimiter);\n }\n if (*String == Delimiter)\n {\n assimilate(String, Delimiter);\n }\n i++;\n String++;\n }\n\n String -= i;\n delete[] String;\n\n return ContainerS;\n}\n\nvector<char*> StringSplit::split_cstr(char* Delimiter)\n{\n int i = 0;\n size_t LenDelim = calc_string_size(Delimiter);\n\n while(*String)\n {\n if (!match_fragment(String, Delimiter, LenDelim) && i == 0)\n {\n assimilate(String, Delimiter);\n }\n if (match_fragment(String, Delimiter, LenDelim))\n {\n assimilate(String,Delimiter);\n }\n i++;\n String++;\n }\n\n String -= i;\n delete[] String;\n\n return Container;\n}\n\nvector<string> StringSplit::split_string(char* Delimiter)\n{\n do_string = true;\n int i = 0;\n size_t LenDelim = calc_string_size(Delimiter);\n\n while (*String)\n {\n if (!match_fragment(String, Delimiter, LenDelim) && i == 0)\n {\n assimilate(String, Delimiter);\n }\n if (match_fragment(String, Delimiter, LenDelim))\n {\n assimilate(String, Delimiter);\n }\n i++;\n String++;\n }\n\n String -= i;\n delete[] String;\n\n return ContainerS;\n}\n int main(int argc, char*argv[])\n{\n StringSplit ss = \"This:CUT:is:CUT:an:CUT:example:CUT:cstring\";\n vector<char*> Split = ss.split_cstr(\":CUT:\");\n\n for (int i = 0; i < Split.size(); i++)\n {\n cout << Split[i] << endl;\n }\n\n return 0;\n}\n int main(int argc, char*argv[])\n{\n StringSplit ss = \"This:is:an:example:cstring\";\n vector<char*> Split = ss.split_cstr(':');\n\n for (int i = 0; i < Split.size(); i++)\n {\n cout << Split[i] << endl;\n }\n\n return 0;\n}\n\nint main(int argc, char*argv[])\n{\n string mystring = \"This[SPLIT]is[SPLIT]an[SPLIT]example[SPLIT]string\";\n StringSplit ss = mystring;\n vector<string> Split = ss.split_string(\"[SPLIT]\");\n\n for (int i = 0; i < Split.size(); i++)\n {\n cout << Split[i] << endl;\n }\n\n return 0;\n}\n\nint main(int argc, char*argv[])\n{\n string mystring = \"This|is|an|example|string\";\n StringSplit ss = mystring;\n vector<string> Split = ss.split_string('|');\n\n for (int i = 0; i < Split.size(); i++)\n {\n cout << Split[i] << endl;\n }\n\n return 0;\n}\n StringSplit ss = mystring;\nss.keep_empty = true;\nvector<string> Split = ss.split_string(\":DELIM:\");\n String[] Split = \n \"Hey:cut:what's:cut:your:cut:name?\".Split(new[]{\":cut:\"}, StringSplitOptions.None);\n\nforeach(String X in Split)\n{\n Console.Write(X);\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 using namespace std;\n#include <iostream>\n#include <vector>\n#include <sstream>\n#include <string>\n\nvector<string> split ( string input , string split_id ) {\n vector<string> result;\n int i = 0;\n bool add;\n string temp;\n stringstream ss;\n size_t found;\n string real;\n int r = 0;\n while ( i != input.length() ) {\n add = false;\n ss << input.at(i);\n temp = ss.str();\n found = temp.find(split_id);\n if ( found != string::npos ) {\n add = true;\n real.append ( temp , 0 , found );\n } else if ( r > 0 && ( i+1 ) == input.length() ) {\n add = true;\n real.append ( temp , 0 , found );\n }\n if ( add ) {\n result.push_back(real);\n ss.str(string());\n ss.clear();\n temp.clear();\n real.clear();\n r = 0;\n }\n i++;\n r++;\n }\n return result;\n}\n\nint main() {\n string s = \"S,o,m,e,w,h,e,r,e, down the road \\n In a really big C++ house. \\n Lives a little old lady. \\n That no one ever knew. \\n She comes outside. \\n In the very hot sun. \\n\\n\\n\\n\\n\\n\\n\\n And throws C++ at us. \\n The End. FIN.\";\n vector < string > Token;\n Token = split ( s , \",\" );\n for ( int i = 0 ; i < Token.size(); i++) cout << Token.at(i) << endl;\n cout << endl << Token.size();\n int a;\n cin >> a;\n return a;\n}\n"
},
{
"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 vector <string> split(const string& str, const string& delimiter = \" \") {\n vector <string> tokens;\n\n string::size_type lastPos = 0;\n string::size_type pos = str.find(delimiter, lastPos);\n\n while (string::npos != pos) {\n // Found a token, add it to the vector.\n cout << str.substr(lastPos, pos - lastPos) << endl;\n tokens.push_back(str.substr(lastPos, pos - lastPos));\n lastPos = pos + delimiter.size();\n pos = str.find(delimiter, lastPos);\n }\n\n tokens.push_back(str.substr(lastPos, str.size() - lastPos));\n return tokens;\n}\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 Somewhere\ndown\nthe\nroad\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 struct Delim {\n bool operator()(char c) {\n return not isalpha(c);\n }\n}; \n\nint main() {\n string s(\"#include<iostream>\\n\"\n \"int main() { std::cout << \\\"Hello world!\\\" << std::endl; }\");\n\n vector<string> v;\n\n split(v, s, Delim(), true);\n /* Which is also the same as */\n split(v, s, [](char c) { return not isalpha(c); }, true);\n\n for (const auto& i : v) {\n cout << i << endl;\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 std::wstring MyString(L\"Part 1SEPsecond partSEPlast partSEPend\");\nstd::vector<std::wstring> Parts = IniFile::SplitString(MyString, L\"SEP\");\nstd::wcout << L\"The string: \" << MyString << std::endl;\nfor (std::vector<std::wstring>::const_iterator it=Parts.begin(); it<Parts.end(); ++it)\n{\n std::wcout << *it << L\"<---\" << std::endl;\n}\nstd::wcout << std::endl;\nMyString = L\"this,time,a,comma separated,string\";\nstd::wcout << L\"The string: \" << MyString << std::endl;\nParts = IniFile::SplitString(MyString, L\",\");\nfor (std::vector<std::wstring>::const_iterator it=Parts.begin(); it<Parts.end(); ++it)\n{\n std::wcout << *it << L\"<---\" << std::endl;\n}\n The string: Part 1SEPsecond partSEPlast partSEPend\nPart 1<---\nsecond part<---\nlast part<---\nend<---\n\nThe string: this,time,a,comma separated,string\nthis<---\ntime<---\na<---\ncomma separated<---\nstring<---\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 LazyStringSplitter next #include <iostream>\nusing namespace std;\n\nint main()\n{\n LazyStringSplitter splitter;\n\n // split at the characters ' ', '!', '.', ','\n splitter(\"This, is a string. And here is another string! Let's test and see how well this does.\", \" !.,\");\n\n while (!splitter.empty())\n cout << splitter.next() << endl;\n return 0;\n}\n This\nis\na\nstring\nAnd\nhere\nis\nanother\nstring\nLet's\ntest\nand\nsee\nhow\nwell\nthis\ndoes\n begin end vector<string> split_string(splitter.begin(), splitter.end());\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 std::list wschars #include <string>\n#include <list>\n#include <iostream>\n#include <cstring>\n\nusing namespace std;\n\nconst char *wschars = \"\\t\\n \";\n\nlist<string> split(const string &str)\n{\n const char *cstr = str.c_str();\n list<string> out;\n\n while (*cstr) { // while remaining string not empty\n size_t toklen;\n cstr += strspn(cstr, wschars); // skip leading whitespace\n toklen = strcspn(cstr, wschars); // figure out token length\n if (toklen) // if we have a token, add to list\n out.push_back(string(cstr, toklen));\n cstr += toklen; // skip over token\n }\n\n // ran out of string; return list\n\n return out;\n}\n\nint main(int argc, char **argv)\n{\n list<string> li = split(argv[1]);\n for (list<string>::iterator i = li.begin(); i != li.end(); i++)\n cout << \"{\" << *i << \"}\" << endl;\n return 0;\n}\n $ ./split \"\"\n$ ./split \"a\"\n{a}\n$ ./split \" a \"\n{a}\n$ ./split \" a b\"\n{a}\n{b}\n$ ./split \" a b c\"\n{a}\n{b}\n{c}\n$ ./split \" a b c d \"\n{a}\n{b}\n{c}\n{d}\n split void split_rec(const char *cstr, list<string> &li)\n{\n if (*cstr) {\n const size_t leadsp = strspn(cstr, wschars);\n const size_t toklen = strcspn(cstr + leadsp, wschars);\n\n if (toklen)\n li.push_back(string(cstr + leadsp, toklen));\n\n split_rec(cstr + leadsp + toklen, li);\n }\n}\n\nlist<string> split(const string &str)\n{\n list<string> out;\n split_rec(str.c_str(), out);\n return out;\n}\n"
},
{
"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 std::vector<string> TokenizeDefault( const string str )\n{\n using namespace std;\n\n regex re( \"[\\\\s,]+\" );\n\n return Tokenize( str, re );\n}\n \"[\\\\s,]+\" \\\\s , wstring string std::regex std::wregex sregex_token_iterator wsregex_token_iterator"
},
{
"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 std::vector"
},
{
"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 this\nis\nthe\nstring\nto\nsplit\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 template<class Container>\nstd::vector<std::string> split_by_valid_chars(const std::string& input, const Container& valid_chars)\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), is_in(valid_chars));\n if (first == end(input)) break;\n auto last = find_if(first, end(input), not_in(valid_chars));\n result.emplace_back(first, last);\n current = last;\n }\n return result;\n}\n namespace detail {\n template<class Container>\n struct is_in {\n is_in(const Container& charset)\n : _charset(charset)\n {}\n\n bool operator()(char c) const\n {\n return find(begin(_charset), end(_charset), c) != end(_charset);\n }\n\n const Container& _charset;\n };\n\n template<class Container>\n struct not_in {\n not_in(const Container& charset)\n : _charset(charset)\n {}\n\n bool operator()(char c) const\n {\n return find(begin(_charset), end(_charset), c) == end(_charset);\n }\n\n const Container& _charset;\n };\n\n}\n\ntemplate<class Container>\ndetail::not_in<Container> not_in(const Container& c)\n{\n return detail::not_in<Container>(c);\n}\n\ntemplate<class Container>\ndetail::is_in<Container> is_in(const Container& c)\n{\n return detail::is_in<Container>(c);\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> std::locale std::istream::imbue() std::ctype<char> std::ctype<wchar_t> std::ctype<char> std::ctype<wchar_t> #include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <sstream>\n#include <locale>\n\nstruct whitespace_mask {\n std::ctype_base::mask mask_table[std::ctype<char>::table_size];\n whitespace_mask(std::string const& spaces) {\n std::ctype_base::mask* table = this->mask_table;\n std::ctype_base::mask const* tab\n = std::use_facet<std::ctype<char>>(std::locale()).table();\n for (std::size_t i(0); i != std::ctype<char>::table_size; ++i) {\n table[i] = tab[i] & ~std::ctype_base::space;\n }\n std::for_each(spaces.begin(), spaces.end(), [=](unsigned char c) {\n table[c] |= std::ctype_base::space;\n });\n }\n};\nclass whitespace_facet\n : private whitespace_mask\n , public std::ctype<char> {\npublic:\n whitespace_facet(std::string const& spaces)\n : whitespace_mask(spaces)\n , std::ctype<char>(this->mask_table) {\n }\n};\n\nstruct whitespace {\n std::string spaces;\n whitespace(std::string const& spaces): spaces(spaces) {}\n};\nstd::istream& operator>>(std::istream& in, whitespace const& ws) {\n std::locale loc(in.getloc(), new whitespace_facet(ws.spaces));\n in.imbue(loc);\n return in;\n}\n// everything above would probably go into a utility library...\n\nint main() {\n std::istringstream in(\"a, b, c, d, e\");\n std::copy(std::istream_iterator<std::string>(in >> whitespace(\", \")),\n std::istream_iterator<std::string>(),\n std::ostream_iterator<std::string>(std::cout, \"\\n\"));\n\n std::istringstream pipes(\"a b c| d |e e\");\n std::copy(std::istream_iterator<std::string>(pipes >> whitespace(\"|\")),\n std::istream_iterator<std::string>(),\n std::ostream_iterator<std::string>(std::cout, \"\\n\")); \n}\n void f(std::istream& in) {\n std::istream pipes(in.rdbuf());\n pipes >> whitespace(\"|\");\n std::istream comma(in.rdbuf());\n comma >> whitespace(\",\");\n\n std::string s0, s1;\n if (pipes >> s0 >> std::ws // read up to first pipe and ignore sequence of pipes\n && comma >> s1 >> std::ws) { // read up to first comma and ignore commas\n // ...\n }\n}\n"
},
{
"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 std::string s = \"one:two::three\";\nstd::string delim = \":\";\nstd::vector<std::string> vv = split(s, delim.c_str());\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 begin() end() list using vec_of_vecs_t = std::vector<std::vector<int>>;\n\nstd::vector<int> v{1, 2, 0, 3, 4, 5, 0, 7, 8, 0, 9};\nauto r = split<vec_of_vecs_t>(v, std::initializer_list<int>{0, 2});\n v 0 2 strtok() getline()"
},
{
"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> ÷rs)\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 std::vector<std::string>& Myneatclass::split(const std::string &s, char delim, std::vector<std::string> &elems, const size_t MAXELEMENTS) {\n std::stringstream ss(s);\n std::string item;\n while (std::getline(ss, item, delim)) {\n elems.push_back(item);\n if (MAXELEMENTS > 0 && !ss.eof() && elems.size() + 1 >= MAXELEMENTS) {\n std::getline(ss, item);\n elems.push_back(item);\n break;\n }\n }\n return elems;\n}\nstd::vector<std::string> Myneatclass::split(const std::string &s, char delim, const size_t MAXELEMENTS) {\n std::vector<std::string> elems;\n split(s, delim, elems, MAXELEMENTS);\n return elems;\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 auto a = split(\"this!!is!!!example!string\", \"!!\");\n this\nis\n!example!string\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 std::vector<std::string> split(const std::string &s,\n const std::vector<char> &delims) {\n std::vector<std::string> res;\n auto stuff = [&delims](char c) { return !in(delims, c); };\n auto space = [&delims](char c) { return in(delims, c); };\n auto first = std::find_if(s.begin(), s.end(), stuff);\n while (first != s.end()) {\n auto last = std::find_if(first, s.end(), space);\n res.push_back(std::string(first, last));\n first = std::find_if(last + 1, s.end(), stuff);\n }\n return res;\n}\n int main() {\n std::string s = \" aaa, bb cc \";\n for (auto el: split(s, {' ', ','}))\n std::cout << el << std::endl;\n return 0;\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 str_split main() int main()\n{\n std::string s = \"Hello, world! We need to make the world a better place. Because your world is also my world, and our children's world.\";\n\n std::vector<std::string> split = str_split(\"world\", s);\n\n for(int i = 0; i < split.size(); i++)\n {\n std::cout << split[i] << std::endl;\n }\n}\n Hello, \n! We need to make the \n a better place. Because your \n is also my \n, and our children's \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\" #include <string>\n#include <vector>\n#include <algorithm>\n\nstd::vector<std::string> split(const std::string& s, const std::string& delims)\n{\n using namespace std;\n\n vector<string> v;\n\n // Start of an element.\n size_t elemStart = 0;\n\n // We start searching from the end of the previous element, which\n // initially is the start of the string.\n size_t elemEnd = 0;\n\n // Find the first non-delim, i.e. the start of an element, after the end of the previous element.\n while((elemStart = s.find_first_not_of(delims, elemEnd)) != string::npos)\n {\n // Find the first delem, i.e. the end of the element (or if this fails it is the end of the string).\n elemEnd = s.find_first_of(delims, elemStart);\n // Add it.\n v.emplace_back(s, elemStart, elemEnd == string::npos ? string::npos : elemEnd - elemStart);\n }\n // When there are no more non-spaces, we are done.\n\n return v;\n}\n"
},
{
"answer_id": 44246368,
"author": "小文件",
"author_id": 4869018,
"author_profile": "https://Stackoverflow.com/users/4869018",
"pm_score": 0,
"selected": false,
"text": "string u32string boost::algorithm::split template<typename CharT, typename UnaryPredicate>\nvoid split(std::vector<std::basic_string<CharT>>& split_result,\n const std::basic_string<CharT>& s,\n UnaryPredicate predicate)\n{\n using ST = std::basic_string<CharT>;\n using std::swap;\n std::vector<ST> tmp_result;\n auto iter = s.cbegin(),\n end_iter = s.cend();\n while (true)\n {\n /**\n * edge case: empty str -> push an empty str and exit.\n */\n auto find_iter = find_if(iter, end_iter, predicate);\n tmp_result.emplace_back(iter, find_iter);\n if (find_iter == end_iter) { break; }\n iter = ++find_iter; \n }\n swap(tmp_result, split_result);\n}\n\n\ntemplate<typename CharT>\nvoid split(std::vector<std::basic_string<CharT>>& split_result,\n const std::basic_string<CharT>& s,\n const std::basic_string<CharT>& char_candidate)\n{\n std::unordered_set<CharT> candidate_set(char_candidate.cbegin(),\n char_candidate.cend());\n auto predicate = [&candidate_set](const CharT& c) {\n return candidate_set.count(c) > 0U;\n };\n return split(split_result, s, predicate);\n}\n\ntemplate<typename CharT>\nvoid split(std::vector<std::basic_string<CharT>>& split_result,\n const std::basic_string<CharT>& s,\n const CharT* literals)\n{\n return split(split_result, s, std::basic_string<CharT>(literals));\n}\n"
},
{
"answer_id": 44294208,
"author": "Romário",
"author_id": 2507567,
"author_profile": "https://Stackoverflow.com/users/2507567",
"pm_score": 2,
"selected": false,
"text": "split #include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> split(const string &str, const string &delim)\n{ \n const auto delim_pos = str.find(delim);\n\n if (delim_pos == string::npos)\n return {str};\n\n vector<string> ret{str.substr(0, delim_pos)};\n auto tail = split(str.substr(delim_pos + delim.size(), string::npos), delim);\n\n ret.insert(ret.end(), tail.begin(), tail.end());\n\n return ret;\n}\n <string> <vector>"
},
{
"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 foo:bar:::baz\nskipEmpty=0 |foo|bar|||baz|\nskipEmpty=1 |foo|bar|baz|\n\n\nskipEmpty=0 |\nskipEmpty=1 |\n\nfoo\nskipEmpty=0 |foo|\nskipEmpty=1 |foo|\n\n:\nskipEmpty=0 |||\nskipEmpty=1 |\n\n::\nskipEmpty=0 ||||\nskipEmpty=1 |\n\n:foo\nskipEmpty=0 ||foo|\nskipEmpty=1 |foo|\n\n::foo\nskipEmpty=0 |||foo|\nskipEmpty=1 |foo|\n\n:foo:\nskipEmpty=0 ||foo||\nskipEmpty=1 |foo|\n\n:foo::\nskipEmpty=0 ||foo|||\nskipEmpty=1 |foo|\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 range-v3 #include <iostream>\n#include <string>\n#include <string_view>\n#include \"range/v3/view.hpp\"\n#include \"range/v3/algorithm.hpp\"\n\nint main() {\n std::string s = \"Somewhere down the range v3 library\";\n ranges::for_each(s \n | ranges::view::split(' ')\n | ranges::view::transform([](auto &&sub) {\n return std::string_view(&*sub.begin(), ranges::distance(sub));\n }),\n [](auto s) {std::cout << \"Substring: \" << s << \"\\n\";}\n );\n}\n for ranges::for_each #include <iostream>\n#include <string>\n#include <string_view>\n#include \"range/v3/view.hpp\"\n\nint main()\n{\n std::string str = \"Somewhere down the range v3 library\";\n for (auto s : str | ranges::view::split(' ')\n | ranges::view::transform([](auto&& sub) { return std::string_view(&*sub.begin(), ranges::distance(sub)); }\n ))\n {\n std::cout << \"Substring: \" << s << \"\\n\";\n }\n}\n"
},
{
"answer_id": 54220083,
"author": "okovko",
"author_id": 5122006,
"author_profile": "https://Stackoverflow.com/users/5122006",
"pm_score": 1,
"selected": false,
"text": "<tag></tag> using namespace std;\n\n#include <iostream>\n#include <string>\n\n#include <cctype>\n\ntypedef enum boundary_type_e {\n E_BOUNDARY_TYPE_ERROR = -1,\n E_BOUNDARY_TYPE_NONE,\n E_BOUNDARY_TYPE_LEFT,\n E_BOUNDARY_TYPE_RIGHT,\n} boundary_type_t;\n\ntypedef struct boundary_s {\n boundary_type_t type;\n int pos;\n} boundary_t;\n\nbool is_delim_char(int c) {\n return isspace(c); // also compare against any other chars you want to use as delimiters\n}\n\nbool is_word_char(int c) {\n return ' ' <= c && c <= '~' && !is_delim_char(c);\n}\n\nboundary_t maybe_word_boundary(string str, int pos) {\n int len = str.length();\n if (pos < 0 || pos >= len) {\n return (boundary_t){.type = E_BOUNDARY_TYPE_ERROR};\n } else {\n if (pos == 0 && is_word_char(str[pos])) {\n // if the first character is word-y, we have a left boundary at the beginning\n return (boundary_t){.type = E_BOUNDARY_TYPE_LEFT, .pos = pos};\n } else if (pos == len - 1 && is_word_char(str[pos])) {\n // if the last character is word-y, we have a right boundary left of the null terminator\n return (boundary_t){.type = E_BOUNDARY_TYPE_RIGHT, .pos = pos + 1};\n } else if (!is_word_char(str[pos]) && is_word_char(str[pos + 1])) {\n // if we have a delimiter followed by a word char, we have a left boundary left of the word char\n return (boundary_t){.type = E_BOUNDARY_TYPE_LEFT, .pos = pos + 1};\n } else if (is_word_char(str[pos]) && !is_word_char(str[pos + 1])) {\n // if we have a word char followed by a delimiter, we have a right boundary right of the word char\n return (boundary_t){.type = E_BOUNDARY_TYPE_RIGHT, .pos = pos + 1};\n }\n return (boundary_t){.type = E_BOUNDARY_TYPE_NONE};\n }\n}\n\nint main() {\n string str;\n getline(cin, str);\n\n int len = str.length();\n for (int i = 0; i < len; i++) {\n boundary_t boundary = maybe_word_boundary(str, i);\n if (boundary.type == E_BOUNDARY_TYPE_LEFT) {\n // whatever\n } else if (boundary.type == E_BOUNDARY_TYPE_RIGHT) {\n // whatever\n }\n }\n}\n enum class is_word_char maybe_word_boundary is_word_char"
},
{
"answer_id": 60732623,
"author": "balki",
"author_id": 463758,
"author_profile": "https://Stackoverflow.com/users/463758",
"pm_score": 1,
"selected": false,
"text": "std::function void iter_words(const std::string_view& input, const std::function<void(std::string_view)>& process_word) {\n\n auto itr = input.begin();\n\n auto consume_whitespace = [&]() {\n for(; itr != input.end(); ++itr) {\n if(!isspace(*itr))\n return;\n }\n };\n\n auto consume_letters = [&]() {\n for(; itr != input.end(); ++itr) {\n if(isspace(*itr))\n return;\n }\n };\n\n while(true) {\n consume_whitespace();\n if(itr == input.end())\n return;\n auto word_start = itr - input.begin();\n consume_letters();\n auto word_end = itr - input.begin();\n process_word(input.substr(word_start, word_end - word_start));\n }\n}\n\nint main() {\n iter_words(\"foo bar\", [](std::string_view sv) {\n std::cout << \"Got word: \" << sv << '\\n';\n });\n return 0;\n}\n"
},
{
"answer_id": 61621475,
"author": "J. Willus",
"author_id": 6327684,
"author_profile": "https://Stackoverflow.com/users/6327684",
"pm_score": 4,
"selected": false,
"text": "split #include <iostream>\n#include <ranges>\n#include <string_view>\n\nnamespace ranges = std::ranges;\nnamespace views = std::views;\n\nusing str = std::string_view;\n\nconstexpr auto view =\n \"Multiple words\"\n | views::split(' ')\n | views::transform([](auto &&r) -> str {\n return {\n &*r.begin(),\n static_cast<str::size_type>(ranges::distance(r))\n };\n });\n\nauto main() -> int {\n for (str &&sv : view) {\n std::cout << sv << '\\n';\n }\n}\n"
},
{
"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 port city international university\n port\ncity\ninternational\nuniversity\n char delimiter = ',' ;\nwhile(getline(ss, token, delimiter)) tokens.push_back(token) ;\n while (ss >> token) tokens.push_back(token);\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 std::string_view std::views::split transform #include <iostream>\n#include <ranges>\n#include <string_view>\n\nnamespace views = std::views;\n\nconstexpr std::string_view text = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit.\";\n\nauto main() -> int {\n for (std::string_view&& word : text | views::split(' ')) {\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 std::string std::vector std::strings #include <string>\n#include <vector>\n\nstd::vector<std::string>\ntokenize(const std::string& str, const std::string& delimiters)\n{\n using ssize_t = std::string::size_type;\n const ssize_t str_ln = str.length();\n ssize_t last_pos = 0;\n\n // container for the extracted tokens\n std::vector<std::string> tokens;\n\n while (last_pos < str_ln) {\n // find the position of the next delimiter\n ssize_t pos = str.find_first_of(delimiters, last_pos);\n\n // if no delimiters found, set the position to the length of string\n if (pos == std::string::npos)\n pos = str_ln;\n\n // if the substring is nonempty, store it in the container\n if (pos != last_pos)\n tokens.emplace_back(str.substr(last_pos, pos - last_pos));\n\n // scan past the previous substring\n last_pos = pos + 1;\n }\n\n return tokens;\n}\n #include <iostream>\n\nint main()\n{\n std::string input_str = \"one + two * (three - four)!!---! \";\n const char* delimiters = \"! +- (*)\";\n std::vector<std::string> tokens = tokenize(input_str, delimiters);\n\n std::cout << \"input = '\" << input_str << \"'\\n\"\n << \"delimiters = '\" << delimiters << \"'\\n\"\n << \"nr of tokens found = \" << tokens.size() << std::endl;\n for (const std::string& tk : tokens) {\n std::cout << \"token = '\" << tk << \"'\\n\";\n }\n\n return 0;\n}\n\n"
},
{
"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 syntax: glob\n\n.DS_Store\n\n*.swp\n*~.nib\n\nbuild\n\n*.pbxuser\n*.perspective\n*.perspectivev3\n*.mode1v3\n\n*.pyc\n"
}
] |
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(\"~/\") HttpContext.Current.Server.MapPath(\"/Directory/\") \n HttpContext.Current.Server.MapPath(\"Directory/\") \n"
},
{
"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(\".\") HostingEnvironment.MapPath(\".\")\n"
},
{
"answer_id": 6916691,
"author": "Damith",
"author_id": 2558060,
"author_profile": "https://Stackoverflow.com/users/2558060",
"pm_score": 4,
"selected": false,
"text": "HostingEnvironment.ApplicationPhysicalPath System.Web.Hosting"
},
{
"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<int> Index = { 3, 1, 2 };
std::vector<std::string> 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 struct ordering {\n bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) {\n return *(a.second) < *(b.second);\n }\n};\n\nsort(order.begin(), order.end(), ordering());\n order order template <typename T>\nvector<T> sort_from_ref(\n vector<T> const& in,\n vector<pair<size_t, myiter> > const& reference\n) {\n vector<T> ret(in.size());\n\n size_t const size = in.size();\n for (size_t i = 0; i < size; ++i)\n ret[i] = in[reference[i].first];\n\n return ret;\n}\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 #include <boost/iterator/counting_iterator.hpp>\n#include <vector>\n#include <algorithm>\n\nstd::vector<double> keys = ...\nstd::vector<double> values = ...\n\nstd::vector<size_t> indices(boost::counting_iterator<size_t>(0u), boost::counting_iterator<size_t>(keys.size()));\nstd::sort(begin(indices), end(indices), [&](size_t lhs, size_t rhs) {\n return keys[lhs] < keys[rhs];\n});\n\n// Now to iterate through the values array.\nfor (size_t i: indices)\n{\n std::cout << values[i] << std::endl;\n}\n"
},
{
"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 ages names void ordered_pairs()\n{\n std::vector<std::string> names;\n std::vector<int> ages;\n\n // read input and populate the vectors\n populate(names, ages);\n\n // print input\n print(names, ages);\n\n // sort pairs\n std::vector<std::string> sortedNames(names);\n std::sort(sortedNames.begin(), sortedNames.end());\n\n std::vector<int> indexMap;\n for(unsigned int i = 0; i < sortedNames.size(); ++i)\n {\n for (unsigned int j = 0; j < names.size(); ++j)\n {\n if (sortedNames[i] == names[j]) \n {\n indexMap.push_back(j);\n break;\n }\n }\n }\n // use the index mapping to match the ages to the names\n std::vector<int> sortedAges;\n for(size_t i = 0; i < indexMap.size(); ++i)\n {\n sortedAges.push_back(ages[indexMap[i]]);\n }\n\n std::cout << \"Ordered pairs:\\n\";\n print(sortedNames, sortedAges); \n}\n populate() print() void populate(std::vector<std::string>& n, std::vector<int>& a)\n{\n std::string prompt(\"Type name and age, separated by white space; 'q' to exit.\\n>>\");\n std::string sentinel = \"q\";\n\n while (true)\n {\n // read input\n std::cout << prompt;\n std::string input;\n getline(std::cin, input);\n\n // exit input loop\n if (input == sentinel)\n {\n break;\n }\n\n std::stringstream ss(input);\n\n // extract input\n std::string name;\n int age;\n if (ss >> name >> age)\n {\n n.push_back(name);\n a.push_back(age);\n }\n else\n {\n std::cout <<\"Wrong input format!\\n\";\n }\n }\n}\n void print(const std::vector<std::string>& n, const std::vector<int>& a)\n{\n if (n.size() != a.size())\n {\n std::cerr <<\"Different number of names and ages!\\n\";\n return;\n }\n\n for (unsigned int i = 0; i < n.size(); ++i)\n {\n std::cout <<'(' << n[i] << \", \" << a[i] << ')' << \"\\n\";\n }\n}\n main() #include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nvoid ordered_pairs();\nvoid populate(std::vector<std::string>&, std::vector<int>&);\nvoid print(const std::vector<std::string>&, const std::vector<int>&);\n\n//=======================================================================\nint main()\n{\n std::cout << \"\\t\\tSimple name - age sorting.\\n\";\n ordered_pairs();\n}\n//=======================================================================\n// Function Definitions...\n"
},
{
"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><h1></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><h1></code> tags, or remove the doctype definition, there is no space (as there should be. Why?</p>
<p>Example HTML:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
body {
margin:0
}
#thediv {
background-color:green
}
</style>
</head>
<body>
<div id="thediv">
<h1>test</h1>
</div>
</body>
</html>
</code></pre>
<p>The problem is the space above the green div, remove the DOCTYPE and the space disappears, change the <code><h1></code> tag to <code><b></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 div h1"
}
] |
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 239.255/16"
}
] |
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 DECLARE @temp TABLE (\n id INT,\n description varchar(50),\n promotionalCode char(1),\n Price smallmoney\n)\n\nINSERT INTO @temp\nselect 1, 'Product 1', 'A', 5\n union\nSELECT 1, 'Product 1', 'B', 4\n union\nSELECT 1, 'Product 1', 'C', 2\n\n\n\nSELECT\n id,\n 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 @temp\nGROUP BY \n id,\n 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 Customer Product Quantity\n Mike Bike 3\n Mike Chain 2\n Mike Bike 5\n Lisa Bike 3\n Lisa Chain 3\n Lisa Chain 4\n SELECT *\n FROM Sales.[Order]\n PIVOT (SUM(Quantity) FOR Product IN ([Bike],[Chain])) AS PVT\n Customer Bike Chain\nLisa 3 7\nMike 8 2\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 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 B.record_id = A.record_id \n AND B.time = (SELECT MAX(time) FROM Table1 C WHERE C.time < A.time AND C.record_id = A.record_id)\n SELECT id, record_id, price, time,\n (SELECT A.price - B.price\n FROM Table1 as B\n WHERE B.record_id = A.record_id AND\n B.time = (SELECT MAX(time) FROM Table1 C WHERE C.time < A.time AND C.record_id = A.record_id)) AS difference\nFROM Table1 as A \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><?php
function toconv(string)
{
$gogo = array("a" => "b","cd" => "e");
$string = str_replace(
array_keys( $gogo ),
array_values( $gogo ),
$string
);
return $string;
}
?>
</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 t u t u null s junk s"
},
{
"answer_id": 8566198,
"author": "Liran",
"author_id": 2164233,
"author_profile": "https://Stackoverflow.com/users/2164233",
"pm_score": 0,
"selected": false,
"text": "Marshal StructLayout unsafe code"
}
] |
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 if ( (int)ageA != (int)idB ) {\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 > 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 int i = 0"
}
] |
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 /Home/Edit/23\n /Home/Edit/Junk\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 routes.MapRoute(\n \"Catchall\",\n \"{*catchall}\", // This is a wildcard routes\n new { controller = \"Home\", action = \"Lost\" }\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 << "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: ";
cout << "\n <r> Give new coefficients";
cout << "\n <c> Calculate equations solutions";
cout << "\n <t> 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 << "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: ";
cout << "\n <r> Give new coefficients";
cout << "\n <c> Calculate equations solutions";
cout << "\n <t> Terminate the program";
cout<<"Enter choice : ";
cin>>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<<"Invalid choice!\n"<<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 cout<<\"Enter choice : \" << std::flush;\n // if( isalpha(choice) )\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) ) r c t default default"
},
{
"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 ~ $ g++ input.cc -o input\n~ $ ./input\n\nQuadratic equation: a*X^2 + b*X + c = 0 main menu:\n <r> Give new coefficients\n <c> Calculate equations solutions\n <t> Terminate the program\nEnter choice : a\nInvalid choice!\n\n\nQuadratic equation: a*X^2 + b*X + c = 0 main menu:\n <r> Give new coefficients\n <c> Calculate equations solutions\n <t> Terminate the program\nEnter choice : c\ngot 'c'\n\nQuadratic equation: a*X^2 + b*X + c = 0 main menu:\n <r> Give new coefficients\n <c> Calculate equations solutions\n <t> Terminate the program\nEnter choice : t\ngot 't'\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 -> 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 However, that would become unwieldy because then the internal API would\nneed to be invoked as self._EventMixin__somePrivateMethod()\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 Session Session ((UserSession) DualContext.Current[\"UserSession\"]).User.Info\n public class DualContext \n{\n private Dictionary<string, object> winFormsSession = new Dictionary<string, object>();\n private static readonly DualContext instance = new DualContext();\n\n public static DualContext Current\n {\n get { return instance; }\n }\n\n public object this[string key]\n {\n get \n {\n if (HttpContext.Current != null)\n return HttpContext.Current.Session[key];\n else\n return winFormsSession[key];\n }\n set \n {\n if (HttpContext.Current != null)\n HttpContext.Current.Session[key] = value;\n else\n winFormsSession[key] = value;\n }\n }\n}\n"
}
] |
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&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 tokens tokens.length()"
}
] |
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() ctype_digit() ┌──────────┬───────────┬────────────────┐\n│ │ is_int: │ ctype_digit: │\n├──────────┼───────────┼────────────────┤\n│ 123 │ true │ false │\n├──────────┼───────────┼────────────────┤\n│ 12.3 │ false │ false │\n├──────────┼───────────┼────────────────┤\n│ \"123\" │ false │ true │\n├──────────┼───────────┼────────────────┤\n│ \"12.3\" │ false │ false │\n├──────────┼───────────┼────────────────┤\n│ \"-1\" │ false │ false │\n├──────────┼───────────┼────────────────┤\n│ -1 │ true │ false │\n└──────────┴───────────┴────────────────┘\n"
},
{
"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 // print table cell and highlight if lowest value is used\nfunction wr($time1, $time2, $time3, $i) {\n if($i == 1) $time = $time1;\n if($i == 2) $time = $time2;\n if($i == 3) $time = $time3;\n\n echo('<td>');\n if(min($time1, $time2, $time3) === $time) printf('<b>%.4f</b>', $time);\n else printf('%.4f', $time);\n echo('</td>');\n}\n\n\n$test_cases = array( 123, 12.3, '123', true);\n$tests = 1000000;\n$result = true; // Used just to make sure cycles won't get optimized out\necho('<table>'.PHP_EOL);\necho('<tr><td> </td><th>is_int</th><th>ctype_digit</th><th>is_numeric</th></tr>');\nforeach($test_cases as $case) {\n echo('<tr><th>'.gettype($case).'</th>');\n\n $time = microtime(true);\n for($i = 0; $i < $tests; $i++) {\n $result |= is_int((int)rand());\n }\n $time1 = microtime(true)-$time;\n\n $time = microtime(true);\n for($i = 0; $i < $tests; $i++) {\n $result |= ctype_digit((int)rand());\n }\n $time2 = microtime(true)-$time;\n\n $time = microtime(true);\n for($i = 0; $i < $tests; $i++) {\n $result |= is_numeric((int)rand());\n }\n $time3 = microtime(true)-$time;\n\n wr($time1, $time2, $time3, 1);\n wr($time1, $time2, $time3, 2);\n wr($time1, $time2, $time3, 3);\n echo('</tr>'.PHP_EOL);\n}\n\necho('</table>');\n\nexit();\n"
},
{
"answer_id": 42679183,
"author": "Nono",
"author_id": 584262,
"author_profile": "https://Stackoverflow.com/users/584262",
"pm_score": 2,
"selected": false,
"text": "is_numeric: 'true' 'false' is_init in_integer intval: -Integer NumberString NumberStringCharacter If String Starts with\n Number ctype_digit true false"
}
] |
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 class MyClass { }\nclass MyClassx extends MyClass { }\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 <applicationSettings>\n <YourAssembly.My.MySettings>\n <setting name=\"DebugMode\" serializeAs=\"String\">\n <value>False</value>\n </setting>\n </YourAssembly.My.MySettings>\n </applicationSettings> \n"
},
{
"answer_id": 236464,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 5,
"selected": true,
"text": "web.config web.config public static class GlobalSettings\n{\n private static string dalConnectionString;\n public static string DALConnectionString\n {\n get\n {\n if (dalConnectionString == null)\n {\n dalConnectionString = WebConfigurationManager\n .ConnectionStrings[\"DALConnectionString\"]\n .ConnectionString;\n }\n return dalConnectionString;\n }\n }\n}\n...\n\nusing (var context = new DALDataContext(GlobalSettings.DALConnectionString))\n{\n ...\n}\n"
},
{
"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 << "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: ";
cout << "\n <r> Give new coefficients";
cout << "\n <c> Calculate equations solutions";
cout << "\n <t> Terminate the program";
cout<<"Enter choice : ";
cin>>mainMenuChoice;
return mainMenuChoice;
}
int main()
{
bool done = false;
while(!done)
{
char choice = displayMainMenu();
switch(tolower(choice))
{
case 'r':
cout<<"Entered case 'r'";
break;
case 'c':
cout<<"Entered case 'c'";
break;
case 't':
cout<<"Entered case 't'";
break;
default:
cout<<"Invalid choice! Try again"<<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:
<r> Give new coefficients
<c> Calculate equations solutions
<t> Terminate the program
Enter choice : ter
Entered case 't'
Quadratic equation: a*X^2 + b*X + c = 0 main menu:
<r> Give new coefficients
<c> Calculate equations solutions
<t> Terminate the program
Enter choice : Invalid choice! Try again
Quadratic equation: a*X^2 + b*X + c = 0 main menu:
<r> Give new coefficients
<c> Calculate equations solutions
<t> 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() char char str[101]\nstd::cin.getline(str, 101);\n cin >> mainMenuChoice;\n"
},
{
"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 LZMA"
},
{
"answer_id": 48366018,
"author": "serv-inc",
"author_id": 1587329,
"author_profile": "https://Stackoverflow.com/users/1587329",
"pm_score": 2,
"selected": false,
"text": "zpaq man zpaq zpaq c archivename.zpaq file1 file2 file3\n"
}
] |
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 (setq ruby-font-lock-syntactic-keywords\n '(\n ;; #{ }, #$hoge, #@foo are not comments\n (\"\\\\(#\\\\)[{$@]\" 1 (1 . nil))\n font-lock-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 find . -name '*.php' | while read filename; do php -l $filename | grep -v 'No syntax errors '; done\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 String \"\" TryGetValue Public Shared Property DictionaryElement(ByVal Key As String) As Object\n Get\n Dim ret As String\n If m_Dictionary.TryGetValue(Key, ret) Then Return ret\n Return \"\" ' Same as String.Empty! '\n End Get\n Set(ByVal value As Object)\n m_Dictionary(Key) = value\n End Set\nEnd Property\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 Public Sub AddOrUpdateKey(ByVal Key As String, ByVal Value as Object)\n If m_Dictionary.ContainsKey(Key) Then\n m_Dictionary(Key) = Value\n Else\n m_Dictionary.Add(Key, Value)\n End If\nEnd Sub\n String.Empty Object String"
},
{
"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 public class ParameterizedProperties\n {\n // Parameterized properties\n private Property<int> m_IntProp = new Property<int>();\n private Property<string> m_StringProp = new Property<string>();\n\n // Parameterized int property accessor for client access\n // (ex: ParameterizedProperties.PublicIntProp[index])\n public Property<int> PublicIntProp\n {\n get { return m_IntProp; }\n }\n\n // Parameterized string property accessor\n // (ex: ParameterizedProperties.PublicStringProp[index])\n public Property<string> PublicStringProp\n {\n get { return m_StringProp; }\n }\n }\n ParameterizedProperties parmProperties = new ParameterizedProperties();\n parmProperties.PublicIntProp[1] = 100;\n parmProperties.PublicStringProp[1] = \"whatever\";\n int ival = parmProperties.PublicIntProp[1];\n string strVal = parmProperties.PublicStringProp[1];\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 C:\\a\\very\\long\\path\nsubst K: \"C:\\a\\very\\long\\path\"\n\nK:\\another\\very\\long\\path\nsubst L: \"K:\\another\\very\\long\\path\"\n\nL:\\yet\\another\\very\\long\\path\nsubst M: \"L:\\yet\\another\\very\\long\\path\"\n\nxcopy M:\\*.* \"D:\\target\"\n subst /d"
},
{
"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__ test.rb puts __FILE__\n /users/foo/test.rb\n __FILE__ File.dirname(__FILE__)\n"
},
{
"answer_id": 51484507,
"author": "David Moles",
"author_id": 27358,
"author_profile": "https://Stackoverflow.com/users/27358",
"pm_score": 2,
"selected": false,
"text": "__dir__ File.dirname(__FILE__)"
}
] |
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<Employee> GetAncestors(int EmployeeId)
{
List<Employee> emps = new List<Employee>();
using (L2STestDataContext dc = new L2STestDataContext())
{
Employee emp = dc.Employees.FirstOrDefault(p => 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 cat list_of_files | xargs svn update\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 --changelist svn update svn update --changelist yourlist\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><div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
</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 descendants"
},
{
"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 <div id=\"mydiv\">\n <h1 class=\"myheader\">Hello</h1>\n</div>\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'; 'header-inner'"
},
{
"answer_id": 236671,
"author": "RogueOne",
"author_id": 31019,
"author_profile": "https://Stackoverflow.com/users/31019",
"pm_score": 1,
"selected": false,
"text": "obj.childNodes list[0] var div = document.getElementById('header-inner');\nvar divTitleWrapper = div.childNodes[0];\nvar h1 = divTitleWrapper.childNodes[0];\n className var h1 = null;\nvar nodeList = divTitleWrapper.childNodes;\nfor (i =0;i < nodeList.length;i++){\n var node = nodeList[i];\n if(node.className == 'title' && node.tagName == 'H1'){\n h1 = node;\n }\n}\n"
},
{
"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 document.querySelector('#header-inner h1').textContent = 'Different text'; <div id='header-inner'> \n <div class='titlewrapper'> \n <h1 class='title'> \n Some text I want to change\n </h1> \n </div> \n</div>"
}
] |
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 ("~~ ^<<<<<<<<<<<<<<<<" 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 ...) (defparameter *english-list*\n \"~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~}\")\n\n(format nil *english-list* '()) ;' ==> \"\"\n(format nil *english-list* '(1)) ;' ==> \"1\"\n(format nil *english-list* '(1 2)) ;' ==> \"1 and 2\"\n(format nil *english-list* '(1 2 3)) ;' ==> \"1, 2, and 3\"\n(format nil *english-list* '(1 2 3 4));' ==> \"1, 2, 3, and 4\"\n"
},
{
"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 Piggy Locations for Sep 18, 2001\n\nNumber: location toe size\n-------------------------------------------\n1) Market 3.50\n2) Home 7.00\n3) Eating Roast Beef 10.50\n4) Having None 14.00\n5) On the way home 17.50\n"
},
{
"answer_id": 237031,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 4,
"selected": false,
"text": "Perl6::Form form format Perl6::Form format Perl6::Form use Perl6::Form;\n\nmy ( $month, $day, $year ) = qw'Sep 18 2001';\nmy ( $num, $numb, $location, $toe_size );\n\nfor ( \"Market\", \"Home\", \"Eating Roast Beef\", \"Having None\", \"On the way home\" ) {\n push @$numb, ++$num;\n push @$location, $_;\n push @$toe_size, $num * 3.5;\n}\n\nprint form\n ' Piggy Locations for {>>>}{>>}, {<<<<}',\n $month, $day, $year ,\n \"\",\n ' Number: location toe size',\n ' --------------------------------------',\n '{]}) {[[[[[[[[[[[[[[[} {].0} ',\n $numb, $location, $toe_size;\n"
}
] |
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;\" width: 100% <div>"
},
{
"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 references"
},
{
"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<Breadcrumb> crumbs = new List<Breadcrumb>();
bool foundCurrent = false;
for (int a = 0; a < cachedCrumbs.Count; a++)
{
crumbs.Add(crumbs[a]);
if (foundCurrent)
{
break;
}
foundCurrent = (crumbs[a + 1] != null && ((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 var crumbs = cachedCrumbs.NewMethod(crumb => crumb == null || !crumb.IsCurrent);\n NewMethod"
},
{
"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 public static IEnumerable<T> TakeUpto<T>(this IList<T> theList, Func<T, bool> predicate)\n{\n var targetItem = theList.First(predicate);\n var targetIdx = theList.IndexOf(targetItem);\n\n return theList.Take(targetIdx + 2);\n}\n var crumbs = cachedCrumbs.TakeUpto(c => c.IsCurrent);\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 IEnumerable<T>"
}
] |
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 image2cga def cga_quantize(image):\n pal_image= Image.new(\"P\", (1,1))\n pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252)\n return image.convert(\"RGB\").quantize(palette=pal_image)\n import itertools as it\n\n# setup: create a map with tuples [(0,0,0,0)‥(3,3,3,3)] as keys\n# and values [chr(0)‥chr(255)], because PIL does not yet support\n# 4 colour palette images\n\nTUPLE2CHAR= {}\n\n# Assume (b7, b6) are pixel0, (b5, b4) are pixel1…\n# Call it \"big endian\"\n\nKEY_BUILDER= [\n (0, 64, 128, 192), # pixel0 value used as index\n (0, 16, 32, 48), # pixel1\n (0, 4, 8, 12), # pixel2\n (0, 1, 2, 3), # pixel3\n]\n# For \"little endian\", uncomment the following line\n## KEY_BUILDER.reverse()\n\n# python2.6 has itertools.product, but for compatibility purposes\n# let's do it verbosely:\nfor ix0, px0 in enumerate(KEY_BUILDER[0]):\n for ix1, px1 in enumerate(KEY_BUILDER[1]):\n for ix2, px2 in enumerate(KEY_BUILDER[2]):\n for ix3, px3 in enumerate(KEY_BUILDER[3]):\n TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3)\n\n# Another helper function, copied almost verbatim from itertools docs\ndef grouper(n, iterable, padvalue=None):\n \"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')\"\n return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n)\n\n# now the functions\ndef seq2str(seq):\n \"\"\"Takes a sequence of [0..3] values and packs them into bytes\n using two bits per value\"\"\"\n return ''.join(\n TUPLE2CHAR[four_pixel]\n for four_pixel in grouper(4, seq, 0))\n\n# and the image related function\n# Note that the following function is correct,\n# but is not useful for Windows 16 colour bitmaps,\n# which start at the *bottom* row…\ndef image2str(img):\n return seq2str(img.getdata())\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> a = "line of text\n line two\n line three"
irb> system("cat > test_file << #{a}")
cat: of: No such file or directory
cat: text: No such file or directory
=> 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 system(\"echo \\\"#{a}\\\" >> test_file\")\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><%= text_field_tag (:filter), "" , :onchange => "alert ('This is a Javascript Alert')" %></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 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 $output = shell_exec('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 String output = GoodWindowsExec.execute(\"dir\");\n import java.util.*;\nimport java.io.*;\nclass StreamGobbler extends Thread\n{\n InputStream is;\n String type;\n StringBuffer output = new StringBuffer();\n\n StreamGobbler(InputStream is, String type)\n {\n this.is = is;\n this.type = type;\n }\n\n public void run()\n {\n try\n {\n InputStreamReader isr = new InputStreamReader(is);\n BufferedReader br = new BufferedReader(isr);\n String line=null;\n while ( (line = br.readLine()) != null)\n System.out.println(type + \">\" + line);\n output.append(line+\"\\r\\n\")\n } catch (IOException ioe)\n {\n ioe.printStackTrace(); \n }\n }\n public String getOutput()\n {\n return this.output.toString();\n }\n}\npublic class GoodWindowsExec\n{\n public static void main(String args[])\n {\n if (args.length < 1)\n {\n System.out.println(\"USAGE: java GoodWindowsExec <cmd>\");\n System.exit(1);\n }\n }\n public static String execute(String aCommand)\n {\n String output = \"\";\n try\n { \n String osName = System.getProperty(\"os.name\" );\n String[] cmd = new String[3];\n if( osName.equals( \"Windows 95\" ) )\n {\n cmd[0] = \"command.com\" ;\n cmd[1] = \"/C\" ;\n cmd[2] = aCommand;\n }\n else if( osName.startsWith( \"Windows\" ) )\n {\n cmd[0] = \"cmd.exe\" ;\n cmd[1] = \"/C\" ;\n cmd[2] = aCommand;\n }\n\n Runtime rt = Runtime.getRuntime();\n System.out.println(\"Executing \" + cmd[0] + \" \" + cmd[1] \n + \" \" + cmd[2]);\n Process proc = rt.exec(cmd);\n // any error message?\n StreamGobbler errorGobbler = new \n StreamGobbler(proc.getErrorStream(), \"ERROR\"); \n\n // any output?\n StreamGobbler outputGobbler = new \n StreamGobbler(proc.getInputStream(), \"OUTPUT\");\n\n // kick them off\n errorGobbler.start();\n outputGobbler.start();\n\n // any error???\n int exitVal = proc.waitFor();\n System.out.println(\"ExitValue: \" + exitVal); \n\n output = outputGobbler.getOutput();\n System.out.println(\"Final output: \" + output); \n\n } catch (Throwable t)\n {\n t.printStackTrace();\n }\n return output;\n }\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 subprocess.check_output() import subprocess\n\ndef cmd_output(args, **kwds):\n kwds.setdefault(\"stdout\", subprocess.PIPE)\n kwds.setdefault(\"stderr\", subprocess.STDOUT)\n p = subprocess.Popen(args, **kwds)\n return p.communicate()[0]\n\nprint cmd_output(\"ls -lt\".split())\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 open my $pipe, '-|', 'ps'\n"
},
{
"answer_id": 241436,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "glibc #define _GNU_SOURCE\n#include <stdio.h>\nint main() {\n char *s = NULL;\n FILE *p = popen(\"ls\", \"r\");\n getdelim(&s, NULL, '\\0', p);\n pclose(p);\n printf(\"%s\", s);\n return 0;\n}\n"
},
{
"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 import System.Cmd.Utils\nmain = do\n (pid, output) <- pipeFrom \"ls\" []\n putStr output\n forceSuccess 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){...} /* File: IOControl.java\n *\n * created: 10 July 2003\n * author: dsm\n */\npackage org.jpop.io;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.io.PrintStream;\n\n/**\n * Controls the I/O for a process. When using the std[in|out|err] streams, they must all be put on\n * different threads to avoid blocking!\n *\n * @author dsm\n * @version 1.5\n */\npublic class IOControl extends Object {\n private Process process;\n private BufferedReader stdout;\n private BufferedReader stderr;\n private PrintStream stdin;\n\n /**\n * Constructor for the IOControl object\n *\n * @param process The process to control I/O for\n */\n public IOControl(Process process) {\n this.process = process;\n this.stdin = new PrintStream(process.getOutputStream());\n this.stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));\n this.stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));\n }\n\n /**\n * Gets the stdin attribute of the IOControl object\n *\n * @return The stdin value\n */\n public PrintStream getStdin() {\n return this.stdin;\n }\n\n /**\n * Gets the stdout attribute of the IOControl object\n *\n * @return The stdout value\n */\n public BufferedReader getStdout() {\n return this.stdout;\n }\n\n /**\n * Gets the stderr attribute of the IOControl object\n *\n * @return The stderr value\n */\n public BufferedReader getStderr() {\n return this.stderr;\n }\n\n /**\n * Gets the process attribute of the IOControl object. To monitor the process (as opposed to\n * just letting it run by itself) its necessary to create a thread like this: <pre>\n *. IOControl ioc;\n *.\n *. new Thread(){\n *. public void run(){\n *. while(true){ // only necessary if you want the process to respawn\n *. try{\n *. ioc = new IOControl(Runtime.getRuntime().exec(\"procname\"));\n *. // add some code to handle the IO streams\n *. ioc.getProcess().waitFor();\n *. }catch(InterruptedException ie){\n *. // deal with exception\n *. }catch(IOException ioe){\n *. // deal with exception\n *. }\n *.\n *. // a break condition can be included here to terminate the loop\n *. } // only necessary if you want the process to respawn\n *. }\n *. }.start();\n * </pre>\n *\n * @return The process value\n */\n public Process getProcess() {\n return this.process;\n }\n}\n"
},
{
"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 IPC::Run"
},
{
"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 import java.io.*;\n\npublic class Test { \n public static void main ( String [] args ) throws IOException { \n String result = execute( args[0] );\n System.out.println( result );\n }\n private static String execute( String command ) throws IOException { \n Process p = Runtime.getRuntime().exec( \"cmd /c \" + command );\n InputStream i = p.getInputStream();\n StringBuilder sb = new StringBuilder();\n for( int c = 0 ; ( c = i.read() ) > -1 ; ) {\n sb.append( ( char ) c );\n }\n i.close();\n return sb.toString();\n }\n}\n C:\\oreyes\\samples\\java\\readinput>java Test \"type hello.txt\"\nThis is a sample file\nwith some\nlines\n C:\\oreyes\\samples\\java\\readinput>java Test \"dir\"\n El volumen de la unidad C no tiene etiqueta.\n El número de serie del volumen es:\n\n Directorio de C:\\oreyes\\samples\\java\\readinput\n\n12/16/2008 05:51 PM <DIR> .\n12/16/2008 05:51 PM <DIR> ..\n12/16/2008 05:50 PM 42 hello.txt\n12/16/2008 05:38 PM 1,209 Test.class\n12/16/2008 05:47 PM 682 Test.java\n 3 archivos 1,933 bytes\n 2 dirs 840 bytes libres\n java Test netstat\njava Test tasklist\njava Test \"taskkill /pid 416\"\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 (execute \"cat\" '(\"/etc/hosts\"))\n (execute \"big-writer\" '(\"some\" \"parameters\") 1000000)\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 (with-output-to-string (*standard-output*)\n (sys:call-system-showing-output \"ls -l\" :prefix \"\" :show-cmd nil))\n"
}
] |
2008/10/25
|
[
"https://Stackoverflow.com/questions/236737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.